diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/pom.xml b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/pom.xml index 5bbb149f5a..b5c5bd3ac2 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/pom.xml +++ b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/pom.xml @@ -37,10 +37,7 @@ maven-compiler-plugin - - 1.8 - 1.8 - + maven-war-plugin @@ -61,7 +58,6 @@ org.apache.maven.plugins maven-antrun-plugin - 1.7 compile @@ -97,9 +93,8 @@ provided - org.apache.cxf + org.apache.cxf.wso2 cxf-bundle - 3.0.0-milestone2 test @@ -133,8 +128,8 @@ - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api provided @@ -299,7 +294,7 @@ org.powermock - powermock-api-mockito + powermock-api-mockito2 test @@ -333,6 +328,11 @@ io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common provided + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.application.mgt.common + provided + diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/GrafanaAPIProxyService.java b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/GrafanaAPIProxyService.java index 5bdf335d30..b33671879d 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/GrafanaAPIProxyService.java +++ b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/GrafanaAPIProxyService.java @@ -18,25 +18,12 @@ package io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api; import com.google.gson.JsonObject; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; +import io.swagger.annotations.*; + +import javax.ws.rs.*; +import javax.ws.rs.core.*; @SwaggerDefinition( info = @Info( diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/addons/ApiOriginFilter.java b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/addons/ApiOriginFilter.java index 59c2fccc32..2a336fa4c4 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/addons/ApiOriginFilter.java +++ b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/addons/ApiOriginFilter.java @@ -18,12 +18,7 @@ package io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api.addons; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/addons/ValidationInterceptor.java b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/addons/ValidationInterceptor.java index b4078f20d6..dcd75926bd 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/addons/ValidationInterceptor.java +++ b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/addons/ValidationInterceptor.java @@ -28,11 +28,7 @@ import org.apache.cxf.message.MessageContentsList; import org.apache.cxf.phase.AbstractPhaseInterceptor; import org.apache.cxf.phase.Phase; -import javax.validation.ConstraintViolation; -import javax.validation.ConstraintViolationException; -import javax.validation.Validation; -import javax.validation.Validator; -import javax.validation.ValidatorFactory; +import javax.validation.*; import javax.validation.executable.ExecutableValidator; import java.lang.reflect.Method; import java.util.List; diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/impl/GrafanaAPIProxyServiceImpl.java b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/impl/GrafanaAPIProxyServiceImpl.java index 92eed32c74..62523bb483 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/impl/GrafanaAPIProxyServiceImpl.java +++ b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/impl/GrafanaAPIProxyServiceImpl.java @@ -29,9 +29,9 @@ import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.bean.GrafanaPa import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config.GrafanaConfiguration; import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config.GrafanaConfigurationManager; import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.exception.MaliciousQueryAttempt; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DBConnectionException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DBConnectionException; import javax.ws.rs.Consumes; import javax.ws.rs.GET; diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/impl/util/GrafanaRequestHandlerUtil.java b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/impl/util/GrafanaRequestHandlerUtil.java index e94b3ccf53..b582c3b11a 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/impl/util/GrafanaRequestHandlerUtil.java +++ b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/api/impl/util/GrafanaRequestHandlerUtil.java @@ -27,6 +27,8 @@ import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config.Grafana import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.exception.GrafanaEnvVariablesNotDefined; import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.util.GrafanaConstants; import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.util.GrafanaUtil; +import io.entgra.device.mgt.core.device.mgt.core.common.util.HttpUtil; +import io.entgra.device.mgt.core.device.mgt.core.report.mgt.Constants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpResponse; @@ -37,8 +39,6 @@ import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; -import io.entgra.device.mgt.core.device.mgt.core.common.util.HttpUtil; -import io.entgra.device.mgt.core.device.mgt.core.report.mgt.Constants; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common/pom.xml b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common/pom.xml index fe168409c7..b2a6031989 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common/pom.xml +++ b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common/pom.xml @@ -35,6 +35,14 @@ + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + org.apache.felix maven-bundle-plugin @@ -48,12 +56,6 @@ io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common.* - - javax.xml.bind.annotation; version="${javax.xml.bind.imp.pkg.version}", - com.fasterxml.jackson.annotation;version="${jackson-annotations.version}", - io.swagger.annotations; version="${swagger.annotations.version}"; resolution:=optional, - com.google.gson - diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/pom.xml b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/pom.xml index e1d23b0dd4..4199ff7273 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/pom.xml +++ b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/pom.xml @@ -35,10 +35,6 @@ - - org.apache.felix - maven-scr-plugin - org.jacoco jacoco-maven-plugin @@ -65,6 +61,14 @@ + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + org.apache.felix maven-bundle-plugin @@ -77,15 +81,47 @@ Grafana API Management Core Bundle io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.internal - io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common.*, - javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, - javax.xml.bind.annotation, - javax.xml.bind, - org.apache.commons.lang, - org.wso2.carbon, - io.entgra.device.mgt.core.device.mgt.common.*, - io.entgra.device.mgt.core.device.mgt.core.* - io.entgra.device.mgt.core.application.mgt.core.* + com.google.common.cache;version="[32.1,33)";resolution:=optional, + com.google.gson;version="[2.9,3)", + io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common.exception;version="[5.0,6)", + io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.bean, + io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config, + io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config.xml.bean, + io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.exception, + io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.service, + io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.service.bean, + io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.service.cache, + io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.service.impl, + io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.sql.connection, + io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.sql.query, + io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.sql.query.encoder, + io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.util, + io.entgra.device.mgt.core.application.mgt.common.exception;version="[5.0,6)", + io.entgra.device.mgt.core.application.mgt.core.config;version="[5.0,6)", + io.entgra.device.mgt.core.application.mgt.core.util;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.exceptions;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.common.util;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.config;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.config.datasource;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.dao;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.report.mgt.config;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.report.mgt.dao.common;version="[5.0,6)", + javax.xml.bind;version="[0.0,1)", + javax.xml.bind.annotation;version="[0.0,1)", + javax.xml.parsers, + org.apache.commons.codec.binary;version="[1.4,2)", + org.apache.commons.lang;version="[2.6,3)", + org.apache.commons.lang3;version="[3.11,4)", + org.apache.commons.logging;version="[1.2,2)", + org.apache.http;version="[4.4,5)", + org.apache.http.client, + org.apache.http.client.methods, + org.apache.http.impl.client, + org.apache.juli.logging;version="[9.0,10)", + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", + org.w3c.dom,org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.utils;version="[4.8,5)" !io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.internal, @@ -103,28 +139,31 @@ - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services + org.apache.felix + org.apache.felix.scr.ds-annotations + provided - org.wso2.orbit.org.scannotation + io.entgra.org.scannotation scannotation io.entgra.device.mgt.core io.entgra.device.mgt.core.device.mgt.common + provided + + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.application.mgt.common + provided org.wso2.carbon org.wso2.carbon.utils - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api provided @@ -139,6 +178,12 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.device.mgt.core + + + com.google.guava + guava + + io.entgra.device.mgt.core @@ -147,17 +192,22 @@ org.apache.httpcomponents.wso2 httpclient - 4.1.1.wso2v1 compile - org.apache.httpcomponents - httpclient + org.apache.httpcomponents.client5 + httpclient5 io.entgra.device.mgt.core io.entgra.device.mgt.core.identity.jwt.client.extension provided + + + com.google.guava + guava + + javax.ws.rs @@ -173,7 +223,7 @@ org.powermock - powermock-api-mockito + powermock-api-mockito2 org.wso2.carbon @@ -191,8 +241,8 @@ provided - com.h2database.wso2 - h2-database-engine + org.wso2.orbit.com.h2database + h2 test @@ -221,7 +271,7 @@ org.wso2.carbon.registry.core - org.apache.tomcat.wso2 + org.wso2.orbit.org.apache.tomcat jdbc-pool @@ -240,14 +290,6 @@ org.apache.ws.commons.axiom.wso2 axiom - org.apache.axis2.wso2 axis2 @@ -257,11 +299,11 @@ org.wso2.carbon.identity.oauth.stub - org.wso2.tomcat + org.wso2.orbit.org.apache.tomcat tomcat - org.wso2.tomcat + org.wso2.orbit.org.apache.tomcat tomcat-servlet-api @@ -276,23 +318,19 @@ commons-collections.wso2 commons-collections - io.entgra.device.mgt.core io.entgra.device.mgt.core.transport.mgt.email.sender.core - mysql mysql-connector-java test - com.google.code.gson gson - io.swagger swagger-annotations @@ -321,9 +359,12 @@ com.google.guava guava + provided + + + org.wso2.orbit.javax.xml.bind + jaxb-api + provided - - - diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/core/internal/GrafanaManagementServiceComponent.java b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/core/internal/GrafanaManagementServiceComponent.java index cc4ab33920..8d53ce7ab3 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/core/internal/GrafanaManagementServiceComponent.java +++ b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/src/main/java/io/entgra/device/mgt/core/analytics/mgt/grafana/proxy/core/internal/GrafanaManagementServiceComponent.java @@ -26,15 +26,19 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; -/** - * @scr.component name="io.entgra.analytics.mgt.grafana.proxy.grafanamanagementservicecomponent" immediate="true" - */ +@Component( + name = "io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.internal.GrafanaManagementServiceComponent", + immediate = true) public class GrafanaManagementServiceComponent { private static Log log = LogFactory.getLog(GrafanaManagementServiceComponent.class); @SuppressWarnings("unused") + @Activate protected void activate(ComponentContext componentContext) { try { if (log.isDebugEnabled()) { @@ -59,6 +63,7 @@ public class GrafanaManagementServiceComponent { } @SuppressWarnings("unused") + @Deactivate protected void deactivate(ComponentContext componentContext) { if (log.isDebugEnabled()) { log.debug("De-activating Grafana Management Service Component"); diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/pom.xml index 0644c29899..866cb6ce57 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/pom.xml @@ -27,9 +27,14 @@ io.entgra.device.mgt.core.apimgt.analytics.extension bundle Entgra - API mgt analytics extension - http://wso2.org + https://entgra.io + + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + org.wso2.carbon org.wso2.carbon.core @@ -40,8 +45,7 @@ org.apache.velocity - velocity - 1.7 + velocity-engine-core @@ -57,8 +61,12 @@ - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -73,10 +81,11 @@ io.entgra.device.mgt.core.apimgt.application.extension.internal io.entgra.device.mgt.core.apimgt.analytics.extension.dto, + io.entgra.device.mgt.core.apimgt.analytics.extension.exception, org.apache.velocity, org.apache.velocity.app, org.apache.velocity.context, - org.wso2.carbon.utils;version="[4.6,5)" + org.wso2.carbon.utils;version="[4.8,5)" io.entgra.device.mgt.core.apimgt.analytics.extension.* diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/AnalyticsArtifactsDeployer.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/AnalyticsArtifactsDeployer.java index ce92682a23..8d7e273633 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/AnalyticsArtifactsDeployer.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/AnalyticsArtifactsDeployer.java @@ -27,16 +27,11 @@ import io.entgra.device.mgt.core.apimgt.analytics.extension.exception.EventStrea import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; - import org.apache.velocity.runtime.RuntimeConstants; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; +import java.io.*; public class AnalyticsArtifactsDeployer { diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.annotations/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.annotations/pom.xml index 5386164088..fba5591029 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.annotations/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.annotations/pom.xml @@ -31,20 +31,18 @@ bundle WSO2 Carbon - API Management Annotations WSO2 Carbon - API Management Custom Annotation Module - http://wso2.org + https://entgra.io - org.eclipse.osgi - org.eclipse.osgi + org.apache.felix + org.apache.felix.scr.ds-annotations + provided - org.eclipse.osgi - org.eclipse.osgi.services - - - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api + provided javax.ws.rs @@ -54,13 +52,16 @@ - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix maven-bundle-plugin - 1.4.0 true @@ -71,15 +72,6 @@ io.entgra.device.mgt.core.apimgt.annotations.* - - org.osgi.framework.*;version="${imp.package.version.osgi.framework}", - org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.apache.commons.logging, - javax.servlet, - javax.xml.*, - javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, - org.apache.commons.lang - scribe;scope=compile|runtime;inline=false; diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/pom.xml index 0431e96880..4be52ce94d 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/pom.xml @@ -30,7 +30,7 @@ war WSO2 Carbon - API Application Management API This module provides capability to create api manager application. - http://wso2.org + https://entgra.io @@ -164,16 +164,12 @@ + org.apache.maven.plugins maven-compiler-plugin - - UTF-8 - ${wso2.maven.compiler.source} - ${wso2.maven.compiler.target} - + org.apache.maven.plugins maven-war-plugin - 2.2 ${project.artifactId} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java index 687fe5be5e..2dd6e523f0 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java @@ -18,18 +18,18 @@ package io.entgra.device.mgt.core.apimgt.application.extension.api; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService; import io.entgra.device.mgt.core.apimgt.application.extension.api.util.APIUtil; import io.entgra.device.mgt.core.apimgt.application.extension.api.util.RegistrationProfile; import io.entgra.device.mgt.core.apimgt.application.extension.constants.ApiApplicationConstants; import io.entgra.device.mgt.core.apimgt.application.extension.dto.ApiApplicationKey; import io.entgra.device.mgt.core.apimgt.application.extension.exception.APIManagerException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.user.api.UserStoreException; import javax.ws.rs.POST; @@ -64,7 +64,8 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( applicationName, APIUtil.getDefaultTags(), ApiApplicationConstants.DEFAULT_TOKEN_TYPE, username, false, - ApiApplicationConstants.DEFAULT_VALIDITY_PERIOD); + ApiApplicationConstants.DEFAULT_VALIDITY_PERIOD, PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() + .getRealmConfiguration().getAdminPassword(), null, null, null, false); return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build(); } catch (APIManagerException e) { String msg = "Error occurred while registering an application '" + applicationName + "'"; @@ -110,7 +111,9 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( applicationName, registrationProfile.getTags(), ApiApplicationConstants.DEFAULT_TOKEN_TYPE, username, - registrationProfile.isAllowedToAllDomains(), validityPeriod); + registrationProfile.isAllowedToAllDomains(), validityPeriod, + registrationProfile.getPassword(), null, registrationProfile.getSupportedGrantTypes(), + registrationProfile.getCallbackUrl(), false); return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build(); } } @@ -122,7 +125,9 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( applicationName, registrationProfile.getTags(), ApiApplicationConstants.DEFAULT_TOKEN_TYPE, registrationProfile.getUsername(), - registrationProfile.isAllowedToAllDomains(), validityPeriod); + registrationProfile.isAllowedToAllDomains(), validityPeriod, + registrationProfile.getPassword(), null, registrationProfile.getSupportedGrantTypes(), + registrationProfile.getCallbackUrl(), false); return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build(); } } catch (APIManagerException e) { diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/filter/ApiPermissionFilter.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/filter/ApiPermissionFilter.java index 3db47a1f16..50bab8861f 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/filter/ApiPermissionFilter.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/filter/ApiPermissionFilter.java @@ -17,20 +17,15 @@ */ package io.entgra.device.mgt.core.apimgt.application.extension.api.filter; +import io.entgra.device.mgt.core.apimgt.application.extension.api.util.APIUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.apimgt.application.extension.api.util.APIUtil; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.bind.JAXBContext; diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/util/APIUtil.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/util/APIUtil.java index 3c35514c40..9a4702cdcb 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/util/APIUtil.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/util/APIUtil.java @@ -18,13 +18,13 @@ package io.entgra.device.mgt.core.apimgt.application.extension.api.util; +import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.registry.api.Resource; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.exceptions.RegistryException; diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/util/RegistrationProfile.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/util/RegistrationProfile.java index 3e3eb30a03..921b27f434 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/util/RegistrationProfile.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/util/RegistrationProfile.java @@ -22,6 +22,7 @@ import org.codehaus.jackson.annotate.JsonIgnoreProperties; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; +import java.util.ArrayList; /** * DTO class to be used when registering an ApiM application. @@ -43,6 +44,10 @@ public class RegistrationProfile { @XmlElement(required = false) private String validityPeriod; + private String callbackUrl; + + private ArrayList supportedGrantTypes; + public String getApplicationName() { return applicationName; } @@ -90,4 +95,20 @@ public class RegistrationProfile { public void setPassword(String password) { this.password = password; } + + public String getCallbackUrl() { + return callbackUrl; + } + + public void setCallbackUrl(String callbackUrl) { + this.callbackUrl = callbackUrl; + } + + public ArrayList getSupportedGrantTypes() { + return supportedGrantTypes; + } + + public void setSupportedGrantTypes(ArrayList supportedGrantTypes) { + this.supportedGrantTypes = supportedGrantTypes; + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/pom.xml index b0af3744db..fdf9c2dd68 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/pom.xml @@ -31,9 +31,14 @@ bundle WSO2 Carbon - API Application Management This module provides capability to create api manager application. - http://wso2.org + https://entgra.io + + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + org.wso2.carbon org.wso2.carbon.registry.core @@ -47,8 +52,9 @@ org.wso2.carbon.utils - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api + provided org.wso2.carbon.apimgt @@ -72,6 +78,17 @@ io.entgra.device.mgt.core.identity.jwt.client.extension provided + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.apimgt.extension.rest.api + + + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.device.mgt.common + + + @@ -86,8 +103,12 @@ - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -101,30 +122,32 @@ API Management Application Bundle io.entgra.device.mgt.core.apimgt.application.extension.internal + io.entgra.device.mgt.core.apimgt.application.extension.bean, + io.entgra.device.mgt.core.apimgt.application.extension.dto, + io.entgra.device.mgt.core.apimgt.application.extension.exception, + io.entgra.device.mgt.core.identity.jwt.client.extension;version="[5.0,6)", + io.entgra.device.mgt.core.identity.jwt.client.extension.dto;version="[5.0,6)", + io.entgra.device.mgt.core.identity.jwt.client.extension.exception;version="[5.0,6)", + io.entgra.device.mgt.core.identity.jwt.client.extension.service;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", org.apache.commons.lang;version="[2.6,3)", org.apache.commons.logging;version="[1.2,2)", - org.json.simple, + org.json.simple;version="[1.1,2)", org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.wso2.carbon.apimgt.api;version="${carbon.api.mgt.version.range}", - org.wso2.carbon.apimgt.api.dto;version="${carbon.api.mgt.version.range}", - org.wso2.carbon.apimgt.api.model;version="${carbon.api.mgt.version.range}", - io.entgra.device.mgt.core.apimgt.application.extension.bean, - io.entgra.device.mgt.core.apimgt.application.extension.dto, - io.entgra.device.mgt.core.apimgt.application.extension.exception, - org.wso2.carbon.apimgt.impl;version="${carbon.api.mgt.version.range}", - org.wso2.carbon.apimgt.impl.utils;version="${carbon.api.mgt.version.range}", - org.wso2.carbon.context;version="${carbon.kernel.version.range}", - io.entgra.device.mgt.core.identity.jwt.client.extension, - io.entgra.device.mgt.core.identity.jwt.client.extension.dto, - io.entgra.device.mgt.core.identity.jwt.client.extension.exception, - io.entgra.device.mgt.core.identity.jwt.client.extension.service, + io.entgra.device.mgt.core.apimgt.extension.rest.api, + org.wso2.carbon.apimgt.api;version="[9.28,10)", + org.wso2.carbon.apimgt.api.dto;version="[9.28,10)", + org.wso2.carbon.apimgt.api.model;version="[9.28,10)", + org.wso2.carbon.apimgt.impl;version="[9.28,10)", + org.wso2.carbon.apimgt.impl.utils;version="[9.28,10)", + org.wso2.carbon.context;version="[4.8,5)", org.wso2.carbon.registry.core.exceptions;version="[1.0,2)", org.wso2.carbon.registry.core.service;version="[1.0,2)", - org.wso2.carbon.registry.indexing.service;version="${carbon.registry.imp.pkg.version.range}", + org.wso2.carbon.registry.indexing.service;version="[4.8,5)", org.wso2.carbon.user.api;version="[1.0,2)", - org.wso2.carbon.user.core.service;version="${carbon.kernel.version.range}", - org.wso2.carbon.user.core.tenant;version="${carbon.kernel.version.range}" + org.wso2.carbon.user.core.service;version="[4.8,5)", + org.wso2.carbon.user.core.tenant;version="[4.8,5)" !io.entgra.device.mgt.core.apimgt.application.extension.internal, diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderService.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderService.java index a46dc715b7..589923a920 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderService.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderService.java @@ -22,6 +22,8 @@ import io.entgra.device.mgt.core.apimgt.application.extension.dto.ApiApplication import io.entgra.device.mgt.core.apimgt.application.extension.exception.APIManagerException; import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.AccessTokenInfo; +import java.util.ArrayList; + /** * This comprise on operation that is been done with api manager from CDMF. This service needs to be implemented in APIM. */ @@ -33,27 +35,14 @@ public interface APIManagementProviderService { */ boolean isTierLoaded(); - /** - * Generate and retreive application keys. if the application does exist then - * create it and subscribe to apis that are grouped with the tags. - * - * @param apiApplicationName name of the application. - * @param tags tags of the apis that application needs to be subscribed. - * @param keyType of the application. - * @param username to whom the application is created - * @param isAllowedAllDomains application is allowed to all the tenants - * @param validityTime validity period of the application - * @return consumerkey and secrete of the created application. - * @throws APIManagerException - */ - ApiApplicationKey generateAndRetrieveApplicationKeys(String apiApplicationName, String tags[], - String keyType, String username, boolean isAllowedAllDomains, - String validityTime) throws APIManagerException; - - /** - * Remove APIM Application. - */ - void removeAPIApplication(String applicationName, String username) throws APIManagerException; + ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String[] tags, + String keyType, String username, + boolean isAllowedAllDomains, + String validityTime, + String password, String accessToken, + ArrayList supportedGrantTypes, + String callbackUrl, + boolean isMappingRequired) throws APIManagerException; /** * To get access token for given scopes and for the given validity period diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderServiceImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderServiceImpl.java index add97f7a25..3e612e5838 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderServiceImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderServiceImpl.java @@ -18,42 +18,47 @@ package io.entgra.device.mgt.core.apimgt.application.extension; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.apimgt.api.APIAdmin; -import org.wso2.carbon.apimgt.api.APIConsumer; -import org.wso2.carbon.apimgt.api.APIManagementException; -import org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO; -import org.wso2.carbon.apimgt.api.model.API; -import org.wso2.carbon.apimgt.api.model.APIKey; -import org.wso2.carbon.apimgt.api.model.ApiTypeWrapper; -import org.wso2.carbon.apimgt.api.model.Application; -import org.wso2.carbon.apimgt.api.model.SubscribedAPI; -import org.wso2.carbon.apimgt.api.model.Subscriber; import io.entgra.device.mgt.core.apimgt.application.extension.bean.APIRegistrationProfile; -import io.entgra.device.mgt.core.apimgt.application.extension.constants.ApiApplicationConstants; import io.entgra.device.mgt.core.apimgt.application.extension.dto.ApiApplicationKey; import io.entgra.device.mgt.core.apimgt.application.extension.exception.APIManagerException; import io.entgra.device.mgt.core.apimgt.application.extension.internal.APIApplicationManagerExtensionDataHolder; -import io.entgra.device.mgt.core.apimgt.application.extension.util.APIManagerUtil; -import org.wso2.carbon.apimgt.impl.APIAdminImpl; -import org.wso2.carbon.apimgt.impl.APIConstants; -import org.wso2.carbon.apimgt.impl.APIManagerFactory; -import org.wso2.carbon.apimgt.impl.utils.APIUtil; -import org.wso2.carbon.context.PrivilegedCarbonContext; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.APIInfo; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.ApplicationKey; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.KeyManager; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Subscription; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataKeyAlreadyExistsException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; import io.entgra.device.mgt.core.identity.jwt.client.extension.JWTClient; import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.AccessTokenInfo; import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.ApiApplicationInfo; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.APIManagerFactory; +import org.wso2.carbon.apimgt.impl.utils.APIUtil; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import java.util.ArrayList; -import java.util.HashSet; +import java.util.Arrays; +import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Set; +import java.util.Objects; +import java.util.Optional; /** * This class represents an implementation of APIManagementProviderService. @@ -62,6 +67,7 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe private static final Log log = LogFactory.getLog(APIManagementProviderServiceImpl.class); public static final APIManagerFactory API_MANAGER_FACTORY = APIManagerFactory.getInstance(); + private static final String UNLIMITED_TIER = "Unlimited"; @Override public boolean isTierLoaded() { @@ -79,219 +85,235 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe } @Override - public void removeAPIApplication(String applicationName, String username) throws APIManagerException { + public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String[] tags, + String keyType, String username, + boolean isAllowedAllDomains, + String validityTime, + String password, String accessToken, + ArrayList supportedGrantTypes, + String callbackUrl, + boolean isMappingRequired) + throws APIManagerException { - try { - APIConsumer apiConsumer = API_MANAGER_FACTORY.getAPIConsumer(username); - Application application = apiConsumer.getApplicationsByName(username, applicationName, ""); - if (application != null) { - apiConsumer.removeApplication(application, username); - } - } catch (APIManagementException e) { - throw new APIManagerException("Failed to remove api application : " + applicationName, e); + ApiApplicationInfo apiApplicationInfo = new ApiApplicationInfo(); + if (StringUtils.isEmpty(accessToken)) { + apiApplicationInfo = getApplicationInfo(username, password); + } else { + apiApplicationInfo.setAccess_token(accessToken); } + ConsumerRESTAPIServices consumerRESTAPIServices = + APIApplicationManagerExtensionDataHolder.getInstance().getConsumerRESTAPIServices(); - } + try { + Map headerParams = new HashMap<>(); + if (!"carbon.super".equals(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true))) { + headerParams.put("X-WSO2-Tenant", "carbon.super"); + } - /** - * {@inheritDoc} - */ - @Override - public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String tags[], - String keyType, String username, boolean isAllowedAllDomains, String validityTime) - throws APIManagerException { + Map uniqueApiSet = new HashMap<>(); + if (tags != null) { + for (String tag : tags) { + Map queryParams = new HashMap<>(); + queryParams.put("tag", tag); - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - if (StringUtils.isEmpty(username)) { - username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername() + "@" + tenantDomain; - } - try { - APIConsumer apiConsumer = API_MANAGER_FACTORY.getAPIConsumer(username); - Application application = apiConsumer.getApplicationsByName(username, applicationName, ""); - - int applicationId = 0; - Subscriber subscriber = null; - if (application == null) { - subscriber = apiConsumer.getSubscriber(username); - if (subscriber == null) { - // create subscriber - apiConsumer.addSubscriber(username, ""); - subscriber = apiConsumer.getSubscriber(username); + APIInfo[] apiInfos = consumerRESTAPIServices.getAllApis(apiApplicationInfo, queryParams, headerParams); + Arrays.stream(apiInfos).forEach(apiInfo -> uniqueApiSet.putIfAbsent(apiInfo.getName(), apiInfo)); } - //create application - application = new Application(applicationName, subscriber); - application.setTier(ApiApplicationConstants.DEFAULT_TIER); - application.setGroupId(""); - application.setTokenType("OAUTH"); - apiConsumer.addApplication(application, username); - application = apiConsumer.getApplicationsByName(username, applicationName, ""); - } else { - subscriber = apiConsumer.getSubscriber(username); } - Set subscribedAPIs = - apiConsumer.getSubscribedAPIs(subscriber, applicationName, ""); + List uniqueApiList = new ArrayList<>(uniqueApiSet.values()); - log.info("Already subscribed API count: " + subscribedAPIs.size()); - - // subscribe to apis. - Set tempApiIds = new HashSet<>(); - APIConsumer apiConsumerAPIPublishedTenant = apiConsumer; - if (tags != null && tags.length > 0) { - for (String tag : tags) { - boolean startedTenantFlow = false; - Set apisWithTag = apiConsumer.getAPIsWithTag(tag, tenantDomain); - - /** - * From APIM 4.0.0, APIs published in the super tenant can only be listed by - * APIConsumer, only if the APIConsumer belongs to the super tenant. So we - * are starting tenant flow if we are not already in super tenant(child - * tenant starting to create OAuth app). - */ - if (apisWithTag == null || apisWithTag.size() == 0) { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, - true); - - try { - String superAdminUsername = PrivilegedCarbonContext - .getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration().getAdminUserName(); - apiConsumerAPIPublishedTenant = API_MANAGER_FACTORY.getAPIConsumer(superAdminUsername); - } catch (UserStoreException e) { - throw new APIManagerException("Failed to create api application for " + - "tenant: " + tenantDomain + - ". Caused by to inability to get super tenant username", e); + io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application[] applications = + consumerRESTAPIServices.getAllApplications(apiApplicationInfo, applicationName); + if (applications.length == 0) { + return handleNewAPIApplication(applicationName, uniqueApiList, apiApplicationInfo, keyType, + validityTime, supportedGrantTypes, callbackUrl, isMappingRequired); + } else { + if (applications.length == 1) { + Optional applicationOpt = + Arrays.stream(applications).findFirst(); + io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application = + applicationOpt.get(); + + MetadataManagementService metadataManagementService = APIApplicationManagerExtensionDataHolder.getInstance().getMetadataManagementService(); + Metadata metaData = metadataManagementService.retrieveMetadata(applicationName); + if (metaData == null) { + // Todo add a comment + consumerRESTAPIServices.deleteApplication(apiApplicationInfo, application.getApplicationId()); + return handleNewAPIApplication(applicationName, uniqueApiList, apiApplicationInfo, keyType, + validityTime, supportedGrantTypes, callbackUrl, isMappingRequired); + } else { + Subscription[] subscriptions = consumerRESTAPIServices.getAllSubscriptions(apiApplicationInfo, application.getApplicationId()); + for (Subscription subscription : subscriptions) { + uniqueApiList.removeIf(apiInfo -> Objects.equals(apiInfo.getId(), subscription.getApiInfo().getId())); } - apisWithTag = apiConsumerAPIPublishedTenant.getAPIsWithTag(tag, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - startedTenantFlow = true; - } - - Set apiTypeWrapperList = new HashSet<>(); - if (apisWithTag != null && apisWithTag.size() > 0) { - for (API apiInfo : apisWithTag) { - String id = apiInfo.getId().getProviderName().replace("@", "-AT-") - + "-" + apiInfo.getId().getName() + "-" + apiInfo.getId().getVersion(); - boolean subscriptionExist = false; - if (subscribedAPIs.size() > 0) { - for (SubscribedAPI subscribedAPI : subscribedAPIs) { - if (String.valueOf(subscribedAPI.getApiId().toString()).equals(id)) { - subscriptionExist = true; - break; - } - } - } - if (!subscriptionExist && !tempApiIds.contains(id)) { - ApiTypeWrapper apiTypeWrapper; - if (startedTenantFlow) { - /** - * This mean APIs were not found in the child tenant, so all - * calls to get info about APIs need to be to super tenant. - */ - apiTypeWrapper = apiConsumerAPIPublishedTenant.getAPIorAPIProductByUUID( - apiInfo.getUuid(), MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - } else { - /** - * Ideally, in all usecases of IoT server, tenant domain here - * will be carbon.super. This block is kept to make sure in - * the future, if there are some APIs published to a specific - * tenant only. - */ - apiTypeWrapper = apiConsumerAPIPublishedTenant.getAPIorAPIProductByUUID( - apiInfo.getUuid(), tenantDomain); - } - apiTypeWrapper.setTier(ApiApplicationConstants.DEFAULT_TIER); - apiTypeWrapperList.add(apiTypeWrapper); - tempApiIds.add(id); - } - } - if (startedTenantFlow) { - PrivilegedCarbonContext.endTenantFlow(); + if (!uniqueApiList.isEmpty()) { + addSubscriptions(application, uniqueApiList, apiApplicationInfo); } - /** This is done in a redundant loop instead of doing in the same loop - * that populates apiTypeWrapperList because in a tenanted scenario, - * apiConsumerAPIPublishedTenant will belong to super tenant. So super - * tenant flow need to end before starting subscription to avoid adding - * subscriptions inside super tenant when we are trying to create an - * Oauth app for a child tenant. - */ - for (ApiTypeWrapper apiTypeWrapper : apiTypeWrapperList) { - apiConsumer.addSubscription(apiTypeWrapper, username, application); - } - } - } - } - //end of subscription - - List applicationKeys = application.getKeys(); - if (applicationKeys != null) { - for (APIKey applicationKey : applicationKeys) { - if (keyType.equals(applicationKey.getType())) { - if (applicationKey.getConsumerKey() != null && !applicationKey.getConsumerKey().isEmpty()) { - ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); - apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey()); - apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret()); - return apiApplicationKey; + String[] metaValues = metaData.getMetaValue().split(":"); + if (metaValues.length != 2) { + String msg = "Found invalid Meta value for meta key: " + applicationName + ". Meta Value: " + + metaData.getMetaValue(); + log.error(msg); + throw new APIManagerException(msg); } + String applicationId = metaValues[0]; + String keyMappingId = metaValues[1]; + ApplicationKey applicationKey = consumerRESTAPIServices.getKeyDetails(apiApplicationInfo, applicationId, keyMappingId); + ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); + apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey()); + apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret()); + return apiApplicationKey; } + } else { + String msg = "Found more than one application for application name: " + applicationName; + log.error(msg); + throw new APIManagerException(msg); } } + } catch (APIServicesException e) { + String msg = "Error occurred while processing the response of APIM REST endpoints."; + log.error(msg, e); + throw new APIManagerException(msg, e); + } catch (BadRequestException e) { + String msg = "Provided incorrect payload when invoking APIM REST endpoints."; + log.error(msg, e); + throw new APIManagerException(msg, e); + } catch (UnexpectedResponseException e) { + String msg = "Error occurred while invoking APIM REST endpoints."; + log.error(msg, e); + throw new APIManagerException(msg, e); + } catch (MetadataManagementException e) { + String msg = "Error occurred while getting meta data for meta key: " + applicationName; + log.error(msg, e); + throw new APIManagerException(msg, e); + } + } + + + private ApiApplicationKey handleNewAPIApplication(String applicationName, List uniqueApiList, + ApiApplicationInfo apiApplicationInfo, String keyType, String validityTime, + ArrayList supportedGrantTypes, String callbackUrl, + boolean isMappingRequired) throws APIManagerException { + ConsumerRESTAPIServices consumerRESTAPIServices = + APIApplicationManagerExtensionDataHolder.getInstance().getConsumerRESTAPIServices(); + io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application = new io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application(); + application.setName(applicationName); + application.setThrottlingPolicy(UNLIMITED_TIER); - List allowedDomains = new ArrayList<>(); - if (isAllowedAllDomains) { - allowedDomains.add(ApiApplicationConstants.ALLOWED_DOMAINS); + try { + application = consumerRESTAPIServices.createApplication(apiApplicationInfo, application); + addSubscriptions(application, uniqueApiList, apiApplicationInfo); + + KeyManager[] keyManagers = consumerRESTAPIServices.getAllKeyManagers(apiApplicationInfo); + KeyManager keyManager; + if (keyManagers.length == 1) { + keyManager = keyManagers[0]; } else { - allowedDomains.add(APIManagerUtil.getTenantDomain()); + String msg = + "Found invalid number of key managers. No of key managers found from the APIM: " + keyManagers.length; + log.error(msg); + throw new APIManagerException(msg); } - APIAdmin apiAdmin = new APIAdminImpl(); - String keyManagerId = null; - try { - List keyManagerConfigurations = apiAdmin - .getKeyManagerConfigurationsByTenant(tenantDomain); - if (keyManagerConfigurations != null) { - for (KeyManagerConfigurationDTO keyManagerConfigurationDTO : keyManagerConfigurations) { - keyManagerId = keyManagerConfigurationDTO.getUuid(); - } - } - String applicationAccessTokenExpiryTime = "N/A"; - if (!StringUtils.isEmpty(validityTime)) { - applicationAccessTokenExpiryTime = validityTime; - } - String jsonString = "{\"grant_types\":\"refresh_token,access_token," + - "urn:ietf:params:oauth:grant-type:saml2-bearer," + - "password,client_credentials,iwa:ntlm,urn:ietf:params:oauth:grant-type:jwt-bearer\"," + - "\"additionalProperties\":\"{\\\"application_access_token_expiry_time\\\":\\\"" + applicationAccessTokenExpiryTime + "\\\"," + - "\\\"user_access_token_expiry_time\\\":\\\"N\\/A\\\"," + - "\\\"refresh_token_expiry_time\\\":\\\"N\\/A\\\"," + - "\\\"id_token_expiry_time\\\":\\\"N\\/A\\\"}\"," + - "\"username\":\"" + username + "\"}"; - - Map keyDetails = apiConsumer - .requestApprovalForApplicationRegistration(username, applicationName, keyType, "", - allowedDomains.toArray(new String[allowedDomains.size()]), validityTime, "default", "", - jsonString, keyManagerId, tenantDomain); - - if (keyDetails != null) { - ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); - apiApplicationKey.setConsumerKey((String) keyDetails.get("consumerKey")); - apiApplicationKey.setConsumerSecret((String) keyDetails.get("consumerSecret")); - return apiApplicationKey; - } - throw new APIManagerException("Failed to generate keys for tenant: " + tenantDomain); - } catch (APIManagementException e) { - throw new APIManagerException("Failed to create api application for tenant: " + tenantDomain, e); + ApplicationKey applicationKey; + + if (isMappingRequired) { + // If we need to get opaque token instead of the JWT token, we have to do the mapping. Therefore, if + // it is a requirement then we have to call the method with enabling the flag. + APIApplicationServices apiApplicationServices = APIApplicationManagerExtensionDataHolder.getInstance() + .getApiApplicationServices(); + + APIApplicationKey apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials( + "ClientForMapping", + "client_credentials password refresh_token urn:ietf:params:oauth:grant-type:jwt-bearer"); + + apiApplicationInfo.setClientId(apiApplicationKey.getClientId()); + apiApplicationInfo.setClientSecret(apiApplicationKey.getClientSecret()); + + applicationKey = consumerRESTAPIServices.mapApplicationKeys(apiApplicationInfo, application, + keyManager.getName(), keyType); + } else { + applicationKey = consumerRESTAPIServices.generateApplicationKeys(apiApplicationInfo, application.getApplicationId(), + keyManager.getName(), validityTime, keyType); } - } catch (APIManagementException e) { - throw new APIManagerException("Failed to create api application for tenant: " + tenantDomain, e); + if (supportedGrantTypes != null || StringUtils.isNotEmpty(callbackUrl)) { + applicationKey = consumerRESTAPIServices.updateGrantType(apiApplicationInfo, application.getApplicationId(), + applicationKey.getKeyMappingId(), keyManager.getName(), supportedGrantTypes, callbackUrl); + } + + ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); + apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey()); + apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret()); + + Metadata metaData = new Metadata(); + metaData.setMetaKey(applicationName); + String metaValue = application.getApplicationId() + ":" + applicationKey.getKeyMappingId(); + metaData.setMetaValue(metaValue); + + MetadataManagementService metadataManagementService = APIApplicationManagerExtensionDataHolder.getInstance().getMetadataManagementService(); + metadataManagementService.createMetadata(metaData); + return apiApplicationKey; + } catch (MetadataKeyAlreadyExistsException e) { + String msg = "Since meta key:" + applicationName + " already exists, meta data creating process failed."; + log.error(msg, e); + throw new APIManagerException(msg, e); + } catch (MetadataManagementException e) { + String msg = "Error occurred while creating meta data for meta key: " + applicationName; + log.error(msg, e); + throw new APIManagerException(msg, e); + } catch (BadRequestException e) { + String msg = "Provided incorrect payload when invoking APIM REST endpoints to handle new API application."; + log.error(msg, e); + throw new APIManagerException(msg, e); + } catch (UnexpectedResponseException e) { + String msg = "Error occurred while invoking APIM REST endpoints to handle new API application."; + log.error(msg, e); + throw new APIManagerException(msg, e); + } catch (APIServicesException e) { + String msg = "Error occurred while processing the response of APIM REST endpoints to handle new API application."; + log.error(msg, e); + throw new APIManagerException(msg, e); } } + /** + * This method can be used to add a new subscriptions providing the ids of the APIs and the applications. + * + * @param application {@link io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application} + * @param apiInfos {@link List} + * @param apiApplicationInfo {@link ApiApplicationInfo} + * @throws BadRequestException if incorrect data provided to call subscribing REST API. + * @throws UnexpectedResponseException if error occurred while processing the subscribing REST API. + * @throws APIServicesException if error occurred while invoking the subscribing REST API. + */ + private void addSubscriptions( + io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application, + List apiInfos, ApiApplicationInfo apiApplicationInfo) + throws BadRequestException, UnexpectedResponseException, APIServicesException { + + ConsumerRESTAPIServices consumerRESTAPIServices = + APIApplicationManagerExtensionDataHolder.getInstance().getConsumerRESTAPIServices(); + + List subscriptionList = new ArrayList<>(); + apiInfos.forEach(apiInfo -> { + Subscription subscription = new Subscription(); + subscription.setApiId(apiInfo.getId()); + subscription.setApplicationId(application.getApplicationId()); + subscription.setThrottlingPolicy(UNLIMITED_TIER); + subscription.setRequestedThrottlingPolicy(UNLIMITED_TIER); + subscriptionList.add(subscription); + }); + + consumerRESTAPIServices.createSubscriptions(apiApplicationInfo, subscriptionList); + } + @Override public AccessTokenInfo getAccessToken(String scopes, String[] tags, String applicationName, String tokenType, - String validityPeriod, String username) throws APIManagerException { + String validityPeriod, String username) throws APIManagerException { try { String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true); ApiApplicationKey clientCredentials = getClientCredentials(tenantDomain, tags, applicationName, tokenType, @@ -317,11 +339,10 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe JWTClientManagerService jwtClientManagerService = APIApplicationManagerExtensionDataHolder.getInstance() .getJwtClientManagerService(); JWTClient jwtClient = jwtClientManagerService.getJWTClient(); - AccessTokenInfo accessTokenForAdmin = jwtClient + + return jwtClient .getAccessToken(clientCredentials.getConsumerKey(), clientCredentials.getConsumerSecret(), username, scopes); - - return accessTokenForAdmin; } catch (JWTClientException e) { String msg = "JWT Error occurred while registering Application to get access token."; log.error(msg, e); @@ -338,18 +359,19 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe } /** - * Get Client credentials - * @param tenantDomain Tenant Domain - * @param tags Tags + * Get Client credentials of application belongs to tenant admin + * + * @param tenantDomain Tenant Domain + * @param tags Tags * @param applicationName Application Name - * @param tokenType Token Type - * @param validityPeriod Validity Period + * @param tokenType Token Type + * @param validityPeriod Validity Period * @return {@link ApiApplicationKey} * @throws APIManagerException if error occurred while generating access token - * @throws UserStoreException if error ocurred while getting admin username. + * @throws UserStoreException if error occurred while getting admin username. */ private ApiApplicationKey getClientCredentials(String tenantDomain, String[] tags, String applicationName, - String tokenType, String validityPeriod) throws APIManagerException, UserStoreException { + String tokenType, String validityPeriod) throws APIManagerException, UserStoreException { APIRegistrationProfile registrationProfile = new APIRegistrationProfile(); registrationProfile.setAllowedToAllDomains(false); @@ -357,7 +379,6 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe registrationProfile.setTags(tags); registrationProfile.setApplicationName(applicationName); - ApiApplicationKey info = null; if (tenantDomain == null || tenantDomain.isEmpty()) { tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; } @@ -368,14 +389,49 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration() .getAdminUserName()); - if (registrationProfile.getUsername() == null || registrationProfile.getUsername().isEmpty()) { - info = generateAndRetrieveApplicationKeys(registrationProfile.getApplicationName(), - registrationProfile.getTags(), tokenType, null, - registrationProfile.isAllowedToAllDomains(), validityPeriod); - } + return generateAndRetrieveApplicationKeys(registrationProfile.getApplicationName(), + registrationProfile.getTags(), tokenType, PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() + .getRealmConfiguration().getAdminUserName(), + registrationProfile.isAllowedToAllDomains(), validityPeriod, PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() + .getRealmConfiguration().getAdminPassword(), null, null, null, false); } finally { PrivilegedCarbonContext.endTenantFlow(); } - return info; + } + + private ApiApplicationInfo getApplicationInfo(String username, String password) + throws APIManagerException { + + APIApplicationServices apiApplicationServices = APIApplicationManagerExtensionDataHolder.getInstance() + .getApiApplicationServices(); + + APIApplicationKey apiApplicationKey; + io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo accessTokenInfo; + try { + if (username == null || password == null) { + apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials( + "ClientForConsumerRestCalls", + "client_credentials password refresh_token urn:ietf:params:oauth:grant-type:jwt-bearer"); + } else { + apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentialsWithUser( + "ClientForConsumerRestCalls", + username, password, + "client_credentials password refresh_token urn:ietf:params:oauth:grant-type:jwt-bearer"); + } + accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + } catch (APIServicesException e) { + String errorMsg = "Error occurred while generating the API application"; + log.error(errorMsg, e); + throw new APIManagerException(errorMsg, e); + } + + ApiApplicationInfo applicationInfo = new ApiApplicationInfo(); + applicationInfo.setClientId(apiApplicationKey.getClientId()); + applicationInfo.setClientSecret(apiApplicationKey.getClientSecret()); + applicationInfo.setAccess_token(accessTokenInfo.getAccess_token()); + applicationInfo.setRefresh_token(accessTokenInfo.getRefresh_token()); + + return applicationInfo; } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/dto/ApiApplicationKey.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/dto/ApiApplicationKey.java index 3c14bbb3d8..526d36cd60 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/dto/ApiApplicationKey.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/dto/ApiApplicationKey.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.apimgt.application.extension.dto; -import org.json.simple.JSONObject; import io.entgra.device.mgt.core.apimgt.application.extension.constants.ApiApplicationConstants; +import org.json.simple.JSONObject; /** * This holds api application consumer key and secret. diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/internal/APIApplicationManagerExtensionDataHolder.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/internal/APIApplicationManagerExtensionDataHolder.java index 299184c946..e3bbebc4d0 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/internal/APIApplicationManagerExtensionDataHolder.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/internal/APIApplicationManagerExtensionDataHolder.java @@ -18,6 +18,9 @@ package io.entgra.device.mgt.core.apimgt.application.extension.internal; import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; import org.wso2.carbon.registry.core.service.TenantRegistryLoader; @@ -35,6 +38,9 @@ public class APIApplicationManagerExtensionDataHolder { private TenantRegistryLoader tenantRegistryLoader; private TenantIndexingLoader indexLoader; private JWTClientManagerService jwtClientManagerService; + private ConsumerRESTAPIServices consumerRESTAPIServices; + private APIApplicationServices apiApplicationServices; + private MetadataManagementService metadataManagementService; private APIApplicationManagerExtensionDataHolder() { } @@ -104,4 +110,28 @@ public class APIApplicationManagerExtensionDataHolder { public void setJwtClientManagerService(JWTClientManagerService jwtClientManagerService) { this.jwtClientManagerService = jwtClientManagerService; } + + public ConsumerRESTAPIServices getConsumerRESTAPIServices() { + return consumerRESTAPIServices; + } + + public void setConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) { + this.consumerRESTAPIServices = consumerRESTAPIServices; + } + + public APIApplicationServices getApiApplicationServices() { + return apiApplicationServices; + } + + public void setApiApplicationServices(APIApplicationServices apiApplicationServices) { + this.apiApplicationServices = apiApplicationServices; + } + + public MetadataManagementService getMetadataManagementService() { + return metadataManagementService; + } + + public void setMetadataManagementService(MetadataManagementService metadataManagementService) { + this.metadataManagementService = metadataManagementService; + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/internal/APIApplicationManagerExtensionServiceComponent.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/internal/APIApplicationManagerExtensionServiceComponent.java index 53dccb67d8..b3dc6dbd9d 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/internal/APIApplicationManagerExtensionServiceComponent.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/internal/APIApplicationManagerExtensionServiceComponent.java @@ -17,42 +17,28 @@ */ package io.entgra.device.mgt.core.apimgt.application.extension.internal; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices; +import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService; +import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderServiceImpl; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; -import org.osgi.service.component.ComponentContext;; -import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService; -import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderServiceImpl; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.registry.core.service.TenantRegistryLoader; import org.wso2.carbon.registry.indexing.service.TenantIndexingLoader; import org.wso2.carbon.user.core.service.RealmService; -/** - * @scr.component name="io.entgra.device.mgt.core.apimgt.application.extension.internal.APIApplicationManagerExtensionServiceComponent" - * @scr.reference name="tenant.registryloader" - * interface="org.wso2.carbon.registry.core.service.TenantRegistryLoader" - * cardinality="1..1" - * policy="dynamic" - * bind="setTenantRegistryLoader" - * unbind="unsetTenantRegistryLoader" - * @scr.reference name="tenant.indexloader" - * interface="org.wso2.carbon.registry.indexing.service.TenantIndexingLoader" - * cardinality="1..1" - * policy="dynamic" - * bind="setIndexLoader" - * unbind="unsetIndexLoader" - * @scr.reference name="realm.service" - * immediate="true" - * interface="org.wso2.carbon.user.core.service.RealmService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRealmService" - * unbind="unsetRealmService" - */ +@Component( + name = "io.entgra.device.mgt.core.apimgt.application.extension.internal.APIApplicationManagerExtensionServiceComponent", + immediate = true) public class APIApplicationManagerExtensionServiceComponent { private static final Log log = LogFactory.getLog(APIApplicationManagerExtensionServiceComponent.class); + @Activate protected void activate(ComponentContext componentContext) { try { if (log.isDebugEnabled()) { @@ -67,10 +53,17 @@ public class APIApplicationManagerExtensionServiceComponent { } } + @Deactivate protected void deactivate(ComponentContext componentContext) { //do nothing } + @Reference( + name = "tenant.registry.loader", + service = org.wso2.carbon.registry.core.service.TenantRegistryLoader.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetTenantRegistryLoader") protected void setTenantRegistryLoader(TenantRegistryLoader tenantRegistryLoader) { APIApplicationManagerExtensionDataHolder.getInstance().setTenantRegistryLoader(tenantRegistryLoader); } @@ -79,6 +72,12 @@ public class APIApplicationManagerExtensionServiceComponent { APIApplicationManagerExtensionDataHolder.getInstance().setTenantRegistryLoader(null); } + @Reference( + name = "tenant.index.loader", + service = org.wso2.carbon.registry.indexing.service.TenantIndexingLoader.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetIndexLoader") protected void setIndexLoader(TenantIndexingLoader indexLoader) { if (indexLoader != null && log.isDebugEnabled()) { log.debug("IndexLoader service initialized"); @@ -95,6 +94,12 @@ public class APIApplicationManagerExtensionServiceComponent { * * @param realmService An instance of RealmService */ + @Reference( + name = "realm.service", + service = org.wso2.carbon.user.core.service.RealmService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRealmService") protected void setRealmService(RealmService realmService) { if (log.isDebugEnabled()) { log.debug("Setting Realm Service"); @@ -113,4 +118,95 @@ public class APIApplicationManagerExtensionServiceComponent { } APIApplicationManagerExtensionDataHolder.getInstance().setRealmService(null); } + + /** + * Sets APIM Consumer REST API service. + * + * @param consumerRESTAPIServices An instance of ConsumerRESTAPIServices + */ + @Reference( + name = "APIM.consumer.service", + service = io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetConsumerRESTAPIServices") + protected void setConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) { + if (log.isDebugEnabled()) { + log.debug("Setting APIM Consumer REST API Service"); + } + APIApplicationManagerExtensionDataHolder.getInstance().setConsumerRESTAPIServices(consumerRESTAPIServices); + } + + /** + * Unset APIM Consumer REST API service + * + * @param consumerRESTAPIServices An instance of ConsumerRESTAPIServices + */ + protected void unsetConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) { + if (log.isDebugEnabled()) { + log.debug("Unsetting APIM Consumer REST API Service"); + } + APIApplicationManagerExtensionDataHolder.getInstance().setConsumerRESTAPIServices(null); + } + + + /** + * Sets DCR REST API service. + * + * @param apiApplicationServices An instance of APIApplicationServices + */ + @Reference( + name = "APIM.application.service", + service = io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetAPIApplicationServices") + protected void setAPIApplicationServices(APIApplicationServices apiApplicationServices) { + if (log.isDebugEnabled()) { + log.debug("Setting DCR REST API Service"); + } + APIApplicationManagerExtensionDataHolder.getInstance().setApiApplicationServices(apiApplicationServices); + } + + /** + * Unset DCR REST API service + * + * @param apiApplicationServices An instance of APIApplicationServices + */ + protected void unsetAPIApplicationServices(APIApplicationServices apiApplicationServices) { + if (log.isDebugEnabled()) { + log.debug("Unsetting DCR REST API Service"); + } + APIApplicationManagerExtensionDataHolder.getInstance().setApiApplicationServices(null); + } + + /** + * Sets Meta Data Mgt service. + * + * @param metadataManagementService An instance of MetadataManagementService + */ + @Reference( + name = "meta.data.mgt.service", + service = io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetAMetaMgtServices") + protected void setMetaMgtServices(MetadataManagementService metadataManagementService) { + if (log.isDebugEnabled()) { + log.debug("Setting Meta data mgt Service"); + } + APIApplicationManagerExtensionDataHolder.getInstance().setMetadataManagementService(metadataManagementService); + } + + /** + * Unset Meta Data Mgt service + * + * @param metadataManagementService An instance of MetadataManagementService + */ + protected void unsetAMetaMgtServices(MetadataManagementService metadataManagementService) { + if (log.isDebugEnabled()) { + log.debug("Unsetting Meta Data mgt Service"); + } + APIApplicationManagerExtensionDataHolder.getInstance().setMetadataManagementService(null); + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/util/APIManagerUtil.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/util/APIManagerUtil.java index d86fdcd77e..a98e1ce632 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/util/APIManagerUtil.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/util/APIManagerUtil.java @@ -17,10 +17,10 @@ */ package io.entgra.device.mgt.core.apimgt.application.extension.util; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.apimgt.application.extension.exception.APIManagerException; import io.entgra.device.mgt.core.apimgt.application.extension.internal.APIApplicationManagerExtensionDataHolder; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.registry.core.exceptions.RegistryException; diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml index ef2bb81d86..7f6cf515e0 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml @@ -34,14 +34,19 @@ https://entgra.io + + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + commons-httpclient.wso2 commons-httpclient provided - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api provided @@ -54,17 +59,6 @@ org.wso2.carbon.core provided - - org.eclipse.osgi - org.eclipse.osgi - provided - - - org.eclipse.osgi - org.eclipse.osgi.services - provided - - org.json.wso2 json @@ -93,13 +87,16 @@ - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix maven-bundle-plugin - 5.1.7 true diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServices.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServices.java index d628c4ce25..7b14f48800 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServices.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServices.java @@ -24,7 +24,11 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIService public interface APIApplicationServices { - APIApplicationKey createAndRetrieveApplicationCredentials() throws APIServicesException; + APIApplicationKey createAndRetrieveApplicationCredentials(String clientName, String grantType) + throws APIServicesException; + + APIApplicationKey createAndRetrieveApplicationCredentialsWithUser(String clientName, String username, String password, String grantType) + throws APIServicesException; AccessTokenInfo generateAccessTokenFromRegisteredApplication(String clientId, String clientSecret) throws APIServicesException; diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServicesImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServicesImpl.java index c412d189c0..9f91fdda84 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServicesImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServicesImpl.java @@ -19,20 +19,15 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api; import com.google.gson.Gson; -import org.json.JSONObject; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.HttpsTrustManagerUtils; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.RequestBody; -import okhttp3.Credentials; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.HttpsTrustManagerUtils; +import okhttp3.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.json.JSONObject; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; @@ -51,7 +46,7 @@ public class APIApplicationServicesImpl implements APIApplicationServices { getAPIManagerConfigurationService().getAPIManagerConfiguration(); @Override - public APIApplicationKey createAndRetrieveApplicationCredentials() throws APIServicesException { + public APIApplicationKey createAndRetrieveApplicationCredentials(String clientName, String grantType) throws APIServicesException { String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); String serverUser = getScopePublishUserName(tenantDomain); String serverPassword = getScopePublishUserPassword(tenantDomain); @@ -60,8 +55,8 @@ public class APIApplicationServicesImpl implements APIApplicationServices { JSONObject jsonObject = new JSONObject(); jsonObject.put("callbackUrl", Constants.EMPTY_STRING); - jsonObject.put("clientName", Constants.CLIENT_NAME); - jsonObject.put("grantType", Constants.GRANT_TYPE); + jsonObject.put("clientName", clientName); + jsonObject.put("grantType", grantType); jsonObject.put("owner", serverUser); jsonObject.put("saasApp", true); @@ -83,6 +78,35 @@ public class APIApplicationServicesImpl implements APIApplicationServices { } } + @Override + public APIApplicationKey createAndRetrieveApplicationCredentialsWithUser(String clientName, String username, String password, String grantType) + throws APIServicesException { + + String applicationEndpoint = config.getFirstProperty(Constants.DCR_END_POINT); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("callbackUrl", Constants.EMPTY_STRING); + jsonObject.put("clientName", clientName); + jsonObject.put("grantType", grantType); + jsonObject.put("owner", username); + jsonObject.put("saasApp", true); + + RequestBody requestBody = RequestBody.Companion.create(jsonObject.toString(), JSON); + Request request = new Request.Builder() + .url(applicationEndpoint) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic(username, password)) + .post(requestBody) + .build(); + try { + Response response = client.newCall(request).execute(); + return gson.fromJson(response.body().string(), APIApplicationKey.class); + } catch (IOException e) { + msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(e); + } + } + @Override public AccessTokenInfo generateAccessTokenFromRegisteredApplication(String consumerKey, String consumerSecret) throws APIServicesException { diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/ConsumerRESTAPIServices.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/ConsumerRESTAPIServices.java new file mode 100644 index 0000000000..2cb3cf692c --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/ConsumerRESTAPIServices.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.apimgt.extension.rest.api; + +import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.*; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.ApiApplicationInfo; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; + +import java.util.List; +import java.util.Map; + +public interface ConsumerRESTAPIServices { + + Application[] getAllApplications(ApiApplicationInfo apiApplicationInfo, String appName) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + Application getDetailsOfAnApplication(ApiApplicationInfo apiApplicationInfo, String applicationId) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + Application createApplication(ApiApplicationInfo apiApplicationInfo, Application application) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + Boolean deleteApplication(ApiApplicationInfo apiApplicationInfo, String applicationId) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + Subscription[] getAllSubscriptions(ApiApplicationInfo apiApplicationInfo, String applicationId) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + APIInfo[] getAllApis(ApiApplicationInfo apiApplicationInfo, Map queryParams, Map headerParams) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + Subscription createSubscription(ApiApplicationInfo apiApplicationInfo, Subscription subscriptions) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + Subscription[] createSubscriptions(ApiApplicationInfo apiApplicationInfo, List subscriptions) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + ApplicationKey generateApplicationKeys(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyManager, + String validityTime, String keyType) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + ApplicationKey mapApplicationKeys(ApiApplicationInfo apiApplicationInfo, Application application, String keyManager, String keyType) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + ApplicationKey getKeyDetails(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyMapId) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + ApplicationKey updateGrantType(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyMapId, String keyManager, + List supportedGrantTypes, String callbackUrl) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + KeyManager[] getAllKeyManagers(ApiApplicationInfo apiApplicationInfo) + throws APIServicesException, BadRequestException, UnexpectedResponseException; +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/ConsumerRESTAPIServicesImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/ConsumerRESTAPIServicesImpl.java new file mode 100644 index 0000000000..998331cc0d --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/ConsumerRESTAPIServicesImpl.java @@ -0,0 +1,674 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.apimgt.extension.rest.api; + +import com.google.gson.Gson; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.*; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.ApiApplicationInfo; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.HttpsTrustManagerUtils; +import okhttp3.*; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices { + + private static final Log log = LogFactory.getLog(ConsumerRESTAPIServicesImpl.class); + private static final OkHttpClient client = new OkHttpClient(HttpsTrustManagerUtils.getSSLClient().newBuilder()); + private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); + private static final Gson gson = new Gson(); + private static final String host = System.getProperty(Constants.IOT_CORE_HOST); + private static final String port = System.getProperty(Constants.IOT_CORE_HTTPS_PORT); + private static final String endPointPrefix = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port; + + @Override + public Application[] getAllApplications(ApiApplicationInfo apiApplicationInfo, String appName) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getAllApplicationsUrl = endPointPrefix + Constants.APPLICATIONS_API + "?query=" + appName; + + Request.Builder builder = new Request.Builder(); + builder.url(getAllApplicationsUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + builder.get(); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + JSONArray applicationList = (JSONArray) new JSONObject(response.body().string()).get("list"); + return gson.fromJson(applicationList.toString(), Application[].class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return getAllApplications(refreshedApiApplicationInfo, appName); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public Application getDetailsOfAnApplication(ApiApplicationInfo apiApplicationInfo, String applicationId) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getDetailsOfAPPUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId; + + Request.Builder builder = new Request.Builder(); + builder.url(getDetailsOfAPPUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + builder.get(); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + return gson.fromJson(response.body().string(), Application.class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return getDetailsOfAnApplication(refreshedApiApplicationInfo, applicationId); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public Application createApplication(ApiApplicationInfo apiApplicationInfo, Application application) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getAllScopesUrl = endPointPrefix + Constants.APPLICATIONS_API; + + JSONArray groups = new JSONArray(); + JSONArray subscriptionScope = new JSONArray(); + + if (application.getGroups() != null && application.getSubscriptionScopes() != null) { + for (String string : application.getGroups()) { + groups.put(string); + } + for (Scopes string : application.getSubscriptionScopes()) { + subscriptionScope.put(string); + } + } + + JSONObject applicationInfo = new JSONObject(); + applicationInfo.put("name", application.getName()); + applicationInfo.put("throttlingPolicy", application.getThrottlingPolicy()); + applicationInfo.put("description", application.getDescription()); + applicationInfo.put("tokenType", application.getTokenType()); + applicationInfo.put("groups", groups); + applicationInfo.put("attributes", new JSONObject()); + applicationInfo.put("subscriptionScopes", subscriptionScope); + + RequestBody requestBody = RequestBody.create(JSON, applicationInfo.toString()); + + Request.Builder builder = new Request.Builder(); + builder.url(getAllScopesUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + builder.post(requestBody); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_CREATED == response.code()) { + return gson.fromJson(response.body().string(), Application.class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return createApplication(refreshedApiApplicationInfo, application); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public Boolean deleteApplication(ApiApplicationInfo apiApplicationInfo, String applicationId) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String deleteScopesUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId; + + Request.Builder builder = new Request.Builder(); + builder.url(deleteScopesUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + builder.delete(); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + return true; + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return deleteApplication(refreshedApiApplicationInfo, applicationId); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public Subscription[] getAllSubscriptions(ApiApplicationInfo apiApplicationInfo, String applicationId) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getAllScopesUrl = endPointPrefix + Constants.SUBSCRIPTION_API + "?applicationId=" + applicationId + "&limit=1000"; + + Request.Builder builder = new Request.Builder(); + builder.url(getAllScopesUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + builder.get(); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + JSONArray subscriptionList = (JSONArray) new JSONObject(response.body().string()).get("list"); + return gson.fromJson(subscriptionList.toString(), Subscription[].class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return getAllSubscriptions(refreshedApiApplicationInfo, applicationId); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public APIInfo[] getAllApis(ApiApplicationInfo apiApplicationInfo, Map queryParams, Map headerParams) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + StringBuilder getAPIsURL = new StringBuilder(endPointPrefix + Constants.DEV_PORTAL_API); + + for (Map.Entry query : queryParams.entrySet()) { + getAPIsURL.append(Constants.AMPERSAND).append(query.getKey()).append(Constants.EQUAL).append(query.getValue()); + } + + Request.Builder builder = new Request.Builder(); + builder.url(getAPIsURL.toString()); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + + for (Map.Entry header : headerParams.entrySet()) { + builder.addHeader(header.getKey(), header.getValue()); + } + builder.get(); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + JSONArray apiList = (JSONArray) new JSONObject(response.body().string()).get("list"); + return gson.fromJson(apiList.toString(), APIInfo[].class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return getAllApis(refreshedApiApplicationInfo, queryParams, headerParams); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public Subscription createSubscription(ApiApplicationInfo apiApplicationInfo, Subscription subscriptions) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String createSubscriptionUrl = endPointPrefix + Constants.SUBSCRIPTION_API; + + JSONObject subscriptionObject = new JSONObject(); + subscriptionObject.put("applicationId", subscriptions.getApplicationId()); + subscriptionObject.put("apiId", subscriptions.getApiId()); + subscriptionObject.put("throttlingPolicy", subscriptions.getThrottlingPolicy()); + subscriptionObject.put("requestedThrottlingPolicy", subscriptions.getRequestedThrottlingPolicy()); + + RequestBody requestBody = RequestBody.create(JSON, subscriptionObject.toString()); + + Request.Builder builder = new Request.Builder(); + builder.url(createSubscriptionUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + + builder.post(requestBody); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_CREATED == response.code()) { + return gson.fromJson(response.body().string(), Subscription.class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return createSubscription(refreshedApiApplicationInfo, subscriptions); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public Subscription[] createSubscriptions(ApiApplicationInfo apiApplicationInfo, List subscriptions) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String createSubscriptionsUrl = endPointPrefix + Constants.SUBSCRIPTION_API + "/multiple"; + + String subscriptionsList = gson.toJson(subscriptions); + RequestBody requestBody = RequestBody.create(JSON, subscriptionsList); + + Request.Builder builder = new Request.Builder(); + builder.url(createSubscriptionsUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + + builder.post(requestBody); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + return gson.fromJson(response.body().string(), Subscription[].class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return createSubscriptions(refreshedApiApplicationInfo, subscriptions); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public ApplicationKey generateApplicationKeys(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyManager, + String validityTime, String keyType) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String generateApplicationKeysUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + + applicationId + "/generate-keys"; + + JSONArray grantTypesToBeSupported = new JSONArray(); + grantTypesToBeSupported.put("password"); + grantTypesToBeSupported.put("client_credentials"); + + JSONArray scopes = new JSONArray(); + scopes.put("am_application_scope"); + scopes.put("default"); + + JSONObject keyInfo = new JSONObject(); + keyInfo.put("keyType", keyType); + keyInfo.put("keyManager", keyManager); + keyInfo.put("grantTypesToBeSupported", grantTypesToBeSupported); + keyInfo.put("callbackUrl", ""); + keyInfo.put("scopes", scopes); + keyInfo.put("validityTime", 3600); + keyInfo.put("additionalProperties", new JSONObject()); + + RequestBody requestBody = RequestBody.create(JSON, keyInfo.toString()); + + Request.Builder builder = new Request.Builder(); + builder.url(generateApplicationKeysUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + builder.post(requestBody); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + return gson.fromJson(response.body().string(), ApplicationKey.class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return generateApplicationKeys(refreshedApiApplicationInfo, applicationId, keyManager, validityTime, keyType); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public ApplicationKey mapApplicationKeys(ApiApplicationInfo apiApplicationInfo, Application application, String keyManager, String keyType) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getAllScopesUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + + application.getApplicationId() + "/map-keys"; + + JSONObject payload = new JSONObject(); + payload.put("consumerKey", apiApplicationInfo.getClientId()); + payload.put("consumerSecret", apiApplicationInfo.getClientSecret()); + payload.put("keyManager", keyManager); + payload.put("keyType", keyType); + + RequestBody requestBody = RequestBody.create(JSON, payload.toString()); + + Request.Builder builder = new Request.Builder(); + builder.url(getAllScopesUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + builder.post(requestBody); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + return gson.fromJson(response.body().string(), ApplicationKey.class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return mapApplicationKeys(refreshedApiApplicationInfo, application, keyManager, keyType); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public ApplicationKey getKeyDetails(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyMapId) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getKeyDetails = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId + "/oauth-keys/" + keyMapId; + + Request.Builder builder = new Request.Builder(); + builder.url(getKeyDetails); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + builder.get(); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + return gson.fromJson(response.body().string(), ApplicationKey.class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return getKeyDetails(refreshedApiApplicationInfo, applicationId, keyMapId); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public ApplicationKey updateGrantType(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyMapId, String keyManager, + List supportedGrantTypes, String callbackUrl) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getKeyDetails = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId + "/oauth-keys/" + keyMapId; + + Request.Builder builder = new Request.Builder(); + builder.url(getKeyDetails); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + + JSONArray supportedGrantTypeList = new JSONArray(); + for (String string : supportedGrantTypes) { + supportedGrantTypeList.put(string); + } + + JSONObject payload = new JSONObject(); + payload.put("keyMappingId", keyMapId); + payload.put("keyManager", keyManager); + payload.put("supportedGrantTypes", supportedGrantTypeList); + payload.put("callbackUrl", (callbackUrl != null ? callbackUrl : "")); + payload.put("additionalProperties", new JSONObject()); + + RequestBody requestBody = RequestBody.create(JSON, payload.toString()); + + builder.put(requestBody); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + return gson.fromJson(response.body().string(), ApplicationKey.class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return updateGrantType(refreshedApiApplicationInfo, applicationId, keyMapId, keyManager, supportedGrantTypes, callbackUrl); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public KeyManager[] getAllKeyManagers(ApiApplicationInfo apiApplicationInfo) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getAllKeyManagersUrl = endPointPrefix + Constants.KEY_MANAGERS_API; + + Request.Builder builder = new Request.Builder(); + builder.url(getAllKeyManagersUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + builder.get(); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + JSONArray keyManagerList = (JSONArray) new JSONObject(response.body().string()).get("list"); + return gson.fromJson(keyManagerList.toString(), KeyManager[].class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return getAllKeyManagers(refreshedApiApplicationInfo); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + private ApiApplicationInfo returnApplicationInfo(ApiApplicationInfo apiApplicationInfo, AccessTokenInfo refreshedToken) { + + ApiApplicationInfo applicationInfo = new ApiApplicationInfo(); + applicationInfo.setClientId(apiApplicationInfo.getClientId()); + applicationInfo.setClientSecret(apiApplicationInfo.getClientSecret()); + applicationInfo.setAccess_token(refreshedToken.getAccess_token()); + applicationInfo.setRefresh_token(refreshedToken.getRefresh_token()); + return applicationInfo; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java index a263ad2d63..da24e906a1 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java @@ -24,7 +24,6 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; -import org.json.JSONObject; import java.util.List; diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/APIInfo.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/APIInfo.java new file mode 100644 index 0000000000..0435fc64ec --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/APIInfo.java @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer; + +import org.json.JSONObject; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +/** + * This class represents the Consumer API Information. + */ + +public class APIInfo { + + private String id; + private String name; + private String description; + private String context; + private String version; + private String provider; + private String lifeCycleStatus; + private String thumbnailUri; + private String avgRating; + private List throttlingPolicies; + private JSONObject advertiseInfo; + private JSONObject businessInformation; + private boolean isSubscriptionAvailable; + private String monetizationLabel; + private String gatewayVendor; + private List additionalProperties; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getContext() { + return context; + } + + public void setContext(String context) { + this.context = context; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getProvider() { + return provider; + } + + public void setProvider(String provider) { + this.provider = provider; + } + + public String getLifeCycleStatus() { + return lifeCycleStatus; + } + + public void setLifeCycleStatus(String lifeCycleStatus) { + this.lifeCycleStatus = lifeCycleStatus; + } + + public String getThumbnailUri() { + return thumbnailUri; + } + + public void setThumbnailUri(String thumbnailUri) { + this.thumbnailUri = thumbnailUri; + } + + public String getAvgRating() { + return avgRating; + } + + public void setAvgRating(String avgRating) { + this.avgRating = avgRating; + } + + public List getThrottlingPolicies() { + return throttlingPolicies; + } + + public void setThrottlingPolicies(List throttlingPolicies) { + this.throttlingPolicies = throttlingPolicies; + } + + public JSONObject getAdvertiseInfo() { + return advertiseInfo; + } + + public void setAdvertiseInfo(JSONObject advertiseInfo) { + this.advertiseInfo = advertiseInfo; + } + + public JSONObject getBusinessInformation() { + return businessInformation; + } + + public void setBusinessInformation(JSONObject businessInformation) { + this.businessInformation = businessInformation; + } + + public boolean isSubscriptionAvailable() { + return isSubscriptionAvailable; + } + + public void setSubscriptionAvailable(boolean subscriptionAvailable) { + isSubscriptionAvailable = subscriptionAvailable; + } + + public String getMonetizationLabel() { + return monetizationLabel; + } + + public void setMonetizationLabel(String monetizationLabel) { + this.monetizationLabel = monetizationLabel; + } + + public String getGatewayVendor() { + return gatewayVendor; + } + + public void setGatewayVendor(String gatewayVendor) { + this.gatewayVendor = gatewayVendor; + } + + public List getAdditionalProperties() { + return additionalProperties; + } + + public void setAdditionalProperties(List additionalProperties) { + this.additionalProperties = additionalProperties; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/APIKey.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/APIKey.java new file mode 100644 index 0000000000..5cdaa83577 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/APIKey.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer; + +/** + * This class represents the Consumer API Key Information. + */ + +public class APIKey { + + private String apikey; + private int validityTime; + + public String getApikey() { + return apikey; + } + + public void setApikey(String apikey) { + this.apikey = apikey; + } + + public int getValidityTime() { + return validityTime; + } + + public void setValidityTime(int validityTime) { + this.validityTime = validityTime; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/Application.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/Application.java new file mode 100644 index 0000000000..d56de0331d --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/Application.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer; + +import org.wso2.carbon.apimgt.api.model.APIKey; + +import java.util.List; +import java.util.Map; + +/** + * This class represents the Consumer Application Information. + */ + +public class Application { + private String applicationId; + private String name; + private String throttlingPolicy; + private String description; + private String tokenType; + private String status; + private List groups; + private int subscriptionCount; + private List keys; + private Map attributes; + private List subscriptionScopes; + private String owner; + private boolean hashEnabled; + + public String getApplicationId() { + return applicationId; + } + + public void setApplicationId(String applicationId) { + this.applicationId = applicationId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getThrottlingPolicy() { + return throttlingPolicy; + } + + public void setThrottlingPolicy(String throttlingPolicy) { + this.throttlingPolicy = throttlingPolicy; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getTokenType() { + return tokenType; + } + + public void setTokenType(String tokenType) { + this.tokenType = tokenType; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public List getGroups() { + return groups; + } + + public void setGroups(List groups) { + this.groups = groups; + } + + public int getSubscriptionCount() { + return subscriptionCount; + } + + public void setSubscriptionCount(int subscriptionCount) { + this.subscriptionCount = subscriptionCount; + } + + public List getKeys() { + return keys; + } + + public void setKeys(List keys) { + this.keys = keys; + } + + public Map getAttributes() { + return attributes; + } + + public void setAttributes(Map attributes) { + this.attributes = attributes; + } + + public List getSubscriptionScopes() { + return subscriptionScopes; + } + + public void setSubscriptionScopes(List subscriptionScopes) { + this.subscriptionScopes = subscriptionScopes; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public boolean isHashEnabled() { + return hashEnabled; + } + + public void setHashEnabled(boolean hashEnabled) { + this.hashEnabled = hashEnabled; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/ApplicationConfigurations.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/ApplicationConfigurations.java new file mode 100644 index 0000000000..9634b77528 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/ApplicationConfigurations.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer; + +import io.apicurio.datamodels.asyncapi.v2.visitors.Aai20Traverser; + +import java.util.List; + +/** + * This class represents the Consumer Application configuration Information. + */ +public class ApplicationConfigurations { + + private String name; + private String label; + private String type; + private boolean required; + private boolean mask; + private boolean multiple; + private String tooltip; + private List values; + private String defaults; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public boolean isRequired() { + return required; + } + + public void setRequired(boolean required) { + this.required = required; + } + + public boolean isMask() { + return mask; + } + + public void setMask(boolean mask) { + this.mask = mask; + } + + public boolean isMultiple() { + return multiple; + } + + public void setMultiple(boolean multiple) { + this.multiple = multiple; + } + + public String getTooltip() { + return tooltip; + } + + public void setTooltip(String tooltip) { + this.tooltip = tooltip; + } + + public List getValues() { + return values; + } + + public void setValues(List values) { + this.values = values; + } + + public String getDefaults() { + return defaults; + } + + public void setDefaults(String defaults) { + this.defaults = defaults; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/ApplicationGrantTypeUpdater.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/ApplicationGrantTypeUpdater.java new file mode 100644 index 0000000000..b7d5e2e8b9 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/ApplicationGrantTypeUpdater.java @@ -0,0 +1,26 @@ +package io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer; + +import java.util.ArrayList; + +public class ApplicationGrantTypeUpdater { + + private String callbackUrl; + + private ArrayList supportedGrantTypes; + + public String getCallbackUrl() { + return callbackUrl; + } + + public void setCallbackUrl(String callbackUrl) { + this.callbackUrl = callbackUrl; + } + + public ArrayList getSupportedGrantTypes() { + return supportedGrantTypes; + } + + public void setSupportedGrantTypes(ArrayList supportedGrantTypes) { + this.supportedGrantTypes = supportedGrantTypes; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/ApplicationKey.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/ApplicationKey.java new file mode 100644 index 0000000000..c51564af2c --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/ApplicationKey.java @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer; + +import org.json.JSONObject; + +import java.util.List; + +/** + * This class represents the Consumer Application key Information. + */ +public class ApplicationKey { + + private String keyMappingId; + private String keyManager; + private String consumerKey; + private String consumerSecret; + private List supportedGrantTypes; + private String callbackUrl; + private String keyState; + private String keyType; + private String mode; + private String groupId; + private JSONObject token; + private JSONObject additionalProperties; + + public String getKeyMappingId() { + return keyMappingId; + } + + public void setKeyMappingId(String keyMappingId) { + this.keyMappingId = keyMappingId; + } + + public String getKeyManager() { + return keyManager; + } + + public void setKeyManager(String keyManager) { + this.keyManager = keyManager; + } + + public String getConsumerKey() { + return consumerKey; + } + + public void setConsumerKey(String consumerKey) { + this.consumerKey = consumerKey; + } + + public String getConsumerSecret() { + return consumerSecret; + } + + public void setConsumerSecret(String consumerSecret) { + this.consumerSecret = consumerSecret; + } + + public List getSupportedGrantTypes() { + return supportedGrantTypes; + } + + public void setSupportedGrantTypes(List supportedGrantTypes) { + this.supportedGrantTypes = supportedGrantTypes; + } + + public String getCallbackUrl() { + return callbackUrl; + } + + public void setCallbackUrl(String callbackUrl) { + this.callbackUrl = callbackUrl; + } + + public String getKeyState() { + return keyState; + } + + public void setKeyState(String keyState) { + this.keyState = keyState; + } + + public String getKeyType() { + return keyType; + } + + public void setKeyType(String keyType) { + this.keyType = keyType; + } + + public String getMode() { + return mode; + } + + public void setMode(String mode) { + this.mode = mode; + } + + public String getGroupId() { + return groupId; + } + + public void setGroupId(String groupId) { + this.groupId = groupId; + } + + public JSONObject getToken() { + return token; + } + + public void setToken(JSONObject token) { + this.token = token; + } + + public JSONObject getAdditionalProperties() { + return additionalProperties; + } + + public void setAdditionalProperties(JSONObject additionalProperties) { + this.additionalProperties = additionalProperties; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/KeyManager.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/KeyManager.java new file mode 100644 index 0000000000..ac34e006dd --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/KeyManager.java @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer; + +import org.json.JSONObject; + +import java.util.List; + +/** + * This class represents the Consumer Key manager Information. + */ + +public class KeyManager { + + private String id; + private String name; + private String type; + private String displayName; + private String description; + private boolean enabled; + private List availableGrantTypes; + private String tokenEndpoint; + private String revokeEndpoint; + private String userInfoEndpoint; + private String enableTokenGeneration; + private String enableTokenEncryption; + private String enableTokenHashing; + private String enableOAuthAppCreation; + private String enableMapOAuthConsumerApps; + private List applicationConfiguration; + private JSONObject additionalProperties; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public List getAvailableGrantTypes() { + return availableGrantTypes; + } + + public void setAvailableGrantTypes(List availableGrantTypes) { + this.availableGrantTypes = availableGrantTypes; + } + + public String getTokenEndpoint() { + return tokenEndpoint; + } + + public void setTokenEndpoint(String tokenEndpoint) { + this.tokenEndpoint = tokenEndpoint; + } + + public String getRevokeEndpoint() { + return revokeEndpoint; + } + + public void setRevokeEndpoint(String revokeEndpoint) { + this.revokeEndpoint = revokeEndpoint; + } + + public String getUserInfoEndpoint() { + return userInfoEndpoint; + } + + public void setUserInfoEndpoint(String userInfoEndpoint) { + this.userInfoEndpoint = userInfoEndpoint; + } + + public String getEnableTokenGeneration() { + return enableTokenGeneration; + } + + public void setEnableTokenGeneration(String enableTokenGeneration) { + this.enableTokenGeneration = enableTokenGeneration; + } + + public String getEnableTokenEncryption() { + return enableTokenEncryption; + } + + public void setEnableTokenEncryption(String enableTokenEncryption) { + this.enableTokenEncryption = enableTokenEncryption; + } + + public String getEnableTokenHashing() { + return enableTokenHashing; + } + + public void setEnableTokenHashing(String enableTokenHashing) { + this.enableTokenHashing = enableTokenHashing; + } + + public String getEnableOAuthAppCreation() { + return enableOAuthAppCreation; + } + + public void setEnableOAuthAppCreation(String enableOAuthAppCreation) { + this.enableOAuthAppCreation = enableOAuthAppCreation; + } + + public String getEnableMapOAuthConsumerApps() { + return enableMapOAuthConsumerApps; + } + + public void setEnableMapOAuthConsumerApps(String enableMapOAuthConsumerApps) { + this.enableMapOAuthConsumerApps = enableMapOAuthConsumerApps; + } + + public List getApplicationConfiguration() { + return applicationConfiguration; + } + + public void setApplicationConfiguration(List applicationConfiguration) { + this.applicationConfiguration = applicationConfiguration; + } + + public JSONObject getAdditionalProperties() { + return additionalProperties; + } + + public void setAdditionalProperties(JSONObject additionalProperties) { + this.additionalProperties = additionalProperties; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/Scopes.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/Scopes.java new file mode 100644 index 0000000000..a2b55005b6 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/Scopes.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer; + +import java.util.List; + +/** + * This class represents the scope data. + */ + +public class Scopes { + + private String key; + private String name; + private List roles; + private String description; + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getRoles() { + return roles; + } + + public void setRoles(List roles) { + this.roles = roles; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/Subscription.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/Subscription.java new file mode 100644 index 0000000000..2ff525f5dc --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/Subscription.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer; + +import org.json.JSONObject; + +public class Subscription { + + private String subscriptionId; + private String applicationId; + private String apiId; + private APIInfo apiInfo; + private JSONObject applicationInfo; + private String throttlingPolicy; + private String requestedThrottlingPolicy; + private String status; + private String redirectionParams; + + public String getSubscriptionId() { + return subscriptionId; + } + + public void setSubscriptionId(String subscriptionId) { + this.subscriptionId = subscriptionId; + } + + public String getApplicationId() { + return applicationId; + } + + public void setApplicationId(String applicationId) { + this.applicationId = applicationId; + } + + public String getApiId() { + return apiId; + } + + public void setApiId(String apiId) { + this.apiId = apiId; + } + + public APIInfo getApiInfo() { + return apiInfo; + } + + public void setApiInfo(APIInfo apiInfo) { + this.apiInfo = apiInfo; + } + + public JSONObject getApplicationInfo() { + return applicationInfo; + } + + public void setApplicationInfo(JSONObject applicationInfo) { + this.applicationInfo = applicationInfo; + } + + public String getThrottlingPolicy() { + return throttlingPolicy; + } + + public void setThrottlingPolicy(String throttlingPolicy) { + this.throttlingPolicy = throttlingPolicy; + } + + public String getRequestedThrottlingPolicy() { + return requestedThrottlingPolicy; + } + + public void setRequestedThrottlingPolicy(String requestedThrottlingPolicy) { + this.requestedThrottlingPolicy = requestedThrottlingPolicy; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getRedirectionParams() { + return redirectionParams; + } + + public void setRedirectionParams(String redirectionParams) { + this.redirectionParams = redirectionParams; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/constants/Constants.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/constants/Constants.java index 90312d093d..34b4f04681 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/constants/Constants.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/constants/Constants.java @@ -24,17 +24,20 @@ public final class Constants { } public static final String EMPTY_STRING = ""; - public static final String CLIENT_NAME = "rest_api_publisher_code"; + public static final String AMPERSAND = "&"; + public static final String SLASH = "/"; + public static final String EQUAL = "="; public static final String SERVER_USER = "WorkflowConfigurations.ServerUser"; public static final String SERVER_PASSWORD = "WorkflowConfigurations.ServerPassword"; - public static final String GRANT_TYPE = "client_credentials password refresh_token"; public static final String REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME = "refresh_token"; public static final String OAUTH_EXPIRES_IN = "expires_in"; public static final String OAUTH_TOKEN_SCOPE = "scope"; public static final String OAUTH_TOKEN_TYPE = "token_type"; public static final String REFRESH_TOKEN_GRANT_TYPE = "refresh_token"; public static final String SCOPE_PARAM_NAME = "scope"; - public static final String SCOPES = "apim:api_create apim:api_view apim:shared_scope_manage apim:api_import_export apim:api_publish"; + public static final String SCOPES = "apim:api_create apim:api_view apim:shared_scope_manage apim:api_import_export " + + "apim:api_publish apim:admin apim:api_key apim:app_import_export apim:app_manage apim:store_settings " + + "apim:sub_alert_manage apim:sub_manage apim:subscribe openid"; public static final String DCR_END_POINT = "WorkflowConfigurations.DCREndPoint"; public static final String TOKE_END_POINT = "WorkflowConfigurations.TokenEndPoint"; public static final String ADAPTER_CONF_KEEP_ALIVE = "keepAlive"; @@ -61,14 +64,16 @@ public final class Constants { public static final String SPACE = " "; public static final String IOT_CORE_HOST = "iot.core.host"; public static final String IOT_CORE_HTTPS_PORT = "iot.core.https.port"; - public static final String GET_ALL_SCOPES = "/api/am/publisher/v2/scopes?limit=1000"; - public static final String SCOPE_API_ENDPOINT = "/api/am/publisher/v2/scopes/"; - public static final String API_ENDPOINT = "/api/am/publisher/v2/apis/"; - public static final String GET_ALL_APIS = "/api/am/publisher/v2/apis?limit=1000"; + public static final String GET_ALL_SCOPES = "/api/am/publisher/v4/scopes?limit=1000"; + public static final String SCOPE_API_ENDPOINT = "/api/am/publisher/v4/scopes/"; + public static final String API_ENDPOINT = "/api/am/publisher/v4/apis/"; + public static final String GET_ALL_APIS = "/api/am/publisher/v4/apis?limit=1000"; + public static final String APPLICATIONS_API = "/api/am/devportal/v3/applications"; + public static final String SUBSCRIPTION_API = "/api/am/devportal/v3/subscriptions"; + public static final String DEV_PORTAL_API = "/api/am/devportal/v3/apis?limit=1000"; + public static final String KEY_MANAGERS_API = "/api/am/devportal/v3/key-managers"; public static final String SCOPE_PUBLISH_RESERVED_USER_NAME = "scope_publish_reserved_user"; public static final String SCOPE_PUBLISH_RESERVED_USER_PASSWORD = "&gKfyE8E4rUY4Q"; public static final String ADMIN_ROLE_KEY = "admin"; public static final String PERM_SCOPE_MAPPING_META_KEY = "perm-scope-mapping"; } - - diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/ApiApplicationInfo.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/ApiApplicationInfo.java new file mode 100644 index 0000000000..169ce76442 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/ApiApplicationInfo.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.dto; + +/** + * This holds the API application client information and token information. + */ +public class ApiApplicationInfo { + private String clientId; + private String clientSecret; + private String refresh_token; + private String access_token; + + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getClientSecret() { + return clientSecret; + } + + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } + + public String getRefresh_token() { + return refresh_token; + } + + public void setRefresh_token(String refresh_token) { + this.refresh_token = refresh_token; + } + + public String getAccess_token() { + return access_token; + } + + public void setAccess_token(String access_token) { + this.access_token = access_token; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceComponent.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceComponent.java index fef16ea6ee..69015d5697 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceComponent.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceComponent.java @@ -20,28 +20,25 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api.internal; import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServicesImpl; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServicesImpl; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServicesImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; -/** - * @scr.component name="internal.io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServiceComponent" - * immediate="true" - * @scr.reference name="user.apimanagerconfigurationservice.default" - * interface="org.wso2.carbon.apimgt.impl.APIManagerConfigurationService" - * cardinality="1..1" - * policy="dynamic" - * bind="setAPIManagerConfigurationService" - * unbind="unsetAPIManagerConfigurationService" - */ +@Component( + name = "io.entgra.device.mgt.core.apimgt.extension.rest.api.internal.APIManagerServiceComponent", + immediate = true) public class APIManagerServiceComponent { private static Log log = LogFactory.getLog(APIManagerServiceComponent.class); + @Activate protected void activate(ComponentContext componentContext) { if (log.isDebugEnabled()) { log.debug("Initializing publisher API extension bundle"); @@ -57,6 +54,10 @@ public class APIManagerServiceComponent { bundleContext.registerService(PublisherRESTAPIServices.class.getName(), publisherRESTAPIServices, null); APIManagerServiceDataHolder.getInstance().setPublisherRESTAPIServices(publisherRESTAPIServices); + ConsumerRESTAPIServices consumerRESTAPIServices = new ConsumerRESTAPIServicesImpl(); + bundleContext.registerService(ConsumerRESTAPIServices.class.getName(), consumerRESTAPIServices, null); + APIManagerServiceDataHolder.getInstance().setConsumerRESTAPIServices(consumerRESTAPIServices); + if (log.isDebugEnabled()) { log.debug("API Application bundle has been successfully initialized"); } @@ -64,11 +65,17 @@ public class APIManagerServiceComponent { log.error("Error occurred while initializing API Application bundle", e); } } - + @Deactivate protected void deactivate(ComponentContext componentContext) { //do nothing } + @Reference( + name = "apim.configuration.service", + service = org.wso2.carbon.apimgt.impl.APIManagerConfigurationService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetAPIManagerConfigurationService") protected void setAPIManagerConfigurationService(APIManagerConfigurationService apiManagerConfigurationService) { if (log.isDebugEnabled()) { log.debug("Setting API Manager Configuration Service"); diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceDataHolder.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceDataHolder.java index deeeaa2a06..3153d50a89 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceDataHolder.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceDataHolder.java @@ -20,6 +20,7 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api.internal; import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.tenant.TenantManager; @@ -34,6 +35,8 @@ public class APIManagerServiceDataHolder { private static APIManagerServiceDataHolder thisInstance = new APIManagerServiceDataHolder(); + private ConsumerRESTAPIServices consumerRESTAPIServices; + private APIManagerServiceDataHolder() { } @@ -60,6 +63,7 @@ public class APIManagerServiceDataHolder { return apiManagerConfigurationService; } + public PublisherRESTAPIServices getPublisherRESTAPIServices() { return publisherRESTAPIServices; } @@ -90,4 +94,12 @@ public class APIManagerServiceDataHolder { } this.tenantManager = realmService.getTenantManager(); } + + public ConsumerRESTAPIServices getConsumerRESTAPIServices() { + return consumerRESTAPIServices; + } + + public void setConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) { + this.consumerRESTAPIServices = consumerRESTAPIServices; + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/util/HttpsTrustManagerUtils.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/util/HttpsTrustManagerUtils.java index 99df380d79..0dbfb4c3c0 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/util/HttpsTrustManagerUtils.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/util/HttpsTrustManagerUtils.java @@ -25,30 +25,12 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.ServerConfiguration; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; -import javax.net.ssl.SSLSession; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.HostnameVerifier; - +import javax.net.ssl.*; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import java.net.Proxy; -import java.net.ProxySelector; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.net.URI; - -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.SecureRandom; +import java.net.*; +import java.security.*; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.List; diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/pom.xml index ebc4285259..14b4f62707 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/pom.xml @@ -29,18 +29,16 @@ war WSO2 Carbon - API Key Management API This module extends the API manager's key management apis. - http://wso2.org + https://entgra.io + org.apache.maven.plugins maven-compiler-plugin - - 1.8 - 1.8 - + org.apache.maven.plugins maven-war-plugin WEB-INF/lib/*cxf*.jar diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/DCRRequest.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/DCRRequest.java index c8171451f6..9235087a77 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/DCRRequest.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/DCRRequest.java @@ -22,6 +22,7 @@ import org.codehaus.jackson.annotate.JsonIgnoreProperties; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; +import java.util.ArrayList; @XmlRootElement @@ -32,6 +33,8 @@ public class DCRRequest { @XmlElement(required = true) private String username; @XmlElement(required = true) + private String password; + @XmlElement(required = true) private String grantTypes; @XmlElement private String callBackUrl; @@ -43,6 +46,10 @@ public class DCRRequest { @XmlElement private int validityPeriod; + private String callbackUrl; + + private ArrayList supportedGrantTypes; + public String getApplicationName() { return applicationName; } @@ -98,4 +105,24 @@ public class DCRRequest { public void setValidityPeriod(int validityPeriod) { this.validityPeriod = validityPeriod; } + + public String getPassword() { return password; } + + public void setPassword(String password) { this.password = password; } + + public String getCallbackUrl() { + return callbackUrl; + } + + public void setCallbackUrl(String callbackUrl) { + this.callbackUrl = callbackUrl; + } + + public ArrayList getSupportedGrantTypes() { + return supportedGrantTypes; + } + + public void setSupportedGrantTypes(ArrayList supportedGrantTypes) { + this.supportedGrantTypes = supportedGrantTypes; + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/KeyManagerService.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/KeyManagerService.java index 3da6325022..b172d73b42 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/KeyManagerService.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/KeyManagerService.java @@ -18,12 +18,7 @@ package io.entgra.device.mgt.core.apimgt.keymgt.extension.api; -import javax.ws.rs.Consumes; -import javax.ws.rs.FormParam; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/KeyManagerServiceImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/KeyManagerServiceImpl.java index 40b077f2f8..573316be81 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/KeyManagerServiceImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/KeyManagerServiceImpl.java @@ -27,13 +27,9 @@ import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtExcepti import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService; import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtServiceImpl; import io.entgra.device.mgt.core.device.mgt.common.exceptions.UnAuthorizedException; +import org.wso2.carbon.context.PrivilegedCarbonContext; -import javax.ws.rs.Consumes; -import javax.ws.rs.FormParam; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.Base64; @@ -51,7 +47,9 @@ public class KeyManagerServiceImpl implements KeyManagerService { try { KeyMgtService keyMgtService = new KeyMgtServiceImpl(); DCRResponse resp = keyMgtService.dynamicClientRegistration(dcrRequest.getApplicationName(), dcrRequest.getUsername(), - dcrRequest.getGrantTypes(), dcrRequest.getCallBackUrl(), dcrRequest.getTags(), dcrRequest.getIsSaasApp(), dcrRequest.getValidityPeriod()); + dcrRequest.getGrantTypes(), dcrRequest.getCallBackUrl(), dcrRequest.getTags(), + dcrRequest.getIsSaasApp(), dcrRequest.getValidityPeriod(), dcrRequest.getPassword(), + dcrRequest.getSupportedGrantTypes(), dcrRequest.getCallbackUrl()); return Response.status(Response.Status.CREATED).entity(gson.toJson(resp)).build(); } catch (KeyMgtException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/webapp/WEB-INF/cxf-servlet.xml index 31a04fcf89..8d0cb7ecce 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -19,9 +19,9 @@ + http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/pom.xml index 1b31e53d33..25c942800f 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/pom.xml @@ -30,9 +30,14 @@ bundle WSO2 Carbon - API Key Management This module extends the API manager's key management. - http://wso2.org + https://entgra.io + + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + commons-codec.wso2 commons-codec @@ -50,18 +55,26 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.device.mgt.common + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.apimgt.extension.rest.api + + - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix maven-bundle-plugin - 5.1.7 true @@ -71,10 +84,41 @@ API Management Application Bundle io.entgra.device.mgt.core.apimgt.keymgt.extension.internal - io.entgra.device.mgt.core.apimgt.application.extension, - io.entgra.device.mgt.core.apimgt.application.extension.*, - io.entgra.device.mgt.core.device.mgt.common.*, - io.entgra.device.mgt.core.device.mgt.core.* + com.google.gson;version="[2.9,3)", + io.entgra.device.mgt.core.apimgt.keymgt.extension, + io.entgra.device.mgt.core.apimgt.keymgt.extension.exception, + io.entgra.device.mgt.core.apimgt.keymgt.extension.service, + io.entgra.device.mgt.core.device.mgt.common.permission.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.config;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.config.keymanager;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.permission.mgt;version="[5.0,6)", + javax.cache;version="[1.0,2)", + javax.net.ssl,okhttp3;version="[4.9,5)", + org.apache.commons.lang;version="[2.4,3)", + org.apache.commons.logging;version="[1.2,2)", + org.json;version="[3.0,4)", + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", + org.wso2.carbon.apimgt.api;version="[9.28,10)", + org.wso2.carbon.apimgt.api.model;version="[9.28,10)", + org.wso2.carbon.apimgt.api.model.subscription;version="[9.28,10)", + org.wso2.carbon.apimgt.impl;version="[9.28,10)", + org.wso2.carbon.apimgt.impl.caching;version="[9.28,10)", + org.wso2.carbon.apimgt.impl.dto;version="[9.28,10)", + org.wso2.carbon.apimgt.impl.factory;version="[9.28,10)", + org.wso2.carbon.apimgt.impl.jwt;version="[9.28,10)", + org.wso2.carbon.apimgt.impl.utils;version="[9.28,10)", + org.wso2.carbon.apimgt.keymgt;version="[9.28,10)", + org.wso2.carbon.apimgt.keymgt.handlers;version="[9.28,10)", + org.wso2.carbon.apimgt.keymgt.model;version="[9.28,10)", + org.wso2.carbon.apimgt.keymgt.model.entity;version="[9.28,10)", + org.wso2.carbon.apimgt.keymgt.service;version="[9.28,10)", + io.entgra.device.mgt.core.apimgt.extension.rest.api, + org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.user.api;version="[1.0,2)", + org.wso2.carbon.user.core.service;version="[4.8,5)", + org.wso2.carbon.user.core.tenant;version="[4.8,5)", + org.wso2.carbon.utils.multitenancy;version="[4.8,5)" !io.entgra.device.mgt.core.apimgt.keymgt.extension.internal, diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/KeyManagerConnectorConfiguration.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/KeyManagerConnectorConfiguration.java index 8f1456ee51..191e3a9ba8 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/KeyManagerConnectorConfiguration.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/KeyManagerConnectorConfiguration.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.apimgt.keymgt.extension; +import org.osgi.service.component.annotations.Component; import org.wso2.carbon.apimgt.api.model.ConfigurationDto; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.DefaultKeyManagerConnectorConfiguration; @@ -27,9 +28,10 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -/** - * @scr.component name="io.entgra.device.mgt.core.apimgt.keymgt.extension.customKeyManagerConfigComponent" immediate="true" - */ +@Component( + name = "io.entgra.device.mgt.core.apimgt.keymgt.extension.KeyManagerConnectorConfiguration", + service = DefaultKeyManagerConnectorConfiguration.class, + immediate = true) public class KeyManagerConnectorConfiguration extends DefaultKeyManagerConnectorConfiguration { @Override diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/KeyValidationHandler.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/KeyValidationHandler.java index c577f3c463..868adfc082 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/KeyValidationHandler.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/KeyValidationHandler.java @@ -17,6 +17,10 @@ */ package io.entgra.device.mgt.core.apimgt.keymgt.extension; +import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.Permission; +import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException; +import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagerService; +import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -36,22 +40,12 @@ import org.wso2.carbon.apimgt.keymgt.model.SubscriptionDataStore; import org.wso2.carbon.apimgt.keymgt.model.entity.API; import org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.Permission; -import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException; -import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagerService; -import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.StringTokenizer; +import java.util.*; public class KeyValidationHandler extends DefaultKeyValidationHandler { diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/exception/KeyMgtException.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/exception/KeyMgtException.java index 5aa4d6e6aa..0faf78683c 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/exception/KeyMgtException.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/exception/KeyMgtException.java @@ -28,5 +28,9 @@ public class KeyMgtException extends Exception { public KeyMgtException(String errorMessage) { super(errorMessage); } + + public KeyMgtException(String errorMessage, Exception e) { + super(errorMessage, e); + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/internal/KeyMgtDataHolder.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/internal/KeyMgtDataHolder.java index fd711781a1..96e96000be 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/internal/KeyMgtDataHolder.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/internal/KeyMgtDataHolder.java @@ -18,12 +18,16 @@ package io.entgra.device.mgt.core.apimgt.keymgt.extension.internal; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices; import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService; public class KeyMgtDataHolder { private static final KeyMgtDataHolder thisInstance = new KeyMgtDataHolder(); private KeyMgtService keyMgtService; + private ConsumerRESTAPIServices consumerRESTAPIServices; + private APIApplicationServices apiApplicationServices; public static KeyMgtDataHolder getInstance() { return thisInstance; @@ -37,4 +41,20 @@ public class KeyMgtDataHolder { this.keyMgtService = keyMgtService; } + + public ConsumerRESTAPIServices getConsumerRESTAPIServices() { + return consumerRESTAPIServices; + } + + public void setConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) { + this.consumerRESTAPIServices = consumerRESTAPIServices; + } + + public APIApplicationServices getApiApplicationServices() { + return apiApplicationServices; + } + + public void setApiApplicationServices(APIApplicationServices apiApplicationServices) { + this.apiApplicationServices = apiApplicationServices; + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/internal/KeyMgtServiceComponent.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/internal/KeyMgtServiceComponent.java index 9bbc07fa95..96a05f15f5 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/internal/KeyMgtServiceComponent.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/internal/KeyMgtServiceComponent.java @@ -18,21 +18,25 @@ package io.entgra.device.mgt.core.apimgt.keymgt.extension.internal; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtServiceImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtServiceImpl; +import org.osgi.service.component.annotations.*; -/** - * @scr.component name="io.entgra.device.mgt.core.apimgt.keymgt.extension.keyMgtServiceComponent" immediate="true" - */ +@Component( + name = "io.entgra.device.mgt.core.apimgt.keymgt.extension.internal.KeyMgtServiceComponent", + immediate = true) public class KeyMgtServiceComponent { private static final Log log = LogFactory.getLog(KeyMgtServiceComponent.class); @SuppressWarnings("unused") + @Activate protected void activate(ComponentContext componentContext) { try { if (log.isDebugEnabled()) { @@ -54,9 +58,70 @@ public class KeyMgtServiceComponent { } @SuppressWarnings("unused") + @Deactivate protected void deactivate(ComponentContext componentContext) { if (log.isDebugEnabled()) { log.debug("De-activating Key Management Service Component"); } } + + /** + * Sets APIM Consumer REST API service. + * + * @param consumerRESTAPIServices An instance of ConsumerRESTAPIServices + */ + @Reference( + name = "APIM.consumer.service", + service = io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetConsumerRESTAPIServices") + protected void setConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) { + if (log.isDebugEnabled()) { + log.debug("Setting APIM Consumer REST API Service"); + } + KeyMgtDataHolder.getInstance().setConsumerRESTAPIServices(consumerRESTAPIServices); + } + + /** + * Unset APIM Consumer REST API service + * + * @param consumerRESTAPIServices An instance of ConsumerRESTAPIServices + */ + protected void unsetConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) { + if (log.isDebugEnabled()) { + log.debug("Unsetting APIM Consumer REST API Service"); + } + KeyMgtDataHolder.getInstance().setConsumerRESTAPIServices(null); + } + + /** + * Sets DCR REST API service. + * + * @param apiApplicationServices An instance of APIApplicationServices + */ + @Reference( + name = "APIM.application.service", + service = io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetAPIApplicationServices") + protected void setAPIApplicationServices(APIApplicationServices apiApplicationServices) { + if (log.isDebugEnabled()) { + log.debug("Setting DCR REST API Service"); + } + KeyMgtDataHolder.getInstance().setApiApplicationServices(apiApplicationServices); + } + + /** + * Unset DCR REST API service + * + * @param apiApplicationServices An instance of APIApplicationServices + */ + protected void unsetAPIApplicationServices(APIApplicationServices apiApplicationServices) { + if (log.isDebugEnabled()) { + log.debug("Unsetting DCR REST API Service"); + } + KeyMgtDataHolder.getInstance().setApiApplicationServices(null); + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/service/KeyMgtService.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/service/KeyMgtService.java index f08f92d8c7..b1ecb3c77b 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/service/KeyMgtService.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/service/KeyMgtService.java @@ -24,6 +24,8 @@ import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenResponse; import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.BadRequestException; import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtException; +import java.util.List; + public interface KeyMgtService { /*** @@ -35,11 +37,13 @@ public interface KeyMgtService { * @param callBackUrl callback url of the application * @param tags api tags for api subscription of the application * @param isSaasApp if the application is a saas app + * @param password Password of the owner * @return @{@link DCRResponse} DCR Response object with client credentials * @throws KeyMgtException if any error occurs during DCR process */ DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl, - String[] tags, boolean isSaasApp, int validityPeriod) throws KeyMgtException; + String[] tags, boolean isSaasApp, int validityPeriod, String password, + List supportedGrantTypes, String callbackUrl) throws KeyMgtException; /*** * This method will handle the access token requests diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/service/KeyMgtServiceImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/service/KeyMgtServiceImpl.java index ef6a14ab91..2752bfb4d1 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/service/KeyMgtServiceImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/service/KeyMgtServiceImpl.java @@ -19,6 +19,17 @@ package io.entgra.device.mgt.core.apimgt.keymgt.extension.service; import com.google.gson.Gson; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.ApiApplicationInfo; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.*; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.BadRequestException; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtException; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.internal.KeyMgtDataHolder; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; +import io.entgra.device.mgt.core.device.mgt.core.config.keymanager.KeyManagerConfigurations; import okhttp3.Credentials; import okhttp3.FormBody; import okhttp3.MediaType; @@ -29,23 +40,10 @@ import okhttp3.Response; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONObject; -import org.wso2.carbon.apimgt.api.APIConsumer; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.model.Application; -import org.wso2.carbon.apimgt.impl.APIManagerFactory; import org.wso2.carbon.apimgt.impl.utils.APIUtil; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.DCRResponse; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.KeyManagerPayload; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.KeyMgtConstants; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.OAuthApplication; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenRequest; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenResponse; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.BadRequestException; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtException; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; -import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; -import io.entgra.device.mgt.core.device.mgt.core.config.keymanager.KeyManagerConfigurations; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; @@ -77,7 +75,8 @@ public class KeyMgtServiceImpl implements KeyMgtService { String subTenantUserUsername, subTenantUserPassword, keyManagerName, msg = null; public DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl, - String[] tags, boolean isSaasApp, int validityPeriod) throws KeyMgtException { + String[] tags, boolean isSaasApp, int validityPeriod, + String password, List supportedGrantTypes, String callbackUrl) throws KeyMgtException { if (owner == null) { PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); @@ -98,20 +97,21 @@ public class KeyMgtServiceImpl implements KeyMgtService { .getTenantManager().getTenantId(tenantDomain); } catch (UserStoreException e) { msg = "Error while loading tenant configuration"; - log.error(msg); - throw new KeyMgtException(msg); + log.error(msg, e); + throw new KeyMgtException(msg, e); } kmConfig = getKeyManagerConfig(); if (KeyMgtConstants.SUPER_TENANT.equals(tenantDomain)) { - OAuthApplication dcrApplication = createOauthApplication(clientName, kmConfig.getAdminUsername(), tags, validityPeriod); + OAuthApplication dcrApplication = createOauthApplication(clientName, kmConfig.getAdminUsername(), tags, + validityPeriod, kmConfig.getAdminPassword(), supportedGrantTypes, callbackUrl); return new DCRResponse(dcrApplication.getClientId(), dcrApplication.getClientSecret()); } else { // super-tenant admin dcr and token generation OAuthApplication superTenantOauthApp = createOauthApplication( KeyMgtConstants.RESERVED_OAUTH_APP_NAME_PREFIX + KeyMgtConstants.SUPER_TENANT, - kmConfig.getAdminUsername(), null, validityPeriod); + kmConfig.getAdminUsername(), null, validityPeriod, kmConfig.getAdminPassword(), null, null); String superAdminAccessToken = createAccessToken(superTenantOauthApp); // create new key manager for the tenant, under super-tenant space @@ -127,18 +127,20 @@ public class KeyMgtServiceImpl implements KeyMgtService { .getRealmProperty("reserved_tenant_user_password"); } catch (UserStoreException e) { msg = "Error while loading user realm configuration"; - log.error(msg); - throw new KeyMgtException(msg); + log.error(msg, e); + throw new KeyMgtException(msg, e); } createUserIfNotExists(subTenantUserUsername, subTenantUserPassword); // DCR for the requesting user - OAuthApplication dcrApplication = createOauthApplication(clientName, owner, tags, validityPeriod); + OAuthApplication dcrApplication = createOauthApplication(clientName, owner, tags, validityPeriod, + password, null, null); String requestingUserAccessToken = createAccessToken(dcrApplication); // get application id - Application application = getApplication(clientName, owner); - String applicationUUID = application.getUUID(); + io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application = + getApplication(clientName, requestingUserAccessToken); + String applicationUUID = application.getApplicationId(); // do app key mapping mapApplicationKeys(dcrApplication.getClientId(), dcrApplication.getClientSecret(), keyManagerName, @@ -238,16 +240,16 @@ public class KeyMgtServiceImpl implements KeyMgtService { } } catch (APIManagementException e) { msg = "Error occurred while retrieving application"; - log.error(msg); - throw new KeyMgtException(msg); + log.error(msg, e); + throw new KeyMgtException(msg, e); } catch (IOException e) { msg = "Error occurred while mapping application keys"; - log.error(msg); - throw new KeyMgtException(msg); + log.error(msg, e); + throw new KeyMgtException(msg, e); } catch (UserStoreException e) { msg = "Error occurred while fetching tenant id"; - log.error(msg); - throw new KeyMgtException(msg); + log.error(msg, e); + throw new KeyMgtException(msg, e); } } @@ -284,7 +286,8 @@ public class KeyMgtServiceImpl implements KeyMgtService { client.newCall(request).execute(); } catch (IOException e) { msg = "Error occurred while mapping application keys"; - throw new KeyMgtException(msg); + log.error(msg, e); + throw new KeyMgtException(msg, e); } } @@ -310,8 +313,8 @@ public class KeyMgtServiceImpl implements KeyMgtService { } } catch (UserStoreException e) { msg = "Error when trying to fetch tenant details"; - log.error(msg); - throw new KeyMgtException(msg); + log.error(msg, e); + throw new KeyMgtException(msg, e); } } @@ -323,8 +326,11 @@ public class KeyMgtServiceImpl implements KeyMgtService { * @return @{@link OAuthApplication} OAuth application object * @throws KeyMgtException if any error occurs while creating response object */ - private OAuthApplication createOauthApplication (String clientName, String owner, String[] tags, int validityPeriod) throws KeyMgtException { - String oauthAppCreationPayloadStr = createOauthAppCreationPayload(clientName, owner, tags, validityPeriod); + private OAuthApplication createOauthApplication (String clientName, String owner, String[] tags, + int validityPeriod, String ownerPassword, + List supportedGrantTypes, String callbackUrl) throws KeyMgtException { + String oauthAppCreationPayloadStr = createOauthAppCreationPayload(clientName, owner, tags, validityPeriod, + ownerPassword, supportedGrantTypes, callbackUrl); RequestBody oauthAppCreationPayload = RequestBody.Companion.create(oauthAppCreationPayloadStr, JSON); kmConfig = getKeyManagerConfig(); String dcrEndpoint = kmConfig.getServerUrl() + KeyMgtConstants.DCR_ENDPOINT; @@ -347,8 +353,9 @@ public class KeyMgtServiceImpl implements KeyMgtService { Response response = client.newCall(request).execute(); return gson.fromJson(response.body().string(), OAuthApplication.class); } catch (IOException e) { - msg = "Error occurred while processing the response"; - throw new KeyMgtException(msg); + msg = "Error occurred while processing the response." ; + log.error(msg, e); + throw new KeyMgtException(msg, e); } } @@ -379,7 +386,8 @@ public class KeyMgtServiceImpl implements KeyMgtService { return jsonObject.getString("access_token"); } catch (IOException e) { msg = "Error occurred while reading access token from response"; - throw new KeyMgtException(msg); + log.error(msg, e); + throw new KeyMgtException(msg, e); } } @@ -418,8 +426,8 @@ public class KeyMgtServiceImpl implements KeyMgtService { client.newCall(request).execute(); } catch (IOException e) { msg = "Error occurred while invoking create key manager endpoint"; - log.error(msg); - throw new KeyMgtException(msg); + log.error(msg, e); + throw new KeyMgtException(msg, e); } } @@ -427,28 +435,52 @@ public class KeyMgtServiceImpl implements KeyMgtService { * Retrieves an application by name and owner * * @param applicationName name of the application - * @param owner owner of the application + * @param accessToken Access Token * @return @{@link Application} Application object * @throws KeyMgtException if any error occurs while retrieving the application */ - private Application getApplication(String applicationName, String owner) throws KeyMgtException { + private io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application getApplication(String applicationName, String accessToken) throws KeyMgtException { + + ApiApplicationInfo apiApplicationInfo = new ApiApplicationInfo(); + apiApplicationInfo.setAccess_token(accessToken); try { - APIManagerFactory apiManagerFactory = APIManagerFactory.getInstance(); - APIConsumer apiConsumer = apiManagerFactory.getAPIConsumer(owner); - return apiConsumer.getApplicationsByName(owner, applicationName, ""); - } catch (APIManagementException e) { + ConsumerRESTAPIServices consumerRESTAPIServices = + KeyMgtDataHolder.getInstance().getConsumerRESTAPIServices(); + io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application[] applications = + consumerRESTAPIServices.getAllApplications(apiApplicationInfo, applicationName); + if (applications.length == 1) { + return applications[0]; + } else { + String msg = + "Found invalid number of applications. No of applications found from the APIM: " + applications.length; + log.error(msg); + throw new KeyMgtException(msg); + } + } catch (io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException e) { msg = "Error while trying to retrieve the application"; - log.error(msg); - throw new KeyMgtException(msg); + log.error(msg, e); + throw new KeyMgtException(msg, e); + } catch (UnexpectedResponseException e) { + msg = "Received invalid response for the API applications retrieving REST API call."; + log.error(msg, e); + throw new KeyMgtException(msg, e); + } catch (APIServicesException e) { + msg = "Error occurred while processing the API Response."; + log.error(msg, e); + throw new KeyMgtException(msg, e); } } - private String createOauthAppCreationPayload(String clientName, String owner, String[] tags, int validityPeriod) { + private String createOauthAppCreationPayload(String clientName, String owner, String[] tags, int validityPeriod, + String password, List supportedGrantTypes, String callbackUrl) { JSONObject jsonObject = new JSONObject(); jsonObject.put("applicationName", clientName); jsonObject.put("username", owner); jsonObject.put("tags", tags); jsonObject.put("validityPeriod", validityPeriod); + jsonObject.put("password", password); + jsonObject.put("supportedGrantTypes", supportedGrantTypes); + jsonObject.put("callbackUrl", callbackUrl); return jsonObject.toString(); } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml index 1f8b3b7809..b211a15d26 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml @@ -31,32 +31,34 @@ bundle WSO2 Carbon - API Management Webapp Publisher WSO2 Carbon - API Management Webapp Publisher - http://wso2.org + https://entgra.io - org.powermock - powermock-api-mockito - test + org.apache.felix + org.apache.felix.scr.ds-annotations + provided - org.eclipse.osgi - org.eclipse.osgi + org.powermock + powermock-api-mockito2 + test - org.eclipse.osgi - org.eclipse.osgi.services + org.mockito + mockito-core + test org.testng testng - org.wso2.tomcat + org.wso2.orbit.org.apache.tomcat tomcat - org.wso2.tomcat + org.wso2.orbit.org.apache.tomcat tomcat-servlet-api @@ -64,8 +66,9 @@ org.wso2.carbon.core - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api + provided org.wso2.carbon @@ -80,7 +83,7 @@ gson - org.wso2.orbit.org.scannotation + io.entgra.org.scannotation scannotation @@ -118,8 +121,8 @@ provided - com.h2database.wso2 - h2-database-engine + org.wso2.orbit.com.h2database + h2 test @@ -134,19 +137,27 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.device.mgt.core + + org.wso2.orbit.javax.xml.bind + jaxb-api + provided + - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix maven-bundle-plugin - 1.4.0 true @@ -161,53 +172,45 @@ io.entgra.device.mgt.core.apimgt.webapp.publisher.* - com.google.gson;version="[2.3,2.8.6)", - com.google.gson.reflect;version="[2.3,2.8.6)", - io.swagger.annotations, - javax.servlet;version="2.6", - javax.xml, - javax.xml.bind, - javax.xml.bind.annotation, - javax.xml.parsers, - org.apache.catalina;version="9.0", - org.apache.catalina.core;version="9.0", - org.apache.commons.logging;version="1.2", - org.osgi.framework.*;version="${imp.package.version.osgi.framework}", - org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.scannotation;version="1.0", - org.scannotation.archiveiterator;version="1.0", - org.w3c.dom, + com.google.gson;version="[2.9,3)", + com.google.gson.reflect;version="[2.9,3)", + io.entgra.device.mgt.core.apimgt.annotations;version="[5.0,6)", io.entgra.device.mgt.core.apimgt.extension.rest.api.*, - io.entgra.device.mgt.core.apimgt.annotations, - org.wso2.carbon.apimgt.api, - org.wso2.carbon.apimgt.api.model, - org.wso2.carbon.apimgt.impl, - org.wso2.carbon.apimgt.impl.utils, - io.entgra.device.mgt.core.apimgt.webapp.publisher, io.entgra.device.mgt.core.apimgt.webapp.publisher.config, io.entgra.device.mgt.core.apimgt.webapp.publisher.dto, io.entgra.device.mgt.core.apimgt.webapp.publisher.exception, - io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.listener, - io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.util, io.entgra.device.mgt.core.device.mgt.common.exceptions, + io.entgra.device.mgt.core.device.mgt.common.permission.mgt, io.entgra.device.mgt.core.device.mgt.common.metadata.mgt, io.entgra.device.mgt.core.device.mgt.core.config, io.entgra.device.mgt.core.device.mgt.core.config.permission, - org.wso2.carbon.base;version="1.0", - org.wso2.carbon.context;version="4.6", - org.wso2.carbon;version="4.6", - org.wso2.carbon.core;version="4.6", - org.wso2.carbon.core.util;version="4.6", - org.wso2.carbon.registry.core.service;version="1.0", - org.wso2.carbon.user.api;version="1.0", - org.wso2.carbon.user.core.service;version="4.6", - org.wso2.carbon.user.core.tenant;version="4.6", - org.wso2.carbon.utils;version="4.6", - org.wso2.carbon.utils.multitenancy;version="4.6", - org.apache.commons.lang, - org.json, - io.entgra.device.mgt.core.device.mgt.common.permission.mgt, - io.entgra.device.mgt.core.device.mgt.core.permission.mgt + io.swagger.annotations;version="[1.6,2)", + javax.servlet;version="[2.6,3)", + javax.xml.bind;version="[0.0,1)", + javax.xml.bind.annotation;version="[0.0,1)", + javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}", + org.apache.catalina;version="${catalina.version.range}", + org.apache.catalina.core;version="${catalina.version.range}", + org.apache.commons.lang;version="[2.6,3)", + org.apache.commons.logging;version="[1.2,2)", + org.json;version="[3.0,4)", + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", + org.scannotation;version="[1.0,2)", + org.scannotation.archiveiterator;version="[1.0,2)", + org.w3c.dom, + org.wso2.carbon.apimgt.api;version="[9.28,10)", + org.wso2.carbon.apimgt.api.model;version="[9.28,10)", + org.wso2.carbon.apimgt.impl;version="[9.28,10)", + org.wso2.carbon.apimgt.impl.utils;version="[9.28,10)", + org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.core;version="[4.8,5)", + org.wso2.carbon.core.util;version="[4.8,5)", + org.wso2.carbon.registry.core.service, + org.wso2.carbon.user.api, + org.wso2.carbon.user.core.service;version="[4.8,5)", + org.wso2.carbon.user.core.tenant;version="[4.8,5)", + org.wso2.carbon.utils;version="[4.8,5)" jsr311-api;scope=compile|runtime;inline=false diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java index cab16f8482..c3e5a6bc54 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -68,8 +68,6 @@ import org.wso2.carbon.user.core.tenant.Tenant; import org.wso2.carbon.user.core.tenant.TenantSearchResult; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionUtils; import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException; import java.io.BufferedReader; @@ -82,13 +80,12 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.Date; import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.Date; /** * This class represents the concrete implementation of the APIPublisherService that corresponds to providing all @@ -158,7 +155,9 @@ public class APIPublisherServiceImpl implements APIPublisherService { try { APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); - apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); + apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials( + "ClientForPublisherRestCalls", + "client_credentials password refresh_token"); accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); } catch (APIServicesException e) { @@ -188,19 +187,8 @@ public class APIPublisherServiceImpl implements APIPublisherService { String apiUuid = apiIdentifier.getUUID(); if (!apiFound) { // add new scopes as shared scopes - for (ApiScope apiScope : apiConfig.getScopes()) { - if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, - apiScope.getKey())) { - Scope scope = new Scope(); - scope.setDisplayName(apiScope.getName()); - scope.setDescription(apiScope.getDescription()); - scope.setName(apiScope.getKey()); - List bindings = new ArrayList<>(apiScope.getRoles()); - bindings.add(ADMIN_ROLE_KEY); - scope.setBindings(bindings); - publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); - } - } + addNewSharedScope(apiConfig.getScopes(), publisherRESTAPIServices, apiApplicationKey, + accessTokenInfo); APIInfo api = getAPI(apiConfig, true); APIInfo createdAPI = publisherRESTAPIServices.addAPI(apiApplicationKey, accessTokenInfo, api); apiUuid = createdAPI.getId(); @@ -240,7 +228,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { } } else { if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) { - // With 4.x to 5.x upgrade // - there cannot be same local scope assigned in 2 different APIs // - local scopes will be deprecated in the future, so need to move all scopes as shared scopes @@ -255,52 +242,18 @@ public class APIPublisherServiceImpl implements APIPublisherService { // 1. add new scopes as shared scopes // 2. update the API adding scopes for the URI Templates - Set scopesToMoveAsSharedScopes = new HashSet<>(); - for (ApiScope apiScope : apiConfig.getScopes()) { - // if the scope is not available as shared scope, and it is assigned to an API as a local scope - // need remove the local scope and add as a shared scope - if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, - apiScope.getKey())) { - if (apiProvider.isScopeKeyAssignedLocally(apiIdentifier, apiScope.getKey(), tenantId)) { - // collect scope to move as shared scopes - scopesToMoveAsSharedScopes.add(apiScope); - } else { - // if new scope add as shared scope - Scope scope = new Scope(); - scope.setName(apiScope.getKey()); - scope.setDescription(apiScope.getDescription()); - scope.setDisplayName(apiScope.getName()); - List bindings = new ArrayList<>(apiScope.getRoles()); - bindings.add(ADMIN_ROLE_KEY); - scope.setBindings(bindings); - publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); + // It is guaranteed that there is no local scope if we update from 5.0.0 to the most + // recent version. Therefore, if the scope is not already available as a shared scope, + // new scopes must be added as shared scopes. Additionally, it is necessary to + // upgrade to 5.0.0 first before updating from 5.0.0 to the most recent version if we + // are updating from a version that is older than 5.0.0. - } - } - } + addNewSharedScope(apiConfig.getScopes(), publisherRESTAPIServices, apiApplicationKey, + accessTokenInfo); // Get existing API APIInfo existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, apiUuid); - if (scopesToMoveAsSharedScopes.size() > 0) { - // update API to remove local scopes - APIInfo api = getAPI(apiConfig, false); - api.setLifeCycleStatus(existingAPI.getLifeCycleStatus()); - publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api); - - for (ApiScope apiScope : scopesToMoveAsSharedScopes) { - Scope scope = new Scope(); - scope.setName(apiScope.getKey()); - scope.setDescription(apiScope.getDescription()); - scope.setDisplayName(apiScope.getName()); - List bindings = new ArrayList<>(apiScope.getRoles()); - bindings.add(ADMIN_ROLE_KEY); - scope.setBindings(bindings); - publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); - } - } - - existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, apiUuid); APIInfo api = getAPI(apiConfig, true); api.setLifeCycleStatus(existingAPI.getLifeCycleStatus()); api.setId(apiUuid); @@ -453,6 +406,34 @@ public class APIPublisherServiceImpl implements APIPublisherService { } } + /** + * Add new Shared Scopes + * + * @param apiScopes set of API scopes + * @param publisherRESTAPIServices {@link PublisherRESTAPIServices} + * @param apiApplicationKey API application Key + * @param accessTokenInfo Details of access token + * @throws BadRequestException if invalid payload receives to add new shared scopes. + * @throws UnexpectedResponseException if the response is not either 200 or 400. + * @throws APIServicesException if error occurred while processing the response. + */ + private void addNewSharedScope(Set apiScopes, PublisherRESTAPIServices publisherRESTAPIServices, + APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) throws BadRequestException, UnexpectedResponseException, APIServicesException { + for (ApiScope apiScope : apiScopes) { + if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, + apiScope.getKey())) { + Scope scope = new Scope(); + scope.setName(apiScope.getKey()); + scope.setDescription(apiScope.getDescription()); + scope.setDisplayName(apiScope.getName()); + List bindings = new ArrayList<>(apiScope.getRoles()); + bindings.add(ADMIN_ROLE_KEY); + scope.setBindings(bindings); + publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); + } + } + } + @Override public void addDefaultScopesIfNotExist() throws APIManagerPublisherException { WebappPublisherConfig config = WebappPublisherConfig.getInstance(); @@ -471,7 +452,9 @@ public class APIPublisherServiceImpl implements APIPublisherService { APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); APIApplicationKey apiApplicationKey = - apiApplicationServices.createAndRetrieveApplicationCredentials(); + apiApplicationServices.createAndRetrieveApplicationCredentials( + "ClientForPublisherRestCalls", "client_credentials password refresh_token" + ); AccessTokenInfo accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); @@ -526,7 +509,8 @@ public class APIPublisherServiceImpl implements APIPublisherService { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); try { APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); - apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); + apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials("ClientForPublisherRestCalls", + "client_credentials password refresh_token"); accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); } catch (APIServicesException e) { @@ -621,7 +605,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { // add permission if not exist try { PermissionUtils.putPermission(permission); - } catch(PermissionManagementException e) { + } catch (PermissionManagementException e) { log.error("Error when adding permission ", e); } } @@ -667,7 +651,10 @@ public class APIPublisherServiceImpl implements APIPublisherService { AccessTokenInfo accessTokenInfo; try { APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); - apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); + apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials( + "ClientForPublisherRestCalls", + "client_credentials password refresh_token" + ); accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); } catch (APIServicesException e) { @@ -853,7 +840,9 @@ public class APIPublisherServiceImpl implements APIPublisherService { scope.setName(apiUriTemplate.getScope().getKey()); scope.setDisplayName(apiUriTemplate.getScope().getName()); scope.setDescription(apiUriTemplate.getScope().getDescription()); - scope.setBindings(apiUriTemplate.getScope().getRoles()); + List bindings = new ArrayList<>(apiUriTemplate.getScope().getRoles()); + bindings.add(ADMIN_ROLE_KEY); + scope.setBindings(bindings); JSONObject scopeObject = new JSONObject(); scopeObject.put("scope", new JSONObject(gson.toJson(scope))); diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherStartupHandler.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherStartupHandler.java index e039259b92..bd3451c4e3 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherStartupHandler.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherStartupHandler.java @@ -18,23 +18,40 @@ package io.entgra.device.mgt.core.apimgt.webapp.publisher; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import com.google.gson.Gson; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope; import io.entgra.device.mgt.core.apimgt.webapp.publisher.exception.APIManagerPublisherException; import io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherDataHolder; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataKeyAlreadyExistsException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; +import io.entgra.device.mgt.core.device.mgt.core.config.permission.DefaultPermission; +import io.entgra.device.mgt.core.device.mgt.core.config.permission.DefaultPermissions; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.core.ServerStartupObserver; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.Stack; public class APIPublisherStartupHandler implements ServerStartupObserver { private static final Log log = LogFactory.getLog(APIPublisherStartupHandler.class); - private static int retryTime = 2000; private static final int CONNECTION_RETRY_FACTOR = 2; private static final int MAX_RETRY_COUNT = 5; - private static Stack failedAPIsStack = new Stack<>(); + private static final Gson gson = new Gson(); + private static final Stack failedAPIsStack = new Stack<>(); + private static int retryTime = 2000; private static Stack currentAPIsStack; - + private final List publishedAPIs = new ArrayList<>(); private APIPublisherService publisher; @Override @@ -44,71 +61,97 @@ public class APIPublisherStartupHandler implements ServerStartupObserver { @Override public void completedServerStartup() { + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); APIPublisherDataHolder.getInstance().setServerStarted(true); currentAPIsStack = APIPublisherDataHolder.getInstance().getUnpublishedApis(); - Thread t = new Thread(new Runnable() { - @Override - public void run() { - if (log.isDebugEnabled()) { - log.debug("Server has just started, hence started publishing unpublished APIs"); - log.debug("Total number of unpublished APIs: " - + APIPublisherDataHolder.getInstance().getUnpublishedApis().size()); - } - publisher = APIPublisherDataHolder.getInstance().getApiPublisherService(); - int retryCount = 0; - while (retryCount < MAX_RETRY_COUNT && (!failedAPIsStack.isEmpty() || !currentAPIsStack.isEmpty())) { + Thread t = new Thread(() -> { + if (log.isDebugEnabled()) { + log.debug("Server has just started, hence started publishing unpublished APIs"); + log.debug("Total number of unpublished APIs: " + + APIPublisherDataHolder.getInstance().getUnpublishedApis().size()); + } + publisher = APIPublisherDataHolder.getInstance().getApiPublisherService(); + int retryCount = 0; + while (retryCount < MAX_RETRY_COUNT && (!failedAPIsStack.isEmpty() || !currentAPIsStack.isEmpty())) { + if (retryCount > 0) { try { retryTime = retryTime * CONNECTION_RETRY_FACTOR; Thread.sleep(retryTime); } catch (InterruptedException te) { //do nothing. } - Stack failedApis; - if (!APIPublisherDataHolder.getInstance().getUnpublishedApis().isEmpty()) { - publishAPIs(currentAPIsStack, failedAPIsStack); - failedApis = failedAPIsStack; - } else { - publishAPIs(failedAPIsStack, currentAPIsStack); - failedApis = currentAPIsStack; - } - retryCount++; - if (retryCount == MAX_RETRY_COUNT && !failedApis.isEmpty()) { - StringBuilder error = new StringBuilder(); - error.append("Error occurred while publishing API ['"); - while (!failedApis.isEmpty()) { - APIConfig api = failedApis.pop(); - error.append(api.getName() + ","); - } - error.append("']"); - log.error(error.toString()); + } + Stack failedApis; + if (!currentAPIsStack.isEmpty()) { + publishAPIs(currentAPIsStack, failedAPIsStack); + failedApis = failedAPIsStack; + } else { + publishAPIs(failedAPIsStack, currentAPIsStack); + failedApis = currentAPIsStack; + } + retryCount++; + if (retryCount == MAX_RETRY_COUNT && !failedApis.isEmpty()) { + StringBuilder error = new StringBuilder(); + error.append("Error occurred while publishing API ['"); + while (!failedApis.isEmpty()) { + APIConfig api = failedApis.pop(); + error.append(api.getName() + ","); } + error.append("']"); + log.info(error.toString()); } + } - try { - publisher.updateScopeRoleMapping(); - publisher.addDefaultScopesIfNotExist(); - } catch (APIManagerPublisherException e) { - log.error("failed to update scope role mapping.", e); - } + try { + publisher.updateScopeRoleMapping(); + publisher.addDefaultScopesIfNotExist(); + } catch (APIManagerPublisherException e) { + log.error("failed to update scope role mapping.", e); + } - // execute after api publishing - for (PostApiPublishingObsever observer : APIPublisherDataHolder.getInstance().getPostApiPublishingObseverList()) { - if (log.isDebugEnabled()) { - log.debug("Executing " + observer.getClass().getName()); - } - observer.execute(); + try { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); + updateScopeMetadataEntryWithDefaultScopes(); + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + + log.info("Successfully published : [" + publishedAPIs + "]. " + + "and failed : [" + failedAPIsStack + "] " + + "Total successful count : [" + publishedAPIs.size() + "]. " + + "Failed count : [" + failedAPIsStack.size() + "]"); + + // execute after api publishing + for (PostApiPublishingObsever observer : APIPublisherDataHolder.getInstance().getPostApiPublishingObseverList()) { + if (log.isDebugEnabled()) { + log.debug("Executing " + observer.getClass().getName()); } - log.info("Finish executing PostApiPublishingObsevers"); + observer.execute(); } + log.info("Finish executing PostApiPublishingObsevers"); }); t.start(); + log.info("Starting API publishing procedure"); } +/** + * Publish apis provided by the API stack, if failed while publishing, then failed API will be added to + * the failed API stack + * + * @param apis Stack of APIs to publish + * @param failedStack Stack to record failed APIs + */ private void publishAPIs(Stack apis, Stack failedStack) { while (!apis.isEmpty()) { APIConfig api = apis.pop(); try { publisher.publishAPI(api); + for (ApiScope scope : api.getScopes()) { + APIPublisherDataHolder.getInstance().getPermScopeMapping().putIfAbsent(scope.getPermissions(), scope.getKey()); + } + publishedAPIs.add(api.getName()); + log.info("Successfully published API [" + api.getName() + "]"); } catch (APIManagerPublisherException e) { log.error("failed to publish api.", e); failedStack.push(api); @@ -116,4 +159,47 @@ public class APIPublisherStartupHandler implements ServerStartupObserver { } } + /** + * Update permission scope mapping entry with default scopes if perm-scope-mapping entry exists, otherwise this function + * will create that entry and update the value with default permissions. + */ + private void updateScopeMetadataEntryWithDefaultScopes() { + Map permScopeMap = APIPublisherDataHolder.getInstance().getPermScopeMapping(); + Metadata permScopeMapping; + + MetadataManagementService metadataManagementService = APIPublisherDataHolder.getInstance().getMetadataManagementService(); + DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); + DefaultPermissions defaultPermissions = deviceManagementConfig.getDefaultPermissions(); + + try { + permScopeMapping = metadataManagementService.retrieveMetadata(Constants.PERM_SCOPE_MAPPING_META_KEY); + boolean entryAlreadyExists = permScopeMapping != null; + if (permScopeMap == null || permScopeMap.isEmpty()) { + permScopeMap = entryAlreadyExists ? gson.fromJson(permScopeMapping.getMetaValue(), HashMap.class) : + new HashMap<>(); + } + + for (DefaultPermission defaultPermission : defaultPermissions.getDefaultPermissions()) { + permScopeMap.putIfAbsent(defaultPermission.getName(), defaultPermission.getScopeMapping().getKey()); + } + + + permScopeMapping = new Metadata(); + permScopeMapping.setMetaKey(Constants.PERM_SCOPE_MAPPING_META_KEY); + permScopeMapping.setMetaValue(gson.toJson(permScopeMap)); + + if (entryAlreadyExists) { + metadataManagementService.updateMetadata(permScopeMapping); + } else { + metadataManagementService.createMetadata(permScopeMapping); + } + + APIPublisherDataHolder.getInstance().setPermScopeMapping(permScopeMap); + log.info(Constants.PERM_SCOPE_MAPPING_META_KEY + "entry updated successfully"); + } catch (MetadataKeyAlreadyExistsException e) { + log.error("Metadata entry already exists for " + Constants.PERM_SCOPE_MAPPING_META_KEY); + } catch (MetadataManagementException e) { + log.error("Error encountered while updating permission scope mapping metadata with default scopes"); + } + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherUtil.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherUtil.java index e982d3d6e8..f8d7638480 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherUtil.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherUtil.java @@ -23,26 +23,34 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.apimgt.annotations.Scope; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResource; import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResourceConfiguration; import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig; import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope; import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiUriTemplate; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherDataHolder; import io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.util.AnnotationProcessor; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; +import org.apache.catalina.core.StandardContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.core.util.Utils; +import org.wso2.carbon.user.api.TenantManager; import org.wso2.carbon.user.api.UserStoreException; import javax.servlet.ServletContext; +import java.io.IOException; import java.util.*; public class APIPublisherUtil { public static final String API_VERSION_PARAM = "{version}"; + public static final String PROPERTY_PROFILE = "profile"; private static final Log log = LogFactory.getLog(APIPublisherUtil.class); private static final String DEFAULT_API_VERSION = "1.0.0"; private static final String API_CONFIG_DEFAULT_VERSION = "1.0.0"; @@ -53,10 +61,10 @@ public class APIPublisherUtil { private static final String PARAM_MANAGED_API_IS_SECURED = "managed-api-isSecured"; private static final String PARAM_SHARED_WITH_ALL_TENANTS = "isSharedWithAllTenants"; private static final String PARAM_PROVIDER_TENANT_DOMAIN = "providerTenantDomain"; - private static final String NON_SECURED_RESOURCES = "nonSecuredEndPoints"; private static final String AUTH_TYPE_NON_SECURED = "None"; private static final String PARAM_IS_DEFAULT = "isDefault"; + private static final Gson gson = new Gson(); public static String getServerBaseUrl() { WebappPublisherConfig webappPublisherConfig = WebappPublisherConfig.getInstance(); @@ -255,7 +263,7 @@ public class APIPublisherUtil { policy = null; } apiConfig.setPolicy(policy); - + setResourceAuthTypes(servletContext, apiConfig); return apiConfig; } @@ -318,7 +326,7 @@ public class APIPublisherUtil { } } if (log.isDebugEnabled()) { - log.debug("API swagger definition: " + swaggerDefinition.toString()); + log.debug("API swagger definition: " + swaggerDefinition); } return swaggerDefinition.toString(); } @@ -336,8 +344,7 @@ public class APIPublisherUtil { String fullPaath = ""; if (!template.getUriTemplate().equals(AnnotationProcessor.WILD_CARD)) { fullPaath = apiConfig.getContext() + template.getUriTemplate(); - } - else { + } else { fullPaath = apiConfig.getContext(); } for (String context : resourcesList) { @@ -349,4 +356,73 @@ public class APIPublisherUtil { } apiConfig.setUriTemplates(templates); } + + /** + * This method will extract and retrieve the API resource configuration by processing the API resources + * @param standardContext {@link StandardContext} + * @param servletContext {@link ServletContext} + * @return Extracted {@link APIResourceConfiguration} list describing from the servlet context + * @throws IOException Throws when error occurred while processing the swagger annotations + * @throws ClassNotFoundException Throws when error occurred while extracting api configurations + */ + public static List getAPIResourceConfiguration(StandardContext standardContext, ServletContext servletContext) + throws IOException, ClassNotFoundException { + List apiResourceConfigurations = new ArrayList<>(); + String profile = System.getProperty(PROPERTY_PROFILE); + if (WebappPublisherConfig.getInstance().getProfiles().getProfile().contains(profile.toLowerCase())) { + AnnotationProcessor annotationProcessor = new AnnotationProcessor(standardContext); + Set annotatedSwaggerAPIClasses = annotationProcessor. + scanStandardContext(io.swagger.annotations.SwaggerDefinition.class.getName()); + apiResourceConfigurations = annotationProcessor.extractAPIInfo(servletContext, + annotatedSwaggerAPIClasses); + } + return apiResourceConfigurations; + } + + /** + * This method can use to publish the apis after the server startup complete. + * + * @param apiConfig {@link APIConfig} Contains API definition + */ + public static void publishAPIAfterServerStartup(APIConfig apiConfig) { + APIPublisherDataHolder apiPublisherDataHolder = APIPublisherDataHolder.getInstance(); + if (!apiPublisherDataHolder.isServerStarted()) { + if (log.isDebugEnabled()) { + log.debug("Abort publishing the API [" + apiConfig.getName() + "]. Server still starting"); + } + throw new IllegalStateException("Server starting procedure is still not completed"); + } + + TenantManager tenantManager = apiPublisherDataHolder.getTenantManager(); + if (tenantManager == null) { + throw new IllegalStateException("Tenant manager service not initialized properly"); + } + try { + if (tenantManager.isTenantActive(tenantManager.getTenantId(apiConfig.getTenantDomain()))) { + APIPublisherService apiPublisherService = apiPublisherDataHolder.getApiPublisherService(); + if (apiPublisherService == null) { + throw new IllegalStateException("API Publisher service is not initialized properly"); + } + apiPublisherService.publishAPI(apiConfig); + for (ApiScope scope : apiConfig.getScopes()) { + apiPublisherDataHolder.getPermScopeMapping().putIfAbsent(scope.getPermissions(), scope.getKey()); + } + + Metadata permScopeMapping = new Metadata(); + permScopeMapping.setMetaKey(Constants.PERM_SCOPE_MAPPING_META_KEY); + permScopeMapping.setMetaValue(gson.toJson(apiPublisherDataHolder.getPermScopeMapping())); + + try { + apiPublisherDataHolder.getMetadataManagementService().updateMetadata(permScopeMapping); + } catch (MetadataManagementException e) { + log.error("Error encountered while updating the " + Constants.PERM_SCOPE_MAPPING_META_KEY + "entry"); + } + } else { + log.error("Can't find an active tenant under tenant domain " + apiConfig.getTenantDomain()); + } + } catch (Throwable e) { + log.error("Error occurred while publishing API '" + apiConfig.getName() + "' with the context '" + + apiConfig.getContext() + "' and version '" + apiConfig.getVersion() + "'", e); + } + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/config/WebappPublisherConfig.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/config/WebappPublisherConfig.java index 0b7225b359..d1d55687ec 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/config/WebappPublisherConfig.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/config/WebappPublisherConfig.java @@ -18,10 +18,10 @@ package io.entgra.device.mgt.core.apimgt.webapp.publisher.config; -import org.w3c.dom.Document; import io.entgra.device.mgt.core.apimgt.webapp.publisher.InvalidConfigurationStateException; import io.entgra.device.mgt.core.apimgt.webapp.publisher.WebappPublisherConfigurationFailedException; import io.entgra.device.mgt.core.apimgt.webapp.publisher.WebappPublisherUtil; +import org.w3c.dom.Document; import org.wso2.carbon.utils.CarbonUtils; import javax.xml.bind.JAXBContext; diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java index d00f50e35f..8e243ab263 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java @@ -33,6 +33,7 @@ import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.carbon.utils.ConfigurationContextService; +import java.util.HashMap; import java.util.Map; import java.util.Stack; import java.util.List; @@ -48,7 +49,7 @@ public class APIPublisherDataHolder { private RegistryService registryService; private boolean isServerStarted; private Stack unpublishedApis = new Stack<>(); - private Map permScopeMapping; + private Map permScopeMapping = new HashMap<>(); private APIApplicationServices apiApplicationServices; private PublisherRESTAPIServices publisherRESTAPIServices; private MetadataManagementService metadataManagementService; diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java index 62684c2215..a6b2773d47 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java @@ -29,55 +29,21 @@ import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherService; import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherServiceImpl; import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherStartupHandler; import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.core.ServerStartupObserver; import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.user.core.service.RealmService; import java.util.HashMap; -/** - * @scr.component name="io.entgra.device.mgt.core.apimgt.webapp.publisher" immediate="true" - * @scr.reference name="user.realmservice.default" - * interface="org.wso2.carbon.user.core.service.RealmService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRealmService" - * unbind="unsetRealmService" - * @scr.reference name="registry.service" - * interface="org.wso2.carbon.registry.core.service.RegistryService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRegistryService" - * unbind="unsetRegistryService" - * @scr.reference name="APIM.application.service" - * interface="io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices" - * cardinality="1..1" - * policy="dynamic" - * bind="setAPIApplicationServices" - * unbind="unsetAPIApplicationServices" - * @scr.reference name="APIM.publisher.service" - * interface="io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices" - * cardinality="1..1" - * policy="dynamic" - * bind="setPublisherRESTAPIServices" - * unbind="unsetPublisherRESTAPIServices" - * @scr.reference name="io.entgra.meta.mgt" - * interface="io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService" - * cardinality="0..1" - * policy="dynamic" - * bind="setMetaDataMgtService" - * unbind="unsetMetaDataMgtService" - * @scr.reference name="postApiPublishingObsever" - * interface="io.entgra.device.mgt.core.apimgt.webapp.publisher.PostApiPublishingObsever" - * cardinality="0..n" - * policy="dynamic" - * bind="setPostApiPublishingObsever" - * unbind="unsetPostApiPublishingObsever" - */ +@Component( + name = "io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherServiceComponent", + immediate = true) public class APIPublisherServiceComponent { private static Log log = LogFactory.getLog(APIPublisherServiceComponent.class); + @Activate protected void activate(ComponentContext componentContext) { try { if (log.isDebugEnabled()) { @@ -102,6 +68,7 @@ public class APIPublisherServiceComponent { } } + @Deactivate protected void deactivate(ComponentContext componentContext) { //do nothing } @@ -119,6 +86,12 @@ public class APIPublisherServiceComponent { bundleContext.registerService(ServerStartupObserver.class, new APIPublisherStartupHandler(), null); } + @Reference( + name = "user.realmservice.default", + service = org.wso2.carbon.user.core.service.RealmService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRealmService") protected void setRealmService(RealmService realmService) { if (log.isDebugEnabled()) { log.debug("Setting Realm Service"); @@ -133,6 +106,12 @@ public class APIPublisherServiceComponent { APIPublisherDataHolder.getInstance().setRealmService(null); } + @Reference( + name = "registry.service", + service = org.wso2.carbon.registry.core.service.RegistryService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRegistryService") protected void setRegistryService(RegistryService registryService) { if (registryService != null && log.isDebugEnabled()) { log.debug("Registry service initialized"); @@ -144,6 +123,12 @@ public class APIPublisherServiceComponent { APIPublisherDataHolder.getInstance().setRegistryService(null); } + @Reference( + name = "APIM.application.service", + service = io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetAPIApplicationServices") protected void setAPIApplicationServices(APIApplicationServices apiApplicationServices) { if (log.isDebugEnabled()) { log.debug("Setting DCR REST API Service"); @@ -158,6 +143,12 @@ public class APIPublisherServiceComponent { APIPublisherDataHolder.getInstance().setApiApplicationServices(null); } + @Reference( + name = "APIM.publisher.service", + service = io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetPublisherRESTAPIServices") protected void setPublisherRESTAPIServices(PublisherRESTAPIServices publisherRESTAPIServices) { if (log.isDebugEnabled()) { log.debug("Setting APIM Publisher REST API Service"); @@ -172,6 +163,12 @@ public class APIPublisherServiceComponent { APIPublisherDataHolder.getInstance().setPublisherRESTAPIServices(null); } + @Reference( + name = "io.entgra.meta.mgt", + service = io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetMetaDataMgtService") protected void setMetaDataMgtService(MetadataManagementService metadataManagementService) { if (metadataManagementService != null && log.isDebugEnabled()) { log.debug("Meta data mgt mgt service initialized"); @@ -183,6 +180,12 @@ public class APIPublisherServiceComponent { APIPublisherDataHolder.getInstance().setMetadataManagementService(null); } + @Reference( + name = "postApiPublishingObsever", + service = io.entgra.device.mgt.core.apimgt.webapp.publisher.PostApiPublishingObsever.class, + cardinality = ReferenceCardinality.MULTIPLE, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetPostApiPublishingObsever") protected void setPostApiPublishingObsever(PostApiPublishingObsever postApiPublishingObsever) { if (log.isDebugEnabled()) { log.debug("Setting PostApiPublishingObsever"); diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java index bbd2fd952e..90c0fb4d6d 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java @@ -17,137 +17,58 @@ */ package io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.listener; -import com.google.gson.Gson; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; -import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; -import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; -import io.entgra.device.mgt.core.device.mgt.core.config.permission.DefaultPermission; -import io.entgra.device.mgt.core.device.mgt.core.config.permission.DefaultPermissions; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIConfig; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherUtil; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResourceConfiguration; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherDataHolder; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleEvent; import org.apache.catalina.LifecycleListener; import org.apache.catalina.core.StandardContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIConfig; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherService; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherUtil; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResourceConfiguration; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherDataHolder; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.util.AnnotationProcessor; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.user.api.UserStoreException; import javax.servlet.ServletContext; import java.io.IOException; -import java.util.HashMap; import java.util.List; -import java.util.Map; -import java.util.Set; @SuppressWarnings("unused") public class APIPublisherLifecycleListener implements LifecycleListener { + public static final String PROFILE_DEFAULT = "default"; private static final Log log = LogFactory.getLog(APIPublisherLifecycleListener.class); private static final String PARAM_MANAGED_API_ENABLED = "managed-api-enabled"; - public static final String PROPERTY_PROFILE = "profile"; - public static final String PROFILE_DT_WORKER = "dtWorker"; - public static final String PROFILE_DEFAULT = "default"; @Override public void lifecycleEvent(LifecycleEvent lifecycleEvent) { - if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType()) ) { - if (WebappPublisherConfig.getInstance() - .isPublished()) { - StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); - ServletContext servletContext = context.getServletContext(); - String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); - boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); + if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) { - String profile = System.getProperty(PROPERTY_PROFILE); - if (WebappPublisherConfig.getInstance().getProfiles().getProfile().contains(profile.toLowerCase()) - && isManagedApi) { - try { - AnnotationProcessor annotationProcessor = new AnnotationProcessor(context); - Set annotatedSwaggerAPIClasses = annotationProcessor. - scanStandardContext(io.swagger.annotations.SwaggerDefinition.class.getName()); - List apiDefinitions = annotationProcessor.extractAPIInfo(servletContext, - annotatedSwaggerAPIClasses); + APIPublisherDataHolder apiPublisherDataHolder = APIPublisherDataHolder.getInstance(); + StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); + ServletContext servletContext = context.getServletContext(); + String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); + boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); - APIPublisherDataHolder apiPublisherDataHolder = APIPublisherDataHolder.getInstance(); - MetadataManagementService metadataManagementService = - apiPublisherDataHolder.getMetadataManagementService(); - Metadata metadata = metadataManagementService.retrieveMetadata("perm-scope-mapping"); - if (metadata != null) { - HashMap permScopeMapping = - new Gson().fromJson(metadata.getMetaValue().toString(), HashMap.class); - apiPublisherDataHolder.setPermScopeMapping(permScopeMapping); - } + if (isManagedApi) { + if (WebappPublisherConfig.getInstance().isPublished() || WebappPublisherConfig.getInstance().isEnabledUpdateApi()) { - Map permScopeMap = apiPublisherDataHolder.getPermScopeMapping(); - for (APIResourceConfiguration apiDefinition : apiDefinitions) { - APIConfig apiConfig = APIPublisherUtil.buildApiConfig(servletContext, apiDefinition); - for (ApiScope scope : apiConfig.getScopes()) { - permScopeMap.put(scope.getPermissions(), scope.getKey()); - } - APIPublisherUtil.setResourceAuthTypes(servletContext,apiConfig); - try { - int tenantId = APIPublisherDataHolder.getInstance().getTenantManager(). - getTenantId(apiConfig.getTenantDomain()); + try { + List apiResourceConfigurations = + APIPublisherUtil.getAPIResourceConfiguration(context, servletContext); - boolean isTenantActive = APIPublisherDataHolder.getInstance(). - getTenantManager().isTenantActive(tenantId); - if (isTenantActive) { - boolean isServerStarted = APIPublisherDataHolder.getInstance().isServerStarted(); - if (isServerStarted) { - APIPublisherService apiPublisherService = - APIPublisherDataHolder.getInstance().getApiPublisherService(); - if (apiPublisherService == null) { - throw new IllegalStateException( - "API Publisher service is not initialized properly"); - } - apiPublisherService.publishAPI(apiConfig); - } else { - if (log.isDebugEnabled()) { - log.debug("Server has not started yet. Hence adding API '" + - apiConfig.getName() + "' to the queue"); - } - APIPublisherDataHolder.getInstance().getUnpublishedApis().push(apiConfig); - } + if (WebappPublisherConfig.getInstance().isPublished()) { + for (APIResourceConfiguration apiDefinition : apiResourceConfigurations) { + APIConfig apiConfig = APIPublisherUtil.buildApiConfig(servletContext, apiDefinition); + if (apiPublisherDataHolder.isServerStarted()) { + APIPublisherUtil.publishAPIAfterServerStartup(apiConfig); } else { - log.error("No tenant [" + apiConfig.getTenantDomain() + "] " + - "found when publishing the Web app"); + apiPublisherDataHolder.getUnpublishedApis().push(apiConfig); } - } catch (Throwable e) { - log.error("Error occurred while publishing API '" + apiConfig.getName() + - "' with the context '" + apiConfig.getContext() + - "' and version '" + apiConfig.getVersion() + "'", e); } } - - Metadata existingMetaData = metadataManagementService.retrieveMetadata("perm-scope" + - "-mapping"); - if (existingMetaData != null) { - existingMetaData.setMetaValue(new Gson().toJson(permScopeMap)); - metadataManagementService.updateMetadata(existingMetaData); - } else { - Metadata newMetaData = new Metadata(); - newMetaData.setMetaKey("perm-scope-mapping"); - - DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); - DefaultPermissions defaultPermissions = deviceManagementConfig.getDefaultPermissions(); - - for (DefaultPermission defaultPermission : defaultPermissions.getDefaultPermissions()) { - permScopeMap.put(defaultPermission.getName(), defaultPermission.getScopeMapping().getKey()); - } - newMetaData.setMetaValue(new Gson().toJson(permScopeMap)); - metadataManagementService.createMetadata(newMetaData); - } - apiPublisherDataHolder.setPermScopeMapping(permScopeMap); } catch (IOException e) { log.error("Error encountered while discovering annotated classes", e); } catch (ClassNotFoundException e) { @@ -160,24 +81,6 @@ public class APIPublisherLifecycleListener implements LifecycleListener { log.error("Failed to Publish api from " + servletContext.getContextPath(), e); } } - } else { - APIPublisherDataHolder apiPublisherDataHolder = APIPublisherDataHolder.getInstance(); - MetadataManagementService metadataManagementService = - apiPublisherDataHolder.getMetadataManagementService(); - try { - Metadata existingMetaData = metadataManagementService.retrieveMetadata("perm-scope" + - "-mapping"); - if (existingMetaData != null) { - existingMetaData.setMetaValue(new Gson().toJson(apiPublisherDataHolder.getPermScopeMapping() - )); - metadataManagementService.updateMetadata(existingMetaData); - } else { - log.error("Couldn't find 'perm-scope-mapping' Meta entry while API publishing has been turned" + - " off."); - } - } catch (MetadataManagementException e) { - log.error("Failed to Load Meta-Mgt data.", e); - } } } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java index b044c9f72a..ffc1e2f7e7 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java @@ -20,27 +20,18 @@ package io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.util; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherUtil; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResource; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResourceConfiguration; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.SwaggerDefinition; import org.apache.catalina.core.StandardContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherUtil; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResource; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResourceConfiguration; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope; import javax.servlet.ServletContext; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HEAD; -import javax.ws.rs.HttpMethod; -import javax.ws.rs.OPTIONS; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; +import javax.ws.rs.*; import java.io.File; import java.io.IOException; import java.lang.annotation.Annotation; diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/util/ExtendedFileProtocolIteratorFactory.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/util/ExtendedFileProtocolIteratorFactory.java index 3d756e2eff..f7391c223c 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/util/ExtendedFileProtocolIteratorFactory.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/lifecycle/util/ExtendedFileProtocolIteratorFactory.java @@ -18,7 +18,6 @@ package io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.util; import org.scannotation.archiveiterator.*; - import java.io.File; import java.io.IOException; import java.net.URL; diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceTest.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceTest.java index cd8f1cd4f0..bd959e2f3a 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceTest.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceTest.java @@ -17,6 +17,13 @@ */ package io.entgra.device.mgt.core.apimgt.webapp.publisher; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.exception.APIManagerPublisherException; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherDataHolder; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.MockAPICollectionApi; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.MockAPIIndividualApi; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.TestUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mockito.Mockito; @@ -32,13 +39,6 @@ import org.wso2.carbon.apimgt.integration.generated.client.publisher.api.APIIndi import org.wso2.carbon.apimgt.integration.generated.client.publisher.model.API; import org.wso2.carbon.apimgt.integration.generated.client.publisher.model.APIInfo; import org.wso2.carbon.apimgt.integration.generated.client.publisher.model.APIList; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.exception.APIManagerPublisherException; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherDataHolder; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.MockAPICollectionApi; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.MockAPIIndividualApi; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.TestUtils; import java.lang.reflect.Field; import java.util.*; diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherUtilTest.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherUtilTest.java index a86c743d4f..4b8d6baac2 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherUtilTest.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherUtilTest.java @@ -17,9 +17,6 @@ */ package io.entgra.device.mgt.core.apimgt.webapp.publisher; -import org.testng.Assert; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResource; import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResourceConfiguration; import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig; @@ -28,6 +25,9 @@ import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiUriTemplate; import io.entgra.device.mgt.core.apimgt.webapp.publisher.exception.APIManagerPublisherException; import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.MockServletContext; import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.TestUtils; +import org.testng.Assert; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService; @@ -36,14 +36,11 @@ import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; import javax.servlet.ServletContext; - import java.util.ArrayList; import java.util.List; import java.util.Set; -import static io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherUtil.buildApiConfig; -import static io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherUtil.getApiEndpointUrl; -import static io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherUtil.setResourceAuthTypes; +import static io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherUtil.*; /** * This is the test class for {@link APIPublisherUtil} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/BaseAPIPublisherTest.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/BaseAPIPublisherTest.java index 0b6e84f2db..2988adb58f 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/BaseAPIPublisherTest.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/BaseAPIPublisherTest.java @@ -17,12 +17,13 @@ */ package io.entgra.device.mgt.core.apimgt.webapp.publisher; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherDataHolder; +import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.MockAPIIndividualApi; +import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mockito.Mockito; import org.testng.annotations.BeforeSuite; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherDataHolder; -import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.MockAPIIndividualApi; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.internal.OSGiDataHolder; @@ -33,7 +34,6 @@ import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService; import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.service.RealmService; -import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; import java.io.File; import java.io.InputStream; diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/resources/user-test/user-mgt-registry-test.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/resources/user-test/user-mgt-registry-test.xml index 1ced8bb1f1..4d53df601c 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/resources/user-test/user-mgt-registry-test.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/test/resources/user-test/user-mgt-registry-test.xml @@ -27,7 +27,7 @@ everyone false 500 - jdbc:h2:target/databasetest/CARBON_TEST + jdbc:h2:./target/databasetest/CARBON_TEST org.h2.Driver 50 60000 diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/pom.xml deleted file mode 100644 index d8c1c34d04..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/pom.xml +++ /dev/null @@ -1,142 +0,0 @@ - - - - - - apimgt-extensions - io.entgra.device.mgt.core - 5.0.0-SNAPSHOT - ../pom.xml - - - 4.0.0 - org.wso2.carbon.apimgt.handlers - bundle - WSO2 Carbon - API Security Handler Component - WSO2 Carbon - API Management Security Handler Module - http://wso2.org - - - - - org.wso2.carbon - org.wso2.carbon.logging - - - org.apache.synapse - synapse-core - - - org.apache.ws.security.wso2 - wss4j - - - io.entgra.device.mgt.core - io.entgra.device.mgt.core.certificate.mgt.core - - - org.json.wso2 - json - - - org.slf4j - slf4j-simple - test - - - - - - - org.apache.felix - maven-scr-plugin - - - org.apache.felix - maven-bundle-plugin - 1.4.0 - true - - - ${project.artifactId} - ${project.artifactId} - ${io.entgra.device.mgt.core.version} - WSO2 Carbon - API Security Handler Component - - org.apache.axiom.*, - javax.security.cert.*, - javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, - javax.xml.*, - org.apache.axis2.*, - org.apache.commons.*, - org.apache.http.*, - org.apache.http.util, - org.apache.ws.*;version="${org.apache.ws.security.wso2.version}", - org.json, - org.wso2.carbon.utils, - org.wso2.carbon.context, - com.google.gson, - org.w3c.dom, - org.apache.synapse, - org.apache.synapse.core.axis2, - org.apache.synapse.rest, - io.entgra.device.mgt.core.certificate.mgt.core.* - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - src/test/resources/testng.xml - - - - - org.jacoco - jacoco-maven-plugin - - ${basedir}/target/coverage-reports/jacoco-unit.exec - - - - jacoco-initialize - - prepare-agent - - - - jacoco-site - test - - report - - - ${basedir}/target/coverage-reports/jacoco-unit.exec - ${basedir}/target/coverage-reports/site - - - - - - - - diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/APIMCertificateMGTException.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/APIMCertificateMGTException.java deleted file mode 100644 index b0e2d41b83..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/APIMCertificateMGTException.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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. - */ - - -import io.entgra.device.mgt.core.device.mgt.api.jaxrs..carbon.apimgt.handlers; - -/** - * Error handling class for the apimgt handler. - */ -public class APIMCertificateMGTException extends Exception{ - - private static final long serialVersionUID = -37676242646464497L; - - public APIMCertificateMGTException(String msg, Exception nestedEx) { - super(msg, nestedEx); - } -} - diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandler.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandler.java deleted file mode 100644 index 885d7f5cc5..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandler.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.handlers; - -import com.google.gson.Gson; -import org.apache.axis2.context.MessageContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.synapse.core.axis2.Axis2MessageContext; -import org.apache.synapse.rest.AbstractHandler; -import org.wso2.carbon.apimgt.handlers.beans.Certificate; -import org.wso2.carbon.apimgt.handlers.beans.ValidationResponce; -import org.wso2.carbon.apimgt.handlers.config.IOTServerConfiguration; -import org.wso2.carbon.apimgt.handlers.invoker.RESTInvoker; -import org.wso2.carbon.apimgt.handlers.invoker.RESTResponse; -import org.wso2.carbon.apimgt.handlers.utils.AuthConstants; -import org.wso2.carbon.apimgt.handlers.utils.Utils; -import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; -import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreException; -import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; -import org.wso2.carbon.context.PrivilegedCarbonContext; - -import javax.security.cert.CertificateEncodingException; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.HashMap; -import java.util.Map; -import java.util.StringTokenizer; - -/** - * Synapse gateway handler for API authentication. - */ -public class AuthenticationHandler extends AbstractHandler { - private static final Log log = LogFactory.getLog(AuthenticationHandler.class); - private RESTInvoker restInvoker; - - private static final String X_JWT_ASSERTION = "X-JWT-Assertion"; - private static final String JWTTOKEN = "JWTToken"; - private static final String AUTHORIZATION = "Authorization"; - private static final String BEARER = "Basic "; - private static final String CONTENT_TYPE = "Content-Type"; - private static final boolean USE_INTERNAL_CERT_VERIFIER = true; - - private IOTServerConfiguration iotServerConfiguration; - - /** - * Setting up configurations at the constructor - */ - public AuthenticationHandler() { - log.info("Engaging API Security Handler.........."); - restInvoker = new RESTInvoker(); - this.iotServerConfiguration = Utils.initConfig(); - } - - /** - * Handling the message and checking the security. - * - * @param messageContext Request message context. - * @return Boolean value of the result of the processing the request. - */ - @Override - public boolean handleRequest(org.apache.synapse.MessageContext messageContext) { - org.apache.axis2.context.MessageContext axisMC = ((Axis2MessageContext) messageContext).getAxis2MessageContext(); - - String ctxPath = messageContext.getTo().getAddress().trim(); - - if (log.isDebugEnabled()) { - log.debug("Authentication handler invoked by: " + ctxPath); - } - Map headers = (Map) axisMC.getProperty(MessageContext.TRANSPORT_HEADERS); - try { - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - RESTResponse response = null; - if (headers.containsKey(AuthConstants.MDM_SIGNATURE)) { - - String mdmSignature = headers.get(AuthConstants.MDM_SIGNATURE); - if (log.isDebugEnabled()) { - log.debug("Verify Cert:\n" + mdmSignature); - } - URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + "ios"); - Map certVerifyHeaders = this.setHeaders(); - - Certificate certificate = new Certificate(); - certificate.setPem(mdmSignature); - certificate.setTenantId(tenantId); - certificate.setSerial(""); - - Gson gson = new Gson(); - String certVerifyContent = gson.toJson(certificate); - response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, certVerifyContent); - - String str = response.getContent(); - if (log.isDebugEnabled()) { - log.debug("Verify response:" + response.getContent()); - log.debug("Response String : " + str); - } - if (response.getHttpStatus() == 200 && str.contains(JWTTOKEN)) { - ValidationResponce validationResponce = gson.fromJson(str, ValidationResponce.class); - headers.put(X_JWT_ASSERTION, validationResponce.getJWTToken()); - } else { - return false; - } - - } else if (headers.containsKey(AuthConstants.PROXY_MUTUAL_AUTH_HEADER)) { - String subjectDN = headers.get(AuthConstants.PROXY_MUTUAL_AUTH_HEADER); - - if (log.isDebugEnabled()) { - log.debug("Verify subject DN: " + subjectDN); - } - - if (USE_INTERNAL_CERT_VERIFIER) { - CertificateResponse certificateResponse = Utils.getCertificateManagementService() - .verifySubjectDN(subjectDN); - if (certificateResponse != null && certificateResponse.getCommonName() != null - && !certificateResponse.getCommonName().isEmpty()) { - return true; - } - } else { - String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim()); - URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType); - Map certVerifyHeaders = this.setHeaders(); - - Certificate certificate = new Certificate(); - certificate.setPem(subjectDN); - certificate.setTenantId(tenantId); - certificate.setSerial(AuthConstants.PROXY_MUTUAL_AUTH_HEADER); - - Gson gson = new Gson(); - String certVerifyContent = gson.toJson(certificate); - response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, certVerifyContent); - if (log.isDebugEnabled()) { - log.debug("Verify response:" + response.getContent()); - } - } - } else if (headers.containsKey(AuthConstants.MUTUAL_AUTH_HEADER)) { - javax.security.cert.X509Certificate[] certs = - (javax.security.cert.X509Certificate[]) axisMC.getProperty(AuthConstants.CLIENT_CERTIFICATE); - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - ByteArrayInputStream bais = new ByteArrayInputStream(certs[0].getEncoded()); - X509Certificate x509 = (X509Certificate) cf.generateCertificate(bais); - bais.close(); - if (x509 != null) { - headers.put(AuthConstants.PROXY_MUTUAL_AUTH_HEADER, CertificateGenerator.getCommonName(x509)); - return true; - } - } else if (headers.containsKey(AuthConstants.ENCODED_PEM)) { - String encodedPem = headers.get(AuthConstants.ENCODED_PEM); - if (log.isDebugEnabled()) { - log.debug("Verify Cert:\n" + encodedPem); - } - String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim()); - URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType); - Map certVerifyHeaders = this.setHeaders(); - - Certificate certificate = new Certificate(); - certificate.setPem(encodedPem); - certificate.setTenantId(tenantId); - certificate.setSerial(""); - Gson gson = new Gson(); - String certVerifyContent = gson.toJson(certificate); - response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, certVerifyContent); - if (log.isDebugEnabled()) { - log.debug("Verify response:" + response.getContent()); - } - } else { - log.warn("Unauthorized request for api: " + ctxPath); - return false; - } - if (response != null && !response.getContent().contains("invalid")) { - return true; - } - log.warn("Unauthorized request for api: " + ctxPath); - return false; - } catch (IOException e) { - log.error("Error while processing certificate.", e); - return false; - } catch (URISyntaxException e) { - log.error("Error while processing certificate.", e); - return false; - } catch (CertificateException e) { - log.error("Certificate issue occurred when generating converting PEM to x509Certificate", e); - return false; - } catch (CertificateEncodingException e) { - log.error("Error while attempting to encode certificate.", e); - return false; - } catch (KeystoreException e) { - log.error("Error while attempting to validate certificate.", e); - return false; - } - } - - @Override - public boolean handleResponse(org.apache.synapse.MessageContext messageContext) { - return true; - } - - - private String getDeviceType(String url) { - StringTokenizer parts = new StringTokenizer(url, "/"); - while (parts.hasMoreElements()) { - if (parts.nextElement().equals("device-mgt")) { - return (String) parts.nextElement(); - } - } - return null; - } - - private Map setHeaders() { - Map map = new HashMap<>(); - String accessToken = Utils.getBase64EncodedToken(iotServerConfiguration); - map.put(AUTHORIZATION, BEARER + accessToken); - map.put(CONTENT_TYPE, "application/json"); - return map; - } -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/beans/Certificate.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/beans/Certificate.java deleted file mode 100644 index b3389a82c5..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/beans/Certificate.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.handlers.beans; - -/** - * This class keeps the certificate data. - */ -public class Certificate { - - // public key of the certificate - private String pem; - // Tenant id - private int tenantId; - // Serial of the certificate. - private String serial; - - public String getPem() { - return pem; - } - - public void setPem(String pem) { - this.pem = pem; - } - - public int getTenantId() { - return tenantId; - } - - public void setTenantId(int tenantId) { - this.tenantId = tenantId; - } - - public String getSerial() { - return serial; - } - - public void setSerial(String serial) { - this.serial = serial; - } -} - diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/beans/DCR.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/beans/DCR.java deleted file mode 100644 index ae5e42b59a..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/beans/DCR.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.handlers.beans; - -/** - * This class holds the DCR endpoints data to create an application. - */ -public class DCR { - - private String callbackUrl; - private String owner; - private String clientName; - private String grantType; - private String tokenScope; - private boolean isSaasApp; - - public String getOwner() { - return owner; - } - - public void setOwner(String owner) { - this.owner = owner; - } - - public String getClientName() { - return clientName; - } - - public void setClientName(String clientName) { - this.clientName = clientName; - } - - public String getGrantType() { - return grantType; - } - - public void setGrantType(String grantType) { - this.grantType = grantType; - } - - public String getTokenScope() { - return tokenScope; - } - - public void setTokenScope(String tokenScope) { - this.tokenScope = tokenScope; - } - - public boolean getIsSaasApp() { - return isSaasApp; - } - - public void setIsSaasApp(boolean isSaasApp) { - this.isSaasApp = isSaasApp; - } - - public String getCallbackUrl() { - return callbackUrl; - } - - public void setCallbackUrl(String callbackUrl) { - this.callbackUrl = callbackUrl; - } - - public String toJSON() { - return "{\"callbackUrl\": \"" + callbackUrl + "\",\"clientName\": \"" + clientName + "\", \"tokenScope\": " + - "\"" + tokenScope + "\", \"owner\": \"" + owner + "\"," + "\"grantType\": \"" + grantType + - "\", \"saasApp\" :" + isSaasApp + " }\n"; - } -} - diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/beans/ValidationResponce.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/beans/ValidationResponce.java deleted file mode 100644 index b9b385e2f3..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/beans/ValidationResponce.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.handlers.beans; - -/** - * This class holds the data returned from the backend after the certificate was authenticated. - */ -public class ValidationResponce { - - private String JWTToken; // X-JWT-Assertion - private String deviceId; - private String deviceType; - private int tenantId; - - public String getJWTToken() { - return JWTToken; - } - - public void setJWTToken(String JWTToken) { - this.JWTToken = JWTToken; - } - - public String getDeviceId() { - return deviceId; - } - - public void setDeviceId(String deviceId) { - this.deviceId = deviceId; - } - - public String getDeviceType() { - return deviceType; - } - - public void setDeviceType(String deviceType) { - this.deviceType = deviceType; - } - - public int getTenantId() { - return tenantId; - } - - public void setTenantId(int tenantId) { - this.tenantId = tenantId; - } -} - diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/config/IOTServerConfiguration.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/config/IOTServerConfiguration.java deleted file mode 100644 index 3beecf11f0..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/config/IOTServerConfiguration.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.handlers.config; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlValue; -import java.util.List; - -/** - * This class initialize the iot-api-config.xml and hold the values, in order to be read from the relevant classes. This - * get initialized at the start of the server when apis get loaded. - */ -@XmlRootElement(name = "ServerConfiguration") -public class IOTServerConfiguration { - - private String hostname; - private String verificationEndpoint; - private String username; - private String password; - private String dynamicClientRegistrationEndpoint; - private String oauthTokenEndpoint; - private List apis; - - @XmlElement(name = "Hostname", required = true) - public String getHostname() { - return hostname; - } - - public void setHostname(String hostname) { - this.hostname = hostname; - } - - @XmlElement(name = "VerificationEndpoint", required = true) - public String getVerificationEndpoint() { - return verificationEndpoint; - } - - public void setVerificationEndpoint(String verificationEndpoint) { - this.verificationEndpoint = verificationEndpoint; - } - - @XmlElement(name = "Username", required = true) - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - @XmlElement(name = "Password", required = true) - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - @XmlElement(name = "DynamicClientRegistrationEndpoint", required = true) - public String getDynamicClientRegistrationEndpoint() { - return dynamicClientRegistrationEndpoint; - } - - public void setDynamicClientRegistrationEndpoint(String dynamicClientRegistrationEndpoint) { - this.dynamicClientRegistrationEndpoint = dynamicClientRegistrationEndpoint; - } - - @XmlElement(name = "OauthTokenEndpoint", required = true) - public String getOauthTokenEndpoint() { - return oauthTokenEndpoint; - } - - public void setOauthTokenEndpoint(String oauthTokenEndpoint) { - this.oauthTokenEndpoint = oauthTokenEndpoint; - } - - @XmlElementWrapper(name="APIS") - @XmlElement(name = "ContextPath", required = true) - public List getApis() { - return apis; - } - - public void setApis(List apis) { - this.apis = apis; - } - - @XmlRootElement(name = "ContextPath") - public static class ContextPath { - - private String contextPath; - - @XmlValue() - public String getContextPath() { - return contextPath; - } - - public void setContextPath(String contextPath) { - this.contextPath = contextPath; - } - } -} - diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/invoker/RESTInvoker.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/invoker/RESTInvoker.java deleted file mode 100644 index bd59e03dc1..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/invoker/RESTInvoker.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.handlers.invoker; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.*; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.util.EntityUtils; - -import java.io.IOException; -import java.net.URI; -import java.util.Map; -import java.util.Set; - -public class RESTInvoker { - - private static final Log log = LogFactory.getLog(RESTInvoker.class); - - private CloseableHttpClient client = null; - - public RESTInvoker() { - configureHttpClient(); - } - - private void configureHttpClient() { - int connectionTimeout = 120000; - int socketTimeout = 120000; - int maxTotalConnectionsPerRoute = 100; - int maxTotalConnections = 100; - RequestConfig defaultRequestConfig = RequestConfig.custom() - .setExpectContinueEnabled(true) - .setConnectTimeout(connectionTimeout) - .setSocketTimeout(socketTimeout) - .build(); - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); - connectionManager.setDefaultMaxPerRoute(maxTotalConnectionsPerRoute); - connectionManager.setMaxTotal(maxTotalConnections); - client = HttpClients.custom() - .setConnectionManager(connectionManager) - .setDefaultRequestConfig(defaultRequestConfig) - .build(); - if (log.isDebugEnabled()) { - log.debug("REST client initialized with " + - "maxTotalConnection = " + maxTotalConnections + - "maxConnectionsPerRoute = " + maxTotalConnectionsPerRoute + - "connectionTimeout = " + connectionTimeout); - } - - } - - public RESTResponse invokePOST(URI uri, Map requestHeaders, String payload) throws IOException { - - HttpPost httpPost = null; - CloseableHttpResponse response = null; - int httpStatus; - String output; - try { - httpPost = new HttpPost(uri); - httpPost.setEntity(new StringEntity(payload)); - if (requestHeaders != null && !requestHeaders.isEmpty()) { - Set keys = requestHeaders.keySet(); - for (String header : keys) { - httpPost.setHeader(header, requestHeaders.get(header)); - } - } - response = sendReceiveRequest(httpPost); - output = IOUtils.toString(response.getEntity().getContent()); - httpStatus = response.getStatusLine().getStatusCode(); - if (log.isDebugEnabled()) { - log.debug("Invoked POST " + uri.toString() + - " - Input payload: " + payload + " - Response message: " + output); - } - EntityUtils.consume(response.getEntity()); - } finally { - if (response != null) { - IOUtils.closeQuietly(response); - } - if (httpPost != null) { - httpPost.releaseConnection(); - } - } - return new RESTResponse(output, httpStatus); - } - - private CloseableHttpResponse sendReceiveRequest(HttpRequestBase requestBase) - throws IOException { - return client.execute(requestBase); - } -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/invoker/RESTResponse.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/invoker/RESTResponse.java deleted file mode 100644 index 205130b30e..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/invoker/RESTResponse.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.handlers.invoker; - - -/** - * RESTResponse class holds the data retrieved from the HTTP invoke response. - */ -public class RESTResponse { - private String content; - private int httpStatus; - - /** - * Constructor - * - * @param content from the REST invoke response - * @param httpStatus from the REST invoke response - */ - RESTResponse(String content, int httpStatus) { - this.content = content; - this.httpStatus = httpStatus; - } - - - /** - * Get contents of the REST invoke response - * - * @return contents of the REST invoke response - */ - public String getContent() { - return content; - } - - /** - * Get the HTTP Status code from REST invoke response - * - * @return int HTTP status code - */ - public int getHttpStatus() { - return httpStatus; - } -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/AuthConstants.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/AuthConstants.java deleted file mode 100644 index d9a9ef8a7b..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/AuthConstants.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.handlers.utils; - -/** - * This initializes the constance. - */ -public class AuthConstants { - public static final String MDM_SIGNATURE = "mdm-signature"; - public static final String PROXY_MUTUAL_AUTH_HEADER = "proxy-mutual-auth-header"; - public static final String MUTUAL_AUTH_HEADER = "mutual-auth-header"; - public static final String ONE_TIME_TOKEN_HEADER = "one-time-token"; - public static final String ENCODED_PEM = "encoded-pem"; - public static final String CALLBACK_URL = ""; - public static final String CLIENT_NAME = "IOT-API-MANAGER"; - public static final String GRANT_TYPE = "refresh_token password client_credentials"; - public static final String TOKEN_SCOPE = "default"; - public static final String CONTENT_TYPE_HEADER = "Content-Type"; - public static final String CONTENT_TYPE = "application/json"; - public static final String AUTHORIZATION_HEADER = "Authorization"; - public static final String BASIC_AUTH_PREFIX = "Basic "; - public static final String CLIENT_ID = "clientId"; - public static final String CLIENT_SECRET = "clientSecret"; - public static final String CLIENT_CERTIFICATE = "ssl.client.auth.cert.X509"; -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/Utils.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/Utils.java deleted file mode 100644 index 2e5d2e164a..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/Utils.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.handlers.utils; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.ws.security.util.Base64; -import org.json.JSONException; -import org.json.JSONObject; -import org.w3c.dom.Document; -import org.wso2.carbon.apimgt.handlers.APIMCertificateMGTException; -import org.wso2.carbon.apimgt.handlers.beans.DCR; -import org.wso2.carbon.apimgt.handlers.config.IOTServerConfiguration; -import org.wso2.carbon.apimgt.handlers.invoker.RESTInvoker; -import org.wso2.carbon.apimgt.handlers.invoker.RESTResponse; -import io.entgra.device.mgt.core.certificate.mgt.core.service.CertificateManagementService; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.utils.CarbonUtils; - -import javax.xml.XMLConstants; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Contains util methods for synapse gateway authentication handler - */ -public class Utils { - - private static final Log log = LogFactory.getLog(Utils.class); - private static final String IOT_APIS_CONFIG_FILE = "iot-api-config.xml"; - private static String clientId; - private static String clientSecret; - - /** - * This method initializes the iot-api-config.xml file. - * - * @return IoTServerConfiguration Object based on the configuration file. - */ - public static IOTServerConfiguration initConfig() { - return initConfig(CarbonUtils.getCarbonConfigDirPath() + File.separator + IOT_APIS_CONFIG_FILE); - } - - /** - * This methods initialized the iot-api-config.xml from provided path. - * - * @param path The actual file path of iot-api-config.xml - * @return The instance of the IOTServerConfiguration based on the configuration. - */ - public static IOTServerConfiguration initConfig(String path) { - try { - File file = new File(path); - Document doc = Utils.convertToDocument(file); - - JAXBContext fileContext = JAXBContext.newInstance(IOTServerConfiguration.class); - Unmarshaller unmarshaller = fileContext.createUnmarshaller(); - - IOTServerConfiguration iotServerConfiguration = (IOTServerConfiguration) unmarshaller.unmarshal( - doc); - iotServerConfiguration.setHostname(replaceProperties(iotServerConfiguration.getHostname())); - iotServerConfiguration.setVerificationEndpoint( - replaceProperties(iotServerConfiguration.getVerificationEndpoint())); - iotServerConfiguration.setDynamicClientRegistrationEndpoint( - replaceProperties(iotServerConfiguration.getDynamicClientRegistrationEndpoint())); - iotServerConfiguration.setOauthTokenEndpoint( - replaceProperties(iotServerConfiguration.getOauthTokenEndpoint())); - return iotServerConfiguration; - } catch (JAXBException | APIMCertificateMGTException e) { - log.error("Error occurred while initializing Data Source config", e); - return null; - } - } - - /** - * This method gets the values from system variables and sets to xml. - */ - private static String replaceProperties(String text) { - String regex = "\\$\\{(.*?)\\}"; - Pattern pattern = Pattern.compile(regex); - Matcher matchPattern = pattern.matcher(text); - while (matchPattern.find()) { - String sysPropertyName = matchPattern.group(1); - String sysPropertyValue = System.getProperty(sysPropertyName); - if (sysPropertyValue != null && !sysPropertyName.isEmpty()) { - text = text.replaceAll("\\$\\{(" + sysPropertyName + ")\\}", sysPropertyValue); - } - } - return text; - } - - /** - * This class build the iot-api-config.xml file. - * - * @param file The file object of iot-api-config.xml. - * @return Document instance of the file - * @throws APIMCertificateMGTException - */ - private static Document convertToDocument(File file) throws APIMCertificateMGTException { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - try { - factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - DocumentBuilder docBuilder = factory.newDocumentBuilder(); - return docBuilder.parse(file); - } catch (Exception e) { - throw new APIMCertificateMGTException("Error occurred while parsing file, while converting " + - "to a org.w3c.dom.Document", e); - } - } - - /** - * This method is used to get the base64 encoded token. - * - * @param iotServerConfiguration Instance of the IoTsererConfiguration. - * @return Access token will be returned. - */ - public static String getBase64EncodedToken(IOTServerConfiguration iotServerConfiguration) { - return Base64.encode((iotServerConfiguration.getUsername() + ":" + iotServerConfiguration.getPassword()). - getBytes()); - } - - /** - * This method register an application to get the client key and secret. - * - * @param iotServerConfiguration Instance of the IoTServerConfiguration. - * @throws APIMCertificateMGTException - */ - private static void getClientSecretes(IOTServerConfiguration iotServerConfiguration, RESTInvoker restInvoker) - throws APIMCertificateMGTException { - try { - String username = iotServerConfiguration.getUsername(); - String password = iotServerConfiguration.getPassword(); - DCR dcr = new DCR(); - dcr.setOwner(iotServerConfiguration.getUsername()); - dcr.setClientName(AuthConstants.CLIENT_NAME); - dcr.setGrantType(AuthConstants.GRANT_TYPE); - dcr.setTokenScope(AuthConstants.TOKEN_SCOPE); - dcr.setCallbackUrl(AuthConstants.CALLBACK_URL); - dcr.setIsSaasApp(true); - String dcrContent = dcr.toJSON(); - Map dcrHeaders = new HashMap<>(); - String basicAuth = Base64.encode((username + ":" + password).getBytes()); - dcrHeaders.put(AuthConstants.CONTENT_TYPE_HEADER, AuthConstants.CONTENT_TYPE); - dcrHeaders.put(AuthConstants.AUTHORIZATION_HEADER, AuthConstants.BASIC_AUTH_PREFIX + basicAuth); - URI dcrUrl = new URI(iotServerConfiguration.getDynamicClientRegistrationEndpoint()); - RESTResponse response = restInvoker.invokePOST(dcrUrl, dcrHeaders, dcrContent); - if (log.isDebugEnabled()) { - log.debug("DCR response :" + response.getContent()); - } - JSONObject jsonResponse = new JSONObject(response.getContent()); - clientId = jsonResponse.getString(AuthConstants.CLIENT_ID); - clientSecret = jsonResponse.getString(AuthConstants.CLIENT_SECRET); - } catch (JSONException e) { - throw new APIMCertificateMGTException("Error occurred while converting the json to object", e); - } catch (IOException | URISyntaxException e) { - throw new APIMCertificateMGTException("Error occurred while trying to call DCR endpoint", e); - } - - } - - public static CertificateManagementService getCertificateManagementService() { - - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - CertificateManagementService certificateManagementService = (CertificateManagementService) - ctx.getOSGiService(CertificateManagementService.class, null); - - if (certificateManagementService == null) { - String msg = "CertificateManagementAdminServiceImpl Management service not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - - return certificateManagementService; - } - -} - diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/resources/iot-api-config.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/resources/iot-api-config.xml deleted file mode 100644 index 7b1462746b..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/resources/iot-api-config.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - https://${iot.core.host}:${iot.core.https.port}/ - - - https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/ - - - admin - admin - - - https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.12/register - - - https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token - - - /services - - \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandlerTest.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandlerTest.java deleted file mode 100644 index 5a9370a56e..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandlerTest.java +++ /dev/null @@ -1,296 +0,0 @@ -/* -* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.handlers; - -import com.google.gson.Gson; -import junit.framework.Assert; -import org.apache.axiom.om.OMAbstractFactory; -import org.apache.axiom.om.OMDocument; -import org.apache.axiom.soap.SOAPEnvelope; -import org.apache.axis2.addressing.EndpointReference; -import org.apache.axis2.context.ConfigurationContext; -import org.apache.axis2.engine.AxisConfiguration; -import org.apache.http.ProtocolVersion; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.entity.BasicHttpEntity; -import org.apache.http.message.BasicStatusLine; -import org.apache.synapse.MessageContext; -import org.apache.synapse.config.SynapseConfigUtils; -import org.apache.synapse.config.SynapseConfiguration; -import org.apache.synapse.core.SynapseEnvironment; -import org.apache.synapse.core.axis2.Axis2MessageContext; -import org.apache.synapse.core.axis2.Axis2SynapseEnvironment; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.apimgt.handlers.beans.ValidationResponce; -import org.wso2.carbon.apimgt.handlers.invoker.RESTInvoker; -import org.wso2.carbon.apimgt.handlers.mock.MockClient; -import org.wso2.carbon.apimgt.handlers.mock.MockHttpResponse; -import org.wso2.carbon.apimgt.handlers.utils.AuthConstants; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Field; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import javax.security.cert.X509Certificate; - -/** - * This testcase will focus on covering the methods of {@link AuthenticationHandler} - */ -public class AuthenticationHandlerTest extends BaseAPIHandlerTest { - - private AuthenticationHandler handler; - private SynapseConfiguration synapseConfiguration; - private MockClient mockClient; - - @BeforeClass - public void initTest() { - TestUtils.setSystemProperties(); - this.handler = new AuthenticationHandler(); - this.synapseConfiguration = new SynapseConfiguration(); - } - - @Test(description = "Handle request with empty transport headers") - public void testHandleRequestWithEmptyTransportHeader() throws Exception { - boolean response = this.handler.handleRequest(createSynapseMessageContext("", this.synapseConfiguration, - new HashMap<>(), "https://test.com/testservice")); - Assert.assertFalse(response); - } - - @Test(description = "Handle request with without device type", - dependsOnMethods = "testHandleRequestWithEmptyTransportHeader") - public void testHandleRequestWithoutDeviceType() throws Exception { - HashMap transportHeaders = new HashMap<>(); - transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert"); - boolean response = this.handler.handleRequest(createSynapseMessageContext("", this.synapseConfiguration, - transportHeaders, "https://test.com/testservice")); - Assert.assertFalse(response); - } - - @Test(description = "Handle request with device type URI with MDM ceritificate", - dependsOnMethods = "testHandleRequestWithoutDeviceType") - public void testHandleSuccessfulRequestMDMCertificate() throws Exception { - HashMap transportHeaders = new HashMap<>(); - transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert"); - setMockClient(); - this.mockClient.setResponse(getValidationResponse()); - boolean response = this.handler.handleRequest(createSynapseMessageContext("", this.synapseConfiguration, - transportHeaders, "https://test.com/testservice/device-mgt/testdevice")); - Assert.assertTrue(response); - this.mockClient.reset(); - } - - @Test(description = "Handle request with device type URI with Mutual Auth Header", - dependsOnMethods = "testHandleSuccessfulRequestMDMCertificate") - public void testHandleSuccessRequestMutualAuthHeader() throws Exception { - HashMap transportHeaders = new HashMap<>(); - transportHeaders.put(AuthConstants.MUTUAL_AUTH_HEADER, "Test Header"); - setMockClient(); - this.mockClient.setResponse(getValidationResponse()); - MessageContext messageContext = createSynapseMessageContext("", this.synapseConfiguration, - transportHeaders, "https://test.com/testservice/device-mgt/testdevice"); - org.apache.axis2.context.MessageContext axisMC = ((Axis2MessageContext) messageContext).getAxis2MessageContext(); - String certStr = getContent(TestUtils.getAbsolutePathOfConfig("ra_cert.pem")); - X509Certificate cert = X509Certificate.getInstance(new ByteArrayInputStream(certStr. - getBytes(StandardCharsets.UTF_8.name()))); - axisMC.setProperty(AuthConstants.CLIENT_CERTIFICATE, new X509Certificate[]{cert}); - boolean response = this.handler.handleRequest(messageContext); - Assert.assertTrue(response); - this.mockClient.reset(); - } - - @Test(description = "Handle request with device type URI with Encoded Pem", - dependsOnMethods = "testHandleSuccessRequestMutualAuthHeader") - public void testHandleSuccessRequestEncodedPem() throws Exception { - HashMap transportHeaders = new HashMap<>(); - transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem"); - setMockClient(); - this.mockClient.setResponse(getValidationResponse()); - MessageContext messageContext = createSynapseMessageContext("", this.synapseConfiguration, - transportHeaders, "https://test.com/testservice/device-mgt/testdevice"); - boolean response = this.handler.handleRequest(messageContext); - Assert.assertTrue(response); - this.mockClient.reset(); - } - - @Test(description = "Handle request with device type URI with Encoded Pem with invalid response", - dependsOnMethods = "testHandleSuccessRequestEncodedPem") - public void testHandleSuccessRequestEncodedPemInvalidResponse() throws Exception { - HashMap transportHeaders = new HashMap<>(); - transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem"); - setMockClient(); - this.mockClient.setResponse(getInvalidResponse()); - MessageContext messageContext = createSynapseMessageContext("", this.synapseConfiguration, - transportHeaders, "https://test.com/testservice/device-mgt/testdevice"); - boolean response = this.handler.handleRequest(messageContext); - Assert.assertFalse(response); - this.mockClient.reset(); - } - - @Test(description = "Handle request with cert management exception ", - dependsOnMethods = "testHandleSuccessRequestEncodedPem") - public void testHandleRequestWithCertMgmtException() throws Exception { - HashMap transportHeaders = new HashMap<>(); - transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem"); - setMockClient(); - this.mockClient.setResponse(null); - MessageContext messageContext = createSynapseMessageContext("", this.synapseConfiguration, - transportHeaders, "https://test.com/testservice/device-mgt/testdevice"); - boolean response = this.handler.handleRequest(messageContext); - Assert.assertFalse(response); - this.mockClient.reset(); - } - - @Test(description = "Handle request with IO exception", - dependsOnMethods = "testHandleRequestWithCertMgmtException") - public void testHandleRequestWithIOException() throws Exception { - HashMap transportHeaders = new HashMap<>(); - transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem"); - setMockClient(); - this.mockClient.setResponse(null); - MessageContext messageContext = createSynapseMessageContext("", this.synapseConfiguration, - transportHeaders, "https://test.com/testservice/device-mgt/testdevice"); - boolean response = this.handler.handleRequest(messageContext); - Assert.assertFalse(response); - this.mockClient.reset(); - } - - @Test(description = "Handle request with URI exception", - dependsOnMethods = "testHandleRequestWithIOException") - public void testHandleRequestWithURIException() throws Exception { - TestUtils.resetSystemProperties(); - HashMap transportHeaders = new HashMap<>(); - transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert"); - AuthenticationHandler handler = new AuthenticationHandler(); - boolean response = handler.handleRequest(createSynapseMessageContext("", this.synapseConfiguration, - transportHeaders, "https://test.com/testservice/device-mgt/testdevice")); - Assert.assertFalse(response); - TestUtils.setSystemProperties(); - } - - @Test(description = "Handle response") - public void testHandleResponse() throws Exception { - boolean response = this.handler.handleResponse(null); - Assert.assertTrue(response); - } - - - private static MessageContext createSynapseMessageContext( - String payload, SynapseConfiguration config, HashMap transportHeaders, - String address) throws Exception { - org.apache.axis2.context.MessageContext mc = - new org.apache.axis2.context.MessageContext(); - AxisConfiguration axisConfig = config.getAxisConfiguration(); - if (axisConfig == null) { - axisConfig = new AxisConfiguration(); - config.setAxisConfiguration(axisConfig); - } - ConfigurationContext cfgCtx = new ConfigurationContext(axisConfig); - SynapseEnvironment env = new Axis2SynapseEnvironment(cfgCtx, config); - MessageContext synMc = new Axis2MessageContext(mc, config, env); - SOAPEnvelope envelope = - OMAbstractFactory.getSOAP11Factory().getDefaultEnvelope(); - OMDocument omDoc = - OMAbstractFactory.getSOAP11Factory().createOMDocument(); - omDoc.addChild(envelope); - envelope.getBody().addChild(SynapseConfigUtils.stringToOM(payload)); - synMc.setEnvelope(envelope); - synMc.setTo(new EndpointReference(address)); - org.apache.axis2.context.MessageContext axis2MessageContext = - ((Axis2MessageContext) synMc).getAxis2MessageContext(); - axis2MessageContext.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, transportHeaders); - return synMc; - } - - private void setMockClient() throws NoSuchFieldException, IllegalAccessException { - Field restInvokerField = this.handler.getClass().getDeclaredField("restInvoker"); - restInvokerField.setAccessible(true); - RESTInvoker restInvoker = (RESTInvoker) restInvokerField.get(this.handler); - Field clientField = restInvoker.getClass().getDeclaredField("client"); - clientField.setAccessible(true); - this.mockClient = new MockClient(); - clientField.set(restInvoker, this.mockClient); - } - - private CloseableHttpResponse getDCRResponse() throws IOException { - CloseableHttpResponse mockDCRResponse = new MockHttpResponse(); - String dcrResponseFile = TestUtils.getAbsolutePathOfConfig("dcr-response.json"); - BasicHttpEntity responseEntity = new BasicHttpEntity(); - responseEntity.setContent(new ByteArrayInputStream(getContent(dcrResponseFile). - getBytes(StandardCharsets.UTF_8.name()))); - responseEntity.setContentType(TestUtils.CONTENT_TYPE); - mockDCRResponse.setEntity(responseEntity); - mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 200, "OK")); - return mockDCRResponse; - } - - private CloseableHttpResponse getAccessTokenReponse() throws IOException { - CloseableHttpResponse mockDCRResponse = new MockHttpResponse(); - String dcrResponseFile = TestUtils.getAbsolutePathOfConfig("accesstoken-response.json"); - BasicHttpEntity responseEntity = new BasicHttpEntity(); - responseEntity.setContent(new ByteArrayInputStream(getContent(dcrResponseFile). - getBytes(StandardCharsets.UTF_8.name()))); - responseEntity.setContentType(TestUtils.CONTENT_TYPE); - mockDCRResponse.setEntity(responseEntity); - mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 200, "OK")); - return mockDCRResponse; - } - - private CloseableHttpResponse getValidationResponse() throws UnsupportedEncodingException { - ValidationResponce response = new ValidationResponce(); - response.setDeviceId("1234"); - response.setDeviceType("testdevice"); - response.setJWTToken("1234567788888888"); - response.setTenantId(-1234); - Gson gson = new Gson(); - String jsonReponse = gson.toJson(response); - CloseableHttpResponse mockDCRResponse = new MockHttpResponse(); - BasicHttpEntity responseEntity = new BasicHttpEntity(); - responseEntity.setContent(new ByteArrayInputStream(jsonReponse.getBytes(StandardCharsets.UTF_8.name()))); - responseEntity.setContentType(TestUtils.CONTENT_TYPE); - mockDCRResponse.setEntity(responseEntity); - mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 200, "OK")); - return mockDCRResponse; - } - - private CloseableHttpResponse getInvalidResponse() throws UnsupportedEncodingException { - CloseableHttpResponse mockDCRResponse = new MockHttpResponse(); - BasicHttpEntity responseEntity = new BasicHttpEntity(); - responseEntity.setContent(new ByteArrayInputStream("invalid response".getBytes(StandardCharsets.UTF_8.name()))); - responseEntity.setContentType(TestUtils.CONTENT_TYPE); - mockDCRResponse.setEntity(responseEntity); - mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 400, "Bad Request")); - return mockDCRResponse; - } - - private String getContent(String filePath) throws IOException { - FileReader fileReader = new FileReader(filePath); - BufferedReader bufferedReader = new BufferedReader(fileReader); - String content = ""; - String line; - while ((line = bufferedReader.readLine()) != null) { - content += line + "\n"; - } - bufferedReader.close(); - return content; - } -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/BaseAPIHandlerTest.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/BaseAPIHandlerTest.java deleted file mode 100644 index 57a293e2eb..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/BaseAPIHandlerTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* -* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.handlers; - -import org.testng.annotations.BeforeSuite; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.context.PrivilegedCarbonContext; - -import java.io.File; - -/** - * This is the base test case for API Handler tests. - */ -public class BaseAPIHandlerTest { - - @BeforeSuite - public void init() { - setUpCarbonHome(); - } - - private void setUpCarbonHome() { - if (System.getProperty("carbon.home") == null) { - File file = new File("src/test/resources/carbon-home"); - if (file.exists()) { - System.setProperty("carbon.home", file.getAbsolutePath()); - } - file = new File("carbon-home"); - if (file.exists()) { - System.setProperty("carbon.home", file.getAbsolutePath()); - } - file = new File("../../resources/carbon-home"); - if (file.exists()) { - System.setProperty("carbon.home", file.getAbsolutePath()); - } - file = new File("../../../resources/carbon-home"); - if (file.exists()) { - System.setProperty("carbon.home", file.getAbsolutePath()); - } - } - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants - .SUPER_TENANT_DOMAIN_NAME); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID); - } - -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/IOTServerConfigurationTest.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/IOTServerConfigurationTest.java deleted file mode 100644 index 1b7a88dd3b..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/IOTServerConfigurationTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/* -* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.handlers; - -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.apimgt.handlers.config.IOTServerConfiguration; -import org.wso2.carbon.apimgt.handlers.utils.Utils; - -import java.io.File; - -/** - * This class validates the behaviour of {@link IOTServerConfiguration} - */ -public class IOTServerConfigurationTest extends BaseAPIHandlerTest { - private static final String CONFIG_DIR = "carbon-home" + File.separator + "repository" + File.separator + - "conf" + File.separator; - - @BeforeClass - public void initTest(){ - TestUtils.resetSystemProperties(); - } - - @Test(description = "Validating the IoT Server configuration initialization without system properties") - public void initConfigWithoutSystemProps() { - IOTServerConfiguration serverConfiguration = Utils.initConfig(); - Assert.assertTrue(serverConfiguration != null); - Assert.assertEquals(serverConfiguration.getHostname(), "https://${iot.core.host}:${iot.core.https.port}/"); - Assert.assertEquals(serverConfiguration.getVerificationEndpoint(), - "https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/"); - Assert.assertEquals(serverConfiguration.getUsername(), "testuser"); - Assert.assertEquals(serverConfiguration.getPassword(), "testuserpwd"); - Assert.assertEquals(serverConfiguration.getDynamicClientRegistrationEndpoint(), - "https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.12/register"); - Assert.assertEquals(serverConfiguration.getOauthTokenEndpoint(), - "https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token"); - Assert.assertEquals(serverConfiguration.getApis().size(), 1); - Assert.assertEquals(serverConfiguration.getApis().get(0).getContextPath(), "/services"); - } - - @Test(description = "Initializing IoT server config with invalid configuration", - dependsOnMethods = "initConfigWithoutSystemProps") - public void initConfigWithInvalidConfig() { - IOTServerConfiguration serverConfig = Utils.initConfig(TestUtils.getAbsolutePathOfConfig(CONFIG_DIR - + "iot-api-config-invalid.xml")); - Assert.assertEquals(serverConfig, null); - } - - @Test(description = "Initializing IoT server config with invalid xml", - dependsOnMethods = "initConfigWithInvalidConfig") - public void initConfigWithInvalidXMLConfig() { - IOTServerConfiguration serverConfig = Utils.initConfig(TestUtils.getAbsolutePathOfConfig(CONFIG_DIR + - "iot-api-config-invalid-xml.xml")); - Assert.assertEquals(serverConfig, null); - } - - @Test(description = "Initializing IoT server config with system configs", - dependsOnMethods = "initConfigWithInvalidXMLConfig") - public void initConfigWithSystemProps() { - TestUtils.setSystemProperties(); - IOTServerConfiguration serverConfiguration = Utils.initConfig(); - Assert.assertTrue(serverConfiguration != null); - Assert.assertEquals(serverConfiguration.getHostname(), "https://" + TestUtils.IOT_CORE_HOST + ":" - + TestUtils.IOT_CORE_HTTPS_PORT - + "/"); - Assert.assertEquals(serverConfiguration.getVerificationEndpoint(), - "https://" + TestUtils.IOT_CORE_HOST + ":" + TestUtils.IOT_CORE_HTTPS_PORT + - "/api/certificate-mgt/v1.0/admin/certificates/" + - "verify/"); - Assert.assertEquals(serverConfiguration.getUsername(), "testuser"); - Assert.assertEquals(serverConfiguration.getPassword(), "testuserpwd"); - Assert.assertEquals(serverConfiguration.getDynamicClientRegistrationEndpoint(), - "https://" + TestUtils.IOT_KEYMANAGER_HOST + ":" + TestUtils.IOT_KEYMANAGER_PORT - + "/client-registration/v0.12/register"); - Assert.assertEquals(serverConfiguration.getOauthTokenEndpoint(), - "https://" + TestUtils.IOT_KEYMANAGER_HOST + ":" + TestUtils.IOT_KEYMANAGER_PORT - + "/oauth2/token"); - Assert.assertEquals(serverConfiguration.getApis().size(), 1); - Assert.assertEquals(serverConfiguration.getApis().get(0).getContextPath(), "/services"); - } -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/TestUtils.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/TestUtils.java deleted file mode 100644 index 5b22e1c5d9..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/TestUtils.java +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.handlers; - -import org.testng.Assert; - -import java.io.File; -import java.net.URL; - -/** - * Utils class which provides utility methods for other testcases. - */ -public class TestUtils { - static final String IOT_CORE_HOST = "iot.core.wso2.com"; - static final String IOT_CORE_HTTPS_PORT = "9443"; - static final String IOT_KEYMANAGER_HOST = "iot.keymanager.wso2.com"; - static final String IOT_KEYMANAGER_PORT = "9443"; - static final String CONTENT_TYPE = "application/json"; - - private static final String IOT_HOST_PROPERTY = "iot.core.host"; - private static final String IOT_PORT_PROPERTY = "iot.core.https.port"; - private static final String IOT_KEY_MANAGER_HOST_PROPERTY = "iot.keymanager.host"; - private static final String IOT_KEY_MANAGER_PORT_PROPERTY = "iot.keymanager.https.port"; - - static String getAbsolutePathOfConfig(String configFilePath) { - ClassLoader classLoader = TestUtils.class.getClassLoader(); - URL invalidConfig = classLoader.getResource(configFilePath); - Assert.assertTrue(invalidConfig != null); - File file = new File(invalidConfig.getFile()); - return file.getAbsolutePath(); - } - - static void setSystemProperties() { - System.setProperty(IOT_HOST_PROPERTY, IOT_CORE_HOST); - System.setProperty(IOT_PORT_PROPERTY, IOT_CORE_HTTPS_PORT); - System.setProperty(IOT_KEY_MANAGER_HOST_PROPERTY, IOT_KEYMANAGER_HOST); - System.setProperty(IOT_KEY_MANAGER_PORT_PROPERTY, IOT_KEYMANAGER_PORT); - } - - static void resetSystemProperties() { - System.clearProperty(IOT_HOST_PROPERTY); - System.clearProperty(IOT_PORT_PROPERTY); - System.clearProperty(IOT_KEY_MANAGER_HOST_PROPERTY); - System.clearProperty(IOT_KEY_MANAGER_PORT_PROPERTY); - } -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/mock/MockClient.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/mock/MockClient.java deleted file mode 100644 index 0c8ab4f6bd..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/mock/MockClient.java +++ /dev/null @@ -1,76 +0,0 @@ -/* -* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.handlers.mock; - -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.params.HttpParams; -import org.apache.http.protocol.HttpContext; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * Mock implementation for CloseableHttpClient to be used in test cases. - */ -public class MockClient extends CloseableHttpClient { - private List responses = new ArrayList<>(); - private int responseCount = 0; - - @Override - protected CloseableHttpResponse doExecute(HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext) - throws IOException { - if (this.responseCount < this.responses.size()) { - this.responseCount++; - CloseableHttpResponse response = this.responses.get(this.responseCount - 1); - if (response == null) { - throw new IOException("test exception"); - } - return response; - } else { - return new MockHttpResponse(); - } - } - - @Override - public void close() throws IOException { - } - - @Override - public HttpParams getParams() { - return null; - } - - @Override - public ClientConnectionManager getConnectionManager() { - return null; - } - - public void setResponse(CloseableHttpResponse reponse) { - this.responses.add(reponse); - } - - public void reset() { - this.responses.clear(); - this.responseCount = 0; - } -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/mock/MockHttpResponse.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/mock/MockHttpResponse.java deleted file mode 100644 index adfd7652c5..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/mock/MockHttpResponse.java +++ /dev/null @@ -1,178 +0,0 @@ -/* -* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.handlers.mock; - -import org.apache.http.Header; -import org.apache.http.HeaderIterator; -import org.apache.http.HttpEntity; -import org.apache.http.ProtocolVersion; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.params.HttpParams; - -import java.io.IOException; -import java.util.Locale; - -/** - * Mock http response to be used in the test cases. - * - */ -public class MockHttpResponse implements CloseableHttpResponse { - private HttpEntity httpEntity; - private StatusLine statusLine; - - @Override - public void close() throws IOException { - - } - - @Override - public StatusLine getStatusLine() { - return this.statusLine; - } - - @Override - public void setStatusLine(StatusLine statusLine) { - this.statusLine = statusLine; - } - - @Override - public void setStatusLine(ProtocolVersion protocolVersion, int i) { - - } - - @Override - public void setStatusLine(ProtocolVersion protocolVersion, int i, String s) { - - } - - @Override - public void setStatusCode(int i) throws IllegalStateException { - - } - - @Override - public void setReasonPhrase(String s) throws IllegalStateException { - - } - - @Override - public HttpEntity getEntity() { - return this.httpEntity; - } - - @Override - public void setEntity(HttpEntity httpEntity) { - this.httpEntity = httpEntity; - } - - @Override - public Locale getLocale() { - return null; - } - - @Override - public void setLocale(Locale locale) { - - } - - @Override - public ProtocolVersion getProtocolVersion() { - return null; - } - - @Override - public boolean containsHeader(String s) { - return false; - } - - @Override - public Header[] getHeaders(String s) { - return new Header[0]; - } - - @Override - public Header getFirstHeader(String s) { - return null; - } - - @Override - public Header getLastHeader(String s) { - return null; - } - - @Override - public Header[] getAllHeaders() { - return new Header[0]; - } - - @Override - public void addHeader(Header header) { - - } - - @Override - public void addHeader(String s, String s1) { - - } - - @Override - public void setHeader(Header header) { - - } - - @Override - public void setHeader(String s, String s1) { - - } - - @Override - public void setHeaders(Header[] headers) { - - } - - @Override - public void removeHeader(Header header) { - - } - - @Override - public void removeHeaders(String s) { - - } - - @Override - public HeaderIterator headerIterator() { - return null; - } - - @Override - public HeaderIterator headerIterator(String s) { - return null; - } - - @Override - public HttpParams getParams() { - return null; - } - - @Override - public void setParams(HttpParams httpParams) { - - } -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/accesstoken-response.json b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/accesstoken-response.json deleted file mode 100644 index 11be1e29eb..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/accesstoken-response.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "scope": "API_SUBSCRIBER_SCOPE", - "token_type": "Bearer", - "expires_in": 3600, - "refresh_token": "33c3be152ebf0030b3fb76f2c1f80bf8", - "access_token": "292ff0fd256814536baca0926f483c8d" -} \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/carbon.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/carbon.xml deleted file mode 100644 index a5518cb720..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/carbon.xml +++ /dev/null @@ -1,658 +0,0 @@ - - - - - - - - - ${product.name} - - - ${product.key} - - - ${product.version} - - - - - - - - - local:/${carbon.context}/services/ - - - - - - - ${default.server.role} - - - - - - - org.wso2.carbon - - - / - - - - - - - - - 15 - - - - - - - - - 0 - - - - - 9999 - - 11111 - - - - - - 10389 - - 8000 - - - - - - 10500 - - - - - - - org.wso2.carbon.tomcat.jndi.CarbonJavaURLContextFactory - - - - - - - - - java - - - - - - - - - - false - - - false - - - 600 - - - - false - - - - - - - - 30 - - - - - - - - - 15 - - - - - - ${carbon.home}/repository/deployment/server/ - - - 15 - - - ${carbon.home}/repository/conf/axis2/axis2.xml - - - 30000 - - - ${carbon.home}/repository/deployment/client/ - - ${carbon.home}/repository/conf/axis2/axis2_client.xml - - true - - - - - - - - - - admin - Default Administrator Role - - - user - Default User Role - - - - - - - - - - - - ${carbon.home}/repository/resources/security/wso2carbon.jks - - JKS - - wso2carbon - - wso2carbon - - wso2carbon - - - - - - ${carbon.home}/repository/resources/security/client-truststore.jks - - JKS - - wso2carbon - - - - - - - - - - - - - - - - - - - UserManager - - - false - - - - - - - ${carbon.home}/tmp/work - - - - - - true - - - 10 - - - 30 - - - - - - 100 - - - - keystore - certificate - * - - org.wso2.carbon.ui.transports.fileupload.AnyFileUploadExecutor - - - - - jarZip - - org.wso2.carbon.ui.transports.fileupload.JarZipUploadExecutor - - - - dbs - - org.wso2.carbon.ui.transports.fileupload.DBSFileUploadExecutor - - - - tools - - org.wso2.carbon.ui.transports.fileupload.ToolsFileUploadExecutor - - - - toolsAny - - org.wso2.carbon.ui.transports.fileupload.ToolsAnyFileUploadExecutor - - - - - - - info - org.wso2.carbon.core.transports.util.InfoProcessor - - - wsdl - org.wso2.carbon.core.transports.util.Wsdl11Processor - - - wsdl2 - org.wso2.carbon.core.transports.util.Wsdl20Processor - - - xsd - org.wso2.carbon.core.transports.util.XsdProcessor - - - - - - false - false - true - svn - http://svnrepo.example.com/repos/ - username - password - true - - - - - - - - - - - - - - - ${require.carbon.servlet} - - - - - true - - - - - - - default repository - ${p2.repo.url} - - - - - - - - true - - - - - - true - - diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/iot-api-config-invalid-xml.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/iot-api-config-invalid-xml.xml deleted file mode 100644 index 2f174b3f03..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/iot-api-config-invalid-xml.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - https://${iot.core.host}:${iot.core.https.port}/ - - - https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/ - - - testuser - testuserpwd - - - https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.12/register - - - https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token - - - /services - - - - - - - https://${iot.core.host}:${iot.core.https.port}/ - - - https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/ - - - testuser - testuserpwd - - - https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.12/register - - - https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token - - - /services - - \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/iot-api-config.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/iot-api-config.xml deleted file mode 100644 index 4224c27a07..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/iot-api-config.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - https://${iot.core.host}:${iot.core.https.port}/ - - - https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/ - - - testuser - testuserpwd - - - https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.12/register - - - https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token - - - /services - - \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/registry.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/registry.xml deleted file mode 100644 index 331c448c87..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/registry.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - wso2registry - false - true - / - - - jdbc:h2:./target/databasetest/CARBON_TEST - - org.h2.Driver - 80 - 60000 - 5 - - - false - - - - true - true - true - true - - diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/dcr-response.json b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/dcr-response.json deleted file mode 100644 index 1672f812d7..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/dcr-response.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "callBackURL": "www.google.lk", - "clientName": null, - "clientId": "HfEl1jJPdg5tbtrxhAwybN05QGoa", - "clientSecret": "l6c0aoLcWR3fwezHhc7XoGOht5Aa" -} \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/ra_cert.pem b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/ra_cert.pem deleted file mode 100644 index 516b08ccee..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/ra_cert.pem +++ /dev/null @@ -1,33 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIFqDCCA5CgAwIBAgIBAjANBgkqhkiG9w0BAQUFADCBizELMAkGA1UEBhMCVVMx -DTALBgNVBAgTBFRlc3QxDTALBgNVBAcTBFRlc3QxETAPBgNVBAoTCFRlc3QgT3Jn -MRYwFAYDVQQLEw1UZXN0IG9yZyB1bml0MRUwEwYDVQQDEwxXU08yIFJvb3QgQ0Ex -HDAaBgkqhkiG9w0BCQEWDXJvb3RAd3NvMi5jb20wHhcNMTUwMTI3MTI1MzAxWhcN -MTcxMDIzMTI1MzAxWjCBgzELMAkGA1UEBhMCVVMxGTAXBgNVBAgTEFRlc3QgUkEg -UHJvdmluY2UxFTATBgNVBAcTDFRlc3QgUkEgQ2l0eTEUMBIGA1UEChMLVGVzdCBS -QSBPcmcxGTAXBgNVBAsTEFRlc3QgUkEgb3JnIHVuaXQxETAPBgNVBAMTCFdTTzIg -UkEgMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAtUMgUlYYU3/TPfEe -zNAvBaiOi/jUjfZ9IbxvMl7obDT17/5vU68TCGkZRjyfYUEiGNBisUEFWjSk/sGL -/ofYKUAxw33cd456FLMjaJX/4Zk4y8eYB1m1GGlHejoDyjPhq8S6GDmy+PXbJr8n -lSTROR2mQHkGwYrCreWeU4AYWzdctIFk7U2DKeIvZYSidIIjfSpDXURxrt9LPvig -fMzr5l/WkZfjvk5S+W7rgMtpllxlEPgyDc07pNAdNSq5FB990oaUsVX8o6l6wdCw -grYz83edPOKwZa04fsVztz2oF3ZYSGGjD3lwh0KS/jUL+awRyhMx5p/O1hySg6PP -pJjeqRuobNTuwSAXxp3nsNSY0DkGW04pSxWoDQqhnpaqBbAf71l6ya2e3so1SHm/ -jouWSYTHncq5bmGE4AN7ZGVGZvfx84+UR8fNxJxxLo+DFFE0oJNzpPGNxILpHxgT -V7IOII6mhfkrQk+AFQiW2Y5FXLVYv8r+SPXW8pYsjaWl971XZeM/HC3L9IZkCrrr -a0ID5oT6vt+xTmdo4yiBqIP5TBYm+1a9YzMAy7XGtPih9k6cufMLcfzvUZdOXw9x -3T05nM5ZtcDq0gHvUzQ7sfHTguWVnuHVEdb2ox4x2L5NzEA475fbSdXpMok9z/z7 -Xa71vIZi28InDAFBQehUlJnFtf0CAwEAAaMdMBswDAYDVR0TBAUwAwEB/zALBgNV -HQ8EBAMCBaAwDQYJKoZIhvcNAQEFBQADggIBAAO0TwnQBMJvL8wbfsnTqAGCCHM4 -x1cpW+KgTmflPEliYGOn/dJYDz/dUowCgoj5mrSxjQ3G1/qL+9Y7E33h0tyw37vH -YDL1p2Tn+fwmXRHrk+CHoPHNcImEfSIDWbbG7ehBR6erVfbQSZjmj4fwPkItp8rP -nyUtXHOLpfFYoAxYkNP9+C8vpC9W/H1pj3rzmQFA1z+EZAKVV7vDAxbe6sun84nf -YAaMSIzHx1B+XLHokgChmnZr3wV7EypBEmmKp4ITvJqK7WsIG9t1M6hI7OTPCURR -mdy+DJtIoIUbZxHyIyC9nPcVJFkdBusnfXq4uMb0KMaWYCU8ESqZPySukF2qZ5KA -acB+0ZhY+EGQ6QF/hB6iiUj96BlQ7XAPXFU6xUt6nRjDiJmb3vW1IEv0hpbs7PRl -UMlbOwQk37rXpFqQc6ZW7lsxI2RmfkD4DOkQIGH3q5foVr+PEp0uSPWrFX62eBet -1S4c/opVv6BcuUgilYABHTYxb45GfYwJAI9Qw2uQWT8DmhtVbcYu6GLYGlnRyaOC -EPzc0z0KQTjhsgHWzi60IYBBh+fy+Z7w5X1rTTvhFOoU5J7kedGEqiBatIZmhF5t -UFbT0u350ET5a0Kg83gu5aLwXdoIP9o7bp3XzLBMVNny2RX3tOHUA2HBe/p0h0OU -Ggt3G6oD0gBe9pZI ------END CERTIFICATE----- diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/testng.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/testng.xml deleted file mode 100644 index 3902ad4c3a..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/testng.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/pom.xml deleted file mode 100644 index 9f546f8038..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/pom.xml +++ /dev/null @@ -1,202 +0,0 @@ - - - - - - apimgt-extensions - io.entgra.device.mgt.core - 5.0.0-SNAPSHOT - ../pom.xml - - - 4.0.0 - org.wso2.carbon.apimgt.integration.client - bundle - WSO2 Carbon - API Management Integration Client - WSO2 Carbon - API Management Integration Client - http://wso2.org - - - - - org.apache.felix - maven-scr-plugin - - - org.apache.felix - maven-bundle-plugin - 1.4.0 - true - - - ${project.artifactId} - ${project.artifactId} - ${project.version} - APIM Integration - org.wso2.carbon.apimgt.integration.client.internal - - org.wso2.carbon.apimgt.integration.client.*, - !org.wso2.carbon.apimgt.integration.client.internal - - - org.osgi.framework, - org.osgi.service.component, - feign, - feign.codec, - feign.auth, - feign.gson, - feign.slf4j, - org.wso2.carbon.apimgt.integration.generated.client.publisher.api, - org.wso2.carbon.apimgt.integration.generated.client.store.api, - javax.xml.bind, - javax.xml.bind.annotation, - javax.xml.parsers;resolution:=optional, - org.apache.commons.logging, - org.w3c.dom, - org.wso2.carbon.context, - org.wso2.carbon.identity.jwt.client.*, - org.wso2.carbon.user.api, - org.wso2.carbon.utils, - com.fasterxml.jackson.annotation, - io.swagger.annotations, - org.wso2.carbon.core.util, - javax.xml, - org.wso2.carbon.base, - javax.net.ssl, - org.apache.commons.lang, - android.util;resolution:=optional, - javax.annotation;resolution:=optional, - javax.net;resolution:=optional, - javax.security.auth.x500;resolution:=optional, - javax.crypto;resolution:=optional, - javax.crypto.spec;resolution:=optional - - - jsr311-api, - feign-jaxrs, - feign-okhttp, - okhttp, - okio - - - - - - org.jacoco - jacoco-maven-plugin - - ${basedir}/target/coverage-reports/jacoco-unit.exec - - - - jacoco-initialize - - prepare-agent - - - - jacoco-site - test - - report - - - ${basedir}/target/coverage-reports/jacoco-unit.exec - ${basedir}/target/coverage-reports/site - - - - - - - - - - com.squareup.okhttp3 - okhttp - - - com.squareup.okio - okio - - - io.github.openfeign - feign-okhttp - - - org.wso2.carbon - org.wso2.carbon.logging - - - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services - - - com.google.code.gson - gson - - - javax.ws.rs - jsr311-api - - - - io.swagger - swagger-annotations - - - junit - junit - - - io.github.openfeign - feign-core - - - io.github.openfeign - feign-jackson - - - io.github.openfeign - feign-jaxrs - - - io.github.openfeign - feign-gson - - - - org.testng - testng - - - io.entgra.device.mgt.core - io.entgra.device.mgt.core.identity.jwt.client.extension - - - io.entgra.device.mgt.core - org.wso2.carbon.apimgt.integration.generated.client - - - - diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/IntegrationClientServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/IntegrationClientServiceImpl.java deleted file mode 100644 index 2dcefcce20..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/IntegrationClientServiceImpl.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.integration.client; - -import org.wso2.carbon.apimgt.integration.client.publisher.PublisherClient; -import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService; -import org.wso2.carbon.apimgt.integration.client.store.StoreClient; - -public class IntegrationClientServiceImpl implements IntegrationClientService { - - private static volatile IntegrationClientServiceImpl instance; - private StoreClient storeClient; - private PublisherClient publisherClient; - private OAuthRequestInterceptor oAuthRequestInterceptor; - - private IntegrationClientServiceImpl() { - oAuthRequestInterceptor = new OAuthRequestInterceptor(); - storeClient = new StoreClient(oAuthRequestInterceptor); - publisherClient = new PublisherClient(oAuthRequestInterceptor); - } - - public IntegrationClientServiceImpl(OAuthRequestInterceptor oAuthRequestInterceptor) { - this.oAuthRequestInterceptor = oAuthRequestInterceptor; - storeClient = new StoreClient(oAuthRequestInterceptor); - publisherClient = new PublisherClient(oAuthRequestInterceptor); - } - - public static IntegrationClientServiceImpl getInstance() { - if (instance == null) { - synchronized (IntegrationClientService.class) { - if (instance == null) { - instance = new IntegrationClientServiceImpl(); - } - } - } - return instance; - } - - public void resetUserInfo(String userName, String tenantDomain) { - oAuthRequestInterceptor.removeToken(userName, tenantDomain); - } - - @Override - public StoreClient getStoreClient() { - return storeClient; - } - - @Override - public PublisherClient getPublisherClient() { - return publisherClient; - } -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/OAuthRequestInterceptor.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/OAuthRequestInterceptor.java deleted file mode 100755 index 46289b3ca1..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/OAuthRequestInterceptor.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * 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.wso2.carbon.apimgt.integration.client; - -import feign.Feign; -import feign.Logger; -import feign.RequestInterceptor; -import feign.RequestTemplate; -import feign.auth.BasicAuthRequestInterceptor; -import feign.gson.GsonDecoder; -import feign.gson.GsonEncoder; -import feign.jaxrs.JAXRSContract; -import feign.okhttp.OkHttpClient; -import feign.slf4j.Slf4jLogger; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.apimgt.integration.client.configs.APIMConfigReader; -import org.wso2.carbon.apimgt.integration.client.exception.APIMClientOAuthException; -import org.wso2.carbon.apimgt.integration.client.internal.APIIntegrationClientDataHolder; -import org.wso2.carbon.apimgt.integration.client.model.ClientProfile; -import org.wso2.carbon.apimgt.integration.client.model.DCRClient; -import org.wso2.carbon.apimgt.integration.client.model.OAuthApplication; -import org.wso2.carbon.apimgt.integration.client.util.Utils; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.identity.jwt.client.extension.JWTClient; -import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.AccessTokenInfo; -import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * This is a request interceptor to add oauth token header. - */ -public class OAuthRequestInterceptor implements RequestInterceptor { - - private static final String APPLICATION_NAME = "api_integration_client"; - private static final String GRANT_TYPES = "password refresh_token urn:ietf:params:oauth:grant-type:jwt-bearer"; - private static final String REQUIRED_SCOPE = - "apim:api_create apim:api_view apim:api_publish apim:subscribe apim:tier_view apim:tier_manage " + - "apim:subscription_view apim:subscription_block"; - private static final String APIM_SUBSCRIBE_SCOPE = "apim:subscribe"; - private static final long DEFAULT_REFRESH_TIME_OFFSET_IN_MILLIS = 100000; - private DCRClient dcrClient; - private OAuthApplication oAuthApplication; - private static Map tenantUserTokenMap = new ConcurrentHashMap<>(); - private static final Log log = LogFactory.getLog(OAuthRequestInterceptor.class); - private String username; - private String password; - - /** - * Creates an interceptor that authenticates all requests. - */ - public OAuthRequestInterceptor() { - username = APIMConfigReader.getInstance().getConfig().getUsername(); - password = APIMConfigReader.getInstance().getConfig().getPassword(); - dcrClient = Feign.builder().client(new OkHttpClient(Utils.getSSLClient())).logger(new Slf4jLogger()) - .logLevel(Logger.Level.FULL).requestInterceptor(new BasicAuthRequestInterceptor(username, password)) - .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) - .target(DCRClient.class, Utils.replaceProperties( - APIMConfigReader.getInstance().getConfig().getDcrEndpoint())); - } - - public OAuthRequestInterceptor(String username, String password) { - this.username = username; - this.password = password; - dcrClient = Feign.builder().client(new OkHttpClient(Utils.getSSLClient())).logger(new Slf4jLogger()) - .logLevel(Logger.Level.FULL).requestInterceptor(new BasicAuthRequestInterceptor(username, password)) - .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) - .target(DCRClient.class, Utils.replaceProperties( - APIMConfigReader.getInstance().getConfig().getDcrEndpoint())); - } - - @Override - public void apply(RequestTemplate template) { - if (oAuthApplication == null) { - //had to do on demand initialization due to start up error. - ClientProfile clientProfile = new ClientProfile(); - clientProfile.setClientName(APPLICATION_NAME); - clientProfile.setCallbackUrl(""); - clientProfile.setGrantType(GRANT_TYPES); - clientProfile.setOwner(username); - clientProfile.setSaasApp(true); - oAuthApplication = dcrClient.register(clientProfile); - } - try { - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); - if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { - username = username + "@" + tenantDomain; - } - AccessTokenInfo tenantBasedAccessTokenInfo = tenantUserTokenMap.get(username); - if ((tenantBasedAccessTokenInfo == null || - ((System.currentTimeMillis() + DEFAULT_REFRESH_TIME_OFFSET_IN_MILLIS) > - tenantBasedAccessTokenInfo.getExpiresIn()))) { - - JWTClient jwtClient = APIIntegrationClientDataHolder.getInstance().getJwtClientManagerService() - .getJWTClient(); - tenantBasedAccessTokenInfo = jwtClient.getAccessToken(oAuthApplication.getClientId(), - oAuthApplication.getClientSecret(), username, REQUIRED_SCOPE); - tenantBasedAccessTokenInfo.setExpiresIn( - System.currentTimeMillis() + (tenantBasedAccessTokenInfo.getExpiresIn() * 1000)); - if (tenantBasedAccessTokenInfo.getScopes() == null) { - throw new APIMClientOAuthException("Failed to retrieve scopes from access token"); - } - - if (tenantBasedAccessTokenInfo.getScopes().contains(APIM_SUBSCRIBE_SCOPE)) { - tenantUserTokenMap.put(username, tenantBasedAccessTokenInfo); - } - - } - if (tenantBasedAccessTokenInfo.getAccessToken() != null) { - String headerValue = "Bearer " + tenantBasedAccessTokenInfo.getAccessToken(); - template.header("Authorization", headerValue); - } - } catch (JWTClientException e) { - throw new APIMClientOAuthException("failed to retrieve oauth token using jwt", e); - } - } - - public void removeToken(String username, String tenantDomain) { - if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { - username = username + "@" + tenantDomain; - } - tenantUserTokenMap.remove(username); - } - -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/configs/APIMConfig.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/configs/APIMConfig.java deleted file mode 100644 index 1e3d34c746..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/configs/APIMConfig.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.integration.client.configs; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * This holds the configuration api manager integration. - */ -@XmlRootElement(name = "APIMConfiguration") -public class APIMConfig { - - String dcrEndpoint; - String tokenEndpoint; - String publisherEndpoint; - String storeEndpoint; - String username; - String password; - - @XmlElement(name = "DCREndpoint", required = true) - public String getDcrEndpoint() { - return dcrEndpoint; - } - - public void setDcrEndpoint(String dcrEndpoint) { - this.dcrEndpoint = dcrEndpoint; - } - - @XmlElement(name = "TokenEndpoint", required = true) - public String getTokenEndpoint() { - return tokenEndpoint; - } - - public void setTokenEndpoint(String tokenEndpoint) { - this.tokenEndpoint = tokenEndpoint; - } - - @XmlElement(name = "PublisherEndpoint", required = true) - public String getPublisherEndpoint() { - return publisherEndpoint; - } - - public void setPublisherEndpoint(String publisherEndpoint) { - this.publisherEndpoint = publisherEndpoint; - } - - @XmlElement(name = "StoreEndpoint", required = true) - public String getStoreEndpoint() { - return storeEndpoint; - } - - public void setStoreEndpoint(String storeEndpoint) { - this.storeEndpoint = storeEndpoint; - } - - @XmlElement(name = "Username", required = true) - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - @XmlElement(name = "Password", required = true) - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/configs/APIMConfigReader.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/configs/APIMConfigReader.java deleted file mode 100644 index 58f39f1a5b..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/configs/APIMConfigReader.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.integration.client.configs; - -import org.w3c.dom.Document; -import org.wso2.carbon.apimgt.integration.client.exception.APIMClientException; -import org.wso2.carbon.apimgt.integration.client.exception.InvalidConfigurationStateException; -import org.wso2.carbon.utils.CarbonUtils; - -import javax.xml.XMLConstants; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import java.io.File; - -/** - * This holds the configuration parser for api integration.xml - */ -public class APIMConfigReader { - - private static APIMConfig config; - private static APIMConfigReader configReader= new APIMConfigReader(); - private static boolean isInitialized = false; - private static final String API_INTEGRATION_CONFIG_PATH = - CarbonUtils.getCarbonConfigDirPath() + File.separator + "apim-integration.xml"; - - private APIMConfigReader() { - - } - - private static String apimIntegrationXmlFilePath = ""; - - //TOD file may be a part of another file - public static APIMConfigReader getInstance() { - if (!isInitialized) { - try { - init(); - } catch (APIMClientException e) { - throw new InvalidConfigurationStateException("Webapp Authenticator Configuration is not " + - "initialized properly"); - } - } - return configReader; - } - - public static void init() throws APIMClientException { - try { - File apimConfigFile = new File(API_INTEGRATION_CONFIG_PATH); - Document doc = convertToDocument(apimConfigFile); - - JAXBContext ctx = JAXBContext.newInstance(APIMConfig.class); - Unmarshaller unmarshaller = ctx.createUnmarshaller(); - config = (APIMConfig) unmarshaller.unmarshal(doc); - isInitialized = true; - } catch (JAXBException e) { - throw new APIMClientException("Error occurred while un-marshalling APIMConfig", e); - } - } - - private static Document convertToDocument(File file) throws APIMClientException { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - try { - factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - DocumentBuilder docBuilder = factory.newDocumentBuilder(); - return docBuilder.parse(file); - } catch (Exception e) { - throw new APIMClientException("Error occurred while parsing file 'apim-integration.xml' to a org.w3c.dom.Document", e); - } - } - - public APIMConfig getConfig() { - return config; - } - -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/exception/APIMClientException.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/exception/APIMClientException.java deleted file mode 100644 index f893f6d276..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/exception/APIMClientException.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.integration.client.exception; - -/** - * This holds api client exception. - */ -public class APIMClientException extends Exception { - - private static final long serialVersionUID = -3976392476319079281L; - private String responseReason; - private int responseStatus; - private String methodKey; - - APIMClientException(String methodKey, String reason, int status) { - super("Exception occured while invoking " + methodKey + " status = " + status + " reason = " + reason); - this.methodKey = methodKey; - this.responseReason = reason; - this.responseStatus = status; - } - - APIMClientException(String message) { - super(message); - } - - public APIMClientException(String message, Exception e) { - super(message, e); - } - - public String getResponseReason() { - return responseReason; - } - - public int getResponseStatus() { - return responseStatus; - } - - public String getMethodKey() { - return methodKey; - } - -} \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/exception/APIMClientOAuthException.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/exception/APIMClientOAuthException.java deleted file mode 100644 index 359b4b621e..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/exception/APIMClientOAuthException.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.integration.client.exception; - -/** - * This holds api client exception. - */ -public class APIMClientOAuthException extends RuntimeException { - - private static final long serialVersionUID = -3976392476319079281L; - private String responseReason; - private int responseStatus; - private String methodKey; - - APIMClientOAuthException(String methodKey, String reason, int status) { - super("Exception occured while invoking " + methodKey + " status = " + status + " reason = " + reason); - this.methodKey = methodKey; - this.responseReason = reason; - this.responseStatus = status; - } - - public APIMClientOAuthException(String message) { - super(message); - } - - public APIMClientOAuthException(String message, Exception e) { - super(message, e); - } - - public String getResponseReason() { - return responseReason; - } - - public int getResponseStatus() { - return responseStatus; - } - - public String getMethodKey() { - return methodKey; - } - -} \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/exception/InvalidConfigurationStateException.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/exception/InvalidConfigurationStateException.java deleted file mode 100644 index dedb63c4bd..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/exception/InvalidConfigurationStateException.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.integration.client.exception; - -/** - * This error is thrown when there is an issue with the client. - */ -public class InvalidConfigurationStateException extends RuntimeException { - - private static final long serialVersionUID = -3151279311329070397L; - - private String errorMessage; - private int errorCode; - - public InvalidConfigurationStateException(int errorCode, String message) { - super(message); - this.errorCode = errorCode; - } - - public InvalidConfigurationStateException(int errorCode, String message, Throwable cause) { - super(message, cause); - this.errorCode = errorCode; - } - - public int getErrorCode() { - return errorCode; - } - - - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - - public InvalidConfigurationStateException(String msg, Exception nestedEx) { - super(msg, nestedEx); - setErrorMessage(msg); - } - - public InvalidConfigurationStateException(String message, Throwable cause) { - super(message, cause); - setErrorMessage(message); - } - - public InvalidConfigurationStateException(String msg) { - super(msg); - setErrorMessage(msg); - } - - public InvalidConfigurationStateException() { - super(); - } - - public InvalidConfigurationStateException(Throwable cause) { - super(cause); - } - -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/internal/APIIntegrationClientDataHolder.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/internal/APIIntegrationClientDataHolder.java deleted file mode 100644 index 56584dfdac..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/internal/APIIntegrationClientDataHolder.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.integration.client.internal; - - -import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; - -/** - * This holds the required service for this component - */ -public class APIIntegrationClientDataHolder { - private static APIIntegrationClientDataHolder thisInstance = new APIIntegrationClientDataHolder(); - private JWTClientManagerService jwtClientManagerService; - private APIIntegrationClientDataHolder() { - } - - - public static APIIntegrationClientDataHolder getInstance() { - return thisInstance; - } - - public void setJwtClientManagerService(JWTClientManagerService jwtClientManagerService) { - this.jwtClientManagerService = jwtClientManagerService; - } - - public JWTClientManagerService getJwtClientManagerService() { - return jwtClientManagerService; - } -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/internal/APIIntegrationClientServiceComponent.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/internal/APIIntegrationClientServiceComponent.java deleted file mode 100644 index babfad55d9..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/internal/APIIntegrationClientServiceComponent.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.integration.client.internal; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.framework.BundleContext; -import org.osgi.service.component.ComponentContext; -import org.wso2.carbon.apimgt.integration.client.IntegrationClientServiceImpl; -import org.wso2.carbon.apimgt.integration.client.configs.APIMConfigReader; -import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService; -import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; - -/** - * @scr.component name="org.wso2.carbon.api.integration.client" immediate="true" - * @scr.reference name="api.integration.client.service" - * interface="io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService" - * cardinality="1..1" - * policy="dynamic" - * bind="setJWTClientManagerService" - * unbind="unsetJWTClientManagerService" - */ -public class APIIntegrationClientServiceComponent { - - private static Log log = LogFactory.getLog(APIIntegrationClientServiceComponent.class); - - protected void activate(ComponentContext componentContext) { - try { - if (log.isDebugEnabled()) { - log.debug("Initializing apimgt client bundle"); - } - - /* Initializing webapp publisher configuration */ - APIMConfigReader.init(); - BundleContext bundleContext = componentContext.getBundleContext(); - bundleContext.registerService(IntegrationClientService.class.getName(), IntegrationClientServiceImpl.getInstance(), null); - - if (log.isDebugEnabled()) { - log.debug("apimgt client bundle has been successfully initialized"); - } - } catch (Throwable e) { - log.error("Error occurred while initializing apimgt client bundle", e); - } - } - - protected void deactivate(ComponentContext componentContext) { - //do nothing - } - - protected void setJWTClientManagerService(JWTClientManagerService jwtClientManagerService) { - if (jwtClientManagerService != null) { - log.debug("jwtClientManagerService service is initialized"); - } - APIIntegrationClientDataHolder.getInstance().setJwtClientManagerService(jwtClientManagerService); - } - - protected void unsetJWTClientManagerService(JWTClientManagerService jwtClientManagerService) { - APIIntegrationClientDataHolder.getInstance().setJwtClientManagerService(null); - } - -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/model/ClientProfile.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/model/ClientProfile.java deleted file mode 100644 index fe1821d3a4..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/model/ClientProfile.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.integration.client.model; - -/** - * DTO fo DCR request. - */ -public class ClientProfile { - - private String clientName; - private String callbackUrl; - private String tokenScope; - private String owner; - private String grantType; - private boolean saasApp; - - public String getClientName() { - return clientName; - } - - public void setClientName(String clientName) { - this.clientName = clientName; - } - - public String getCallbackUrl() { - return callbackUrl; - } - - public void setCallbackUrl(String callbackUrl) { - this.callbackUrl = callbackUrl; - } - - public String getTokenScope() { - return tokenScope; - } - - public void setTokenScope(String tokenScope) { - this.tokenScope = tokenScope; - } - - public String getOwner() { - return owner; - } - - public void setOwner(String owner) { - this.owner = owner; - } - - public String getGrantType() { - return grantType; - } - - public void setGrantType(String grantTypem) { - this.grantType = grantTypem; - } - - public boolean isSaasApp() { - return saasApp; - } - - public void setSaasApp(boolean saasApp) { - this.saasApp = saasApp; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("{\n"); - - sb.append(" clientName: ").append(clientName).append("\n"); - sb.append(" callbackUrl: ").append("callbackUrl").append("\n"); - sb.append(" grantType: ").append(grantType).append("\n"); - sb.append(" tokenScope: ").append(tokenScope).append("\n"); - sb.append(" owner: ").append(owner).append("\n"); - sb.append(" saasApp: ").append(saasApp).append("\n"); - sb.append("}\n"); - return sb.toString(); - } - -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/model/DCRClient.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/model/DCRClient.java deleted file mode 100644 index 2adcfa45ad..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/model/DCRClient.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.integration.client.model; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; - -/** - * DCR Rest resource. - */ -@Path("/") -public interface DCRClient { - - // DCR APIs - @POST - @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.APPLICATION_JSON) - OAuthApplication register(ClientProfile registrationProfile); - -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/model/OAuthApplication.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/model/OAuthApplication.java deleted file mode 100644 index 7f3bf458f4..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/model/OAuthApplication.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.integration.client.model; - -public class OAuthApplication { - - private String jsonString; - private String appOwner; - private String clientName; - private String callBackURL; - private String isSaasApplication; - private String clientId; - private String clientSecret; - - public String getJsonString() { - return jsonString; - } - - public void setJsonString(String jsonString) { - this.jsonString = jsonString; - } - - public String getAppOwner() { - return appOwner; - } - - public void setAppOwner(String appOwner) { - this.appOwner = appOwner; - } - - public String getClientName() { - return clientName; - } - - public void setClientName(String clientName) { - this.clientName = clientName; - } - - public String getCallBackURL() { - return callBackURL; - } - - public void setCallBackURL(String callBackURL) { - this.callBackURL = callBackURL; - } - - public String getIsSaasApplication() { - return isSaasApplication; - } - - public void setIsSaasApplication(String isSaasApplication) { - this.isSaasApplication = isSaasApplication; - } - - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - - public String getClientSecret() { - return clientSecret; - } - - public void setClientSecret(String clientSecret) { - this.clientSecret = clientSecret; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class OAuthApplication {\n"); - - sb.append(" jsonString: ").append(jsonString).append("\n"); - sb.append(" appOwner: ").append(appOwner).append("\n"); - sb.append(" clientName: ").append(clientName).append("\n"); - sb.append(" callBackURL: ").append(callBackURL).append("\n"); - sb.append(" isSaasApplication: ").append(isSaasApplication).append("\n"); - sb.append(" clientId: ").append(isSaasApplication).append("\n"); - sb.append(" clientSecret: ").append(clientSecret).append("\n"); - sb.append("}\n"); - return sb.toString(); - } - -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/publisher/PublisherClient.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/publisher/PublisherClient.java deleted file mode 100644 index 3887d59c66..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/publisher/PublisherClient.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.integration.client.publisher; - -import feign.Feign; -import feign.Logger; -import feign.RequestInterceptor; -import feign.gson.GsonDecoder; -import feign.gson.GsonEncoder; -import feign.okhttp.OkHttpClient; -import feign.slf4j.Slf4jLogger; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.apimgt.integration.client.configs.APIMConfigReader; -import org.wso2.carbon.apimgt.integration.generated.client.publisher.api.*; -import org.wso2.carbon.core.util.Utils; - -/** - * Publisher client generated using swagger. - */ -public class PublisherClient { - - private static final Log log = LogFactory.getLog(PublisherClient.class); - private APIIndividualApi api = null; - private APICollectionApi apis = null; - private DocumentIndividualApi document = null; - private ApplicationIndividualApi application = null; - private EnvironmentCollectionApi environments = null; - private SubscriptionCollectionApi subscriptions = null; - private ThrottlingTierCollectionApi tiers = null; - - - /** - * PublisherClient constructor - Initialize a PublisherClient instance - * - */ - public PublisherClient(RequestInterceptor requestInterceptor) { - Feign.Builder builder = Feign.builder().client(new OkHttpClient( - org.wso2.carbon.apimgt.integration.client.util.Utils.getSSLClient())).logger(new - Slf4jLogger()) - .logLevel(Logger.Level.FULL) - .requestInterceptor(requestInterceptor).encoder(new GsonEncoder()).decoder(new GsonDecoder()); - String basePath = Utils.replaceSystemProperty(APIMConfigReader.getInstance().getConfig().getPublisherEndpoint()); - - api = builder.target(APIIndividualApi.class, basePath); - apis = builder.target(APICollectionApi.class, basePath); - document = builder.target(DocumentIndividualApi.class, basePath); - application = builder.target(ApplicationIndividualApi.class, basePath); - environments = builder.target(EnvironmentCollectionApi.class, basePath); - subscriptions = builder.target(SubscriptionCollectionApi.class, basePath); - tiers = builder.target(ThrottlingTierCollectionApi.class, basePath); - } - - public APIIndividualApi getApi() { - return api; - } - - public APICollectionApi getApis() { - return apis; - } - - public DocumentIndividualApi getDocument() { - return document; - } - - public ApplicationIndividualApi getApplication() { - return application; - } - - public EnvironmentCollectionApi getEnvironments() { - return environments; - } - - public SubscriptionCollectionApi getSubscriptions() { - return subscriptions; - } - - public ThrottlingTierCollectionApi getTiers() { - return tiers; - } -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/service/IntegrationClientService.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/service/IntegrationClientService.java deleted file mode 100644 index a98571ef4f..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/service/IntegrationClientService.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.integration.client.service; - - -import org.wso2.carbon.apimgt.integration.client.publisher.PublisherClient; -import org.wso2.carbon.apimgt.integration.client.store.StoreClient; - -/** - * This is a service that can be called upon to access store and publisher. - */ -public interface IntegrationClientService { - - - void resetUserInfo(String username, String tenantDomain); - - /** - * - * @return API Store Client. - */ - StoreClient getStoreClient(); - - /** - * - * @return API Publisher Client. - */ - PublisherClient getPublisherClient(); - -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/store/StoreClient.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/store/StoreClient.java deleted file mode 100644 index db751f204e..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/store/StoreClient.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.integration.client.store; - -import feign.Feign; -import feign.Logger; -import feign.Request; -import feign.RequestInterceptor; -import feign.Retryer; -import feign.gson.GsonDecoder; -import feign.gson.GsonEncoder; -import feign.okhttp.OkHttpClient; -import feign.slf4j.Slf4jLogger; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.apimgt.integration.client.configs.APIMConfigReader; -import org.wso2.carbon.apimgt.integration.generated.client.store.api.*; -import org.wso2.carbon.core.util.Utils; - -import java.util.concurrent.TimeUnit; - -/** - * API Store client, created using swagger gen. - */ -public class StoreClient { - - private static final org.apache.commons.logging.Log log = LogFactory.getLog(StoreClient.class); - private APICollectionApi apis = null; - private APIIndividualApi individualApi = null; - private ApplicationCollectionApi applications = null; - private ApplicationIndividualApi individualApplication = null; - private SubscriptionCollectionApi subscriptions = null; - private SubscriptionIndividualApi individualSubscription = null; - private SubscriptionMultitpleApi subscriptionMultitpleApi = null; - private ThrottlingTierIndividualApi individualTier = null; - private TagCollectionApi tags = null; - private ThrottlingTierCollectionApi tiers = null; - - - public StoreClient(RequestInterceptor requestInterceptor) { - - Feign.Builder builder = Feign.builder().client(new OkHttpClient( - org.wso2.carbon.apimgt.integration.client.util.Utils.getSSLClient())).logger(new - Slf4jLogger()) - .logLevel(Logger.Level.FULL) - .requestInterceptor(requestInterceptor).encoder(new GsonEncoder()).decoder(new GsonDecoder()); - String basePath = Utils.replaceSystemProperty(APIMConfigReader.getInstance().getConfig().getStoreEndpoint()); - - apis = builder.target(APICollectionApi.class, basePath); - individualApi = builder.target(APIIndividualApi.class, basePath); - applications = builder.target(ApplicationCollectionApi.class, basePath); - individualApplication = builder.target(ApplicationIndividualApi.class, basePath); - subscriptions = builder.target(SubscriptionCollectionApi.class, basePath); - individualSubscription = builder.target(SubscriptionIndividualApi.class, basePath); - subscriptionMultitpleApi = builder.target(SubscriptionMultitpleApi.class, basePath); - tags = builder.target(TagCollectionApi.class, basePath); - individualTier = builder.target(ThrottlingTierIndividualApi.class, basePath); - tiers = builder.retryer(new Retryer.Default(100L, TimeUnit.SECONDS.toMillis(1L), 1)) - .options(new Request.Options(10000, 5000)) - .target(ThrottlingTierCollectionApi.class, basePath); - - } - - public APICollectionApi getApis() { - return apis; - } - - public APIIndividualApi getIndividualApi() { - return individualApi; - } - - public ApplicationCollectionApi getApplications() { - return applications; - } - - public ApplicationIndividualApi getIndividualApplication() { - return individualApplication; - } - - public SubscriptionCollectionApi getSubscriptions() { - return subscriptions; - } - - public SubscriptionIndividualApi getIndividualSubscription() { - return individualSubscription; - } - - public ThrottlingTierIndividualApi getIndividualTier() { - return individualTier; - } - - public TagCollectionApi getTags() { - return tags; - } - - public ThrottlingTierCollectionApi getTiers() { - return tiers; - } - - public SubscriptionMultitpleApi getSubscriptionMultitpleApi() { - return subscriptionMultitpleApi; - } -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/util/Utils.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/util/Utils.java deleted file mode 100644 index 369f357ddd..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/util/Utils.java +++ /dev/null @@ -1,238 +0,0 @@ -/* -* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.integration.client.util; - -import okhttp3.OkHttpClient; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.base.ServerConfiguration; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.InetSocketAddress; -import java.net.Proxy; -import java.net.ProxySelector; -import java.net.SocketAddress; -import java.net.URI; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class Utils { - - private static final Log log = LogFactory.getLog(Utils.class); - - private static final String KEY_STORE_TYPE = "JKS"; - /** - * Default truststore type of the client - */ - private static final String TRUST_STORE_TYPE = "JKS"; - /** - * Default keymanager type of the client - */ - private static final String KEY_MANAGER_TYPE = "SunX509"; //Default Key Manager Type - /** - * Default trustmanager type of the client - */ - private static final String TRUST_MANAGER_TYPE = "SunX509"; //Default Trust Manager Type - - private static final String SSLV3 = "SSLv3"; - - private static final String DEFAULT_HOST = "localhost"; - - private static final String DEFAULT_HOST_IP = "127.0.0.1"; - - - //This method is only used if the mb features are within DAS. - public static String replaceProperties(String text) { - String regex = "\\$\\{(.*?)\\}"; - Pattern pattern = Pattern.compile(regex); - Matcher matchPattern = pattern.matcher(text); - while (matchPattern.find()) { - String sysPropertyName = matchPattern.group(1); - String sysPropertyValue = System.getProperty(sysPropertyName); - if (sysPropertyValue != null && !sysPropertyName.isEmpty()) { - text = text.replaceAll("\\$\\{(" + sysPropertyName + ")\\}", sysPropertyValue); - } - } - return text; - } - - public static OkHttpClient getSSLClient() { - - boolean isIgnoreHostnameVerification = Boolean.parseBoolean(System.getProperty("org.wso2" - + ".ignoreHostnameVerification")); - OkHttpClient okHttpClient; - final String proxyHost = System.getProperty("http.proxyHost"); - final String proxyPort = System.getProperty("http.proxyPort"); - final String nonProxyHostsValue = System.getProperty("http.nonProxyHosts"); - - final ProxySelector proxySelector = new ProxySelector() { - @Override - public List select(URI uri) { - List proxyList = new ArrayList<>(); - String host = uri.getHost(); - - if (!StringUtils.isEmpty(host)) { - if (host.startsWith(DEFAULT_HOST_IP) || host.startsWith(DEFAULT_HOST) || StringUtils - .isEmpty(nonProxyHostsValue) || StringUtils.contains(nonProxyHostsValue, host) || - StringUtils.isEmpty(proxyHost) || StringUtils.isEmpty(proxyPort)) { - proxyList.add(Proxy.NO_PROXY); - } else { - proxyList.add(new Proxy(Proxy.Type.HTTP, - new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort)))); - } - } else { - log.error("Host is null. Host could not be empty or null"); - } - return proxyList; - } - - @Override - public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { - throw new UnsupportedOperationException("Not supported yet."); - } - }; - - X509TrustManager trustAllCerts = new X509TrustManager() { - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return new java.security.cert.X509Certificate[0]; - } - public void checkClientTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - } - public void checkServerTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - } - }; - if(isIgnoreHostnameVerification) { - okHttpClient = new OkHttpClient.Builder() - .sslSocketFactory(getSimpleTrustedSSLSocketFactory(), trustAllCerts) - .hostnameVerifier(new HostnameVerifier() { - @Override - public boolean verify(String s, SSLSession sslSession) { - return true; - } - }).proxySelector(proxySelector).build(); - return okHttpClient; - }else { - SSLSocketFactory trustedSSLSocketFactory = getTrustedSSLSocketFactory(); - okHttpClient = new OkHttpClient.Builder().sslSocketFactory(trustedSSLSocketFactory) - .proxySelector(proxySelector).build(); - return okHttpClient; - } - } - - private static SSLSocketFactory getSimpleTrustedSSLSocketFactory() { - try { - TrustManager[] trustAllCerts = new TrustManager[]{ - new X509TrustManager() { - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return null; - } - public void checkClientTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - } - public void checkServerTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - } - } - }; - SSLContext sc = SSLContext.getInstance("SSL"); - sc.init(null, trustAllCerts, new java.security.SecureRandom()); - return sc.getSocketFactory(); - } catch (KeyManagementException | NoSuchAlgorithmException e) { - return null; - } - - } - - private static SSLSocketFactory getTrustedSSLSocketFactory() { - try { - String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password"); - String keyStoreLocation = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Location"); - String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty( - "Security.TrustStore.Password"); - String trustStoreLocation = ServerConfiguration.getInstance().getFirstProperty( - "Security.TrustStore.Location"); - KeyStore keyStore = loadKeyStore(keyStoreLocation,keyStorePassword,KEY_STORE_TYPE); - KeyStore trustStore = loadTrustStore(trustStoreLocation,trustStorePassword); - - return initSSLConnection(keyStore,keyStorePassword,trustStore); - } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException - |CertificateException | IOException | UnrecoverableKeyException e) { - log.error("Error while creating the SSL socket factory due to "+e.getMessage(),e); - return null; - } - - } - - private static SSLSocketFactory initSSLConnection(KeyStore keyStore,String keyStorePassword,KeyStore trustStore) throws NoSuchAlgorithmException, UnrecoverableKeyException, - KeyStoreException, KeyManagementException { - KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE); - keyManagerFactory.init(keyStore, keyStorePassword.toCharArray()); - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE); - trustManagerFactory.init(trustStore); - - // Create and initialize SSLContext for HTTPS communication - SSLContext sslContext = SSLContext.getInstance(SSLV3); - sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); - SSLContext.setDefault(sslContext); - return sslContext.getSocketFactory(); - } - - - private static KeyStore loadKeyStore(String keyStorePath, String ksPassword,String type) - throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { - InputStream fileInputStream = null; - try { - char[] keypassChar = ksPassword.toCharArray(); - KeyStore keyStore = KeyStore.getInstance(type); - fileInputStream = new FileInputStream(keyStorePath); - keyStore.load(fileInputStream, keypassChar); - return keyStore; - } finally { - if (fileInputStream != null) { - fileInputStream.close(); - } - } - } - - private static KeyStore loadTrustStore(String trustStorePath, String tsPassword) - throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { - return loadKeyStore(trustStorePath,tsPassword,TRUST_STORE_TYPE); - } -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/pom.xml deleted file mode 100644 index 5a148fbfb3..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/pom.xml +++ /dev/null @@ -1,213 +0,0 @@ - - - - - - apimgt-extensions - io.entgra.device.mgt.core - 5.0.0-SNAPSHOT - ../pom.xml - - - 4.0.0 - org.wso2.carbon.apimgt.integration.generated.client - bundle - WSO2 Carbon - API Management Integration Generated Client - WSO2 Carbon - API Management Integration Client - http://wso2.org - - - - - - io.swagger - swagger-codegen-maven-plugin - 2.2.1 - - - process-resources - publisher - - generate - - - ${project.basedir}/src/main/resources/publisher-api.yaml - java - - ${project.artifactId}.publisher.api - ${project.artifactId}.publisher.model - - feign - - - - process-resources - store - - generate - - - ${project.basedir}/src/main/resources/store-api.yaml - java - - ${project.artifactId}.store.api - ${project.artifactId}.store.model - - feign - - - - - - com.google.code.maven-replacer-plugin - replacer - 1.5.2 - - - - process-resources - replace-for-swagger-genenerated-code-publisher - - replace - - - ${project.basedir}/target/generated-sources/swagger/src/main/java/org/wso2/carbon/apimgt/integration/generated/client/publisher/model/API.java - - - CURRENT_TENANT - current_tenant - - - ALL_TENANTS - all_tenants - - - SPECIFIC_TENANTS - specific_tenants - - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - ${project.artifactId} - ${project.artifactId} - ${project.version} - APIM Integration - - org.wso2.carbon.apimgt.integration.generated.client.publisher.api.*, - org.wso2.carbon.apimgt.integration.generated.client.publisher.model.*, - org.wso2.carbon.apimgt.integration.generated.client.store.api.*, - org.wso2.carbon.apimgt.integration.generated.client.store.model.* - - - feign;version="${io.github.openfeign.version.range}", - feign.jackson;version="${io.github.openfeign.version.range}", - feign.codec;version="${io.github.openfeign.version.range}", - feign.auth;version="${io.github.openfeign.version.range}", - feign.gson;version="${io.github.openfeign.version.range}", - feign.slf4j;version="${io.github.openfeign.version.range}", - com.google.gson, - com.fasterxml.jackson.core;resolution:=optional, - com.fasterxml.jackson.annotation, - com.fasterxml.jackson.databind;resolution:=optional, - io.swagger.annotations, - javax.net.ssl, - com.fasterxml.jackson.datatype.joda;resolution:=optional, - org.apache.oltu.oauth2.client.*;resolution:=optional, - org.apache.oltu.oauth2.common.*;resolution:=optional, - org.junit;resolution:=optional, - - - jsr311-api, - feign-jaxrs - - - - - - - - - - - com.google.code.gson - gson - - - javax.ws.rs - jsr311-api - - - - io.swagger - swagger-annotations - - - junit - junit - - - io.github.openfeign - feign-core - - - io.github.openfeign - feign-jackson - - - io.github.openfeign - feign-jaxrs - - - io.github.openfeign - feign-gson - - - org.testng - testng - - - org.apache.oltu.oauth2 - org.apache.oltu.oauth2.client - - - io.github.openfeign - feign-slf4j - - - org.wso2.orbit.com.fasterxml.jackson.core - jackson-databind - ${jackson-databind.version} - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - - - - true - - diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/src/main/resources/publisher-api.yaml b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/src/main/resources/publisher-api.yaml deleted file mode 100644 index b2068857a7..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/src/main/resources/publisher-api.yaml +++ /dev/null @@ -1,3691 +0,0 @@ - -swagger: '2.0' -###################################################### -# Prolog -###################################################### -info: - version: "0.12.0" - title: "WSO2 API Manager - Publisher API" - description: | - This specifies a **RESTful API** for WSO2 **API Manager** - Publisher. - - Please see [full swagger definition](https://raw.githubusercontent.com/wso2/carbon-apimgt/v6.1.66/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher/src/main/resources/publisher-api.yaml) of the API which is written using [swagger 2.0](http://swagger.io/) specification. - contact: - name: "WSO2" - url: "http://wso2.com/products/api-manager/" - email: "architecture@wso2.com" - license: - name: "Apache 2.0" - url: "http://www.apache.org/licenses/LICENSE-2.0.html" - -###################################################### -# The fixed parts of the URLs of the API -###################################################### - -# The schemes supported by the API -schemes: - - https - -# The domain of the API. -# This is configured by the customer during deployment. -# The given host is just an example. -host: apis.wso2.com - -# The base path of the API. -# Will be prefixed to all paths. -basePath: /api/am/publisher/v0.12 - -# The following media types can be passed as input in message bodies of the API. -# The actual media type must be specified in the Content-Type header field of the request. -# The default is json, i.e. the Content-Type header is not needed to -# be set, but supporting it serves extensibility. -consumes: - - application/json - -# The following media types may be passed as output in message bodies of the API. -# The media type(s) consumable by the requestor is specified in the Accept header field -# of the corresponding request. -# The actual media type returned will be specfied in the Content-Type header field -# of the of the response. -# The default of the Accept header is json, i.e. there is not needed to -# set the value, but supporting it serves extensibility. -produces: - - application/json - - -x-wso2-security: - apim: - x-wso2-scopes: - - description: "" - roles: admin - name: apim:api_view - key: apim:api_view - - description: "" - roles: admin - name: apim:api_create - key: apim:api_create - - description: "" - roles: admin - name: apim:api_publish - key: apim:api_publish - - description: "" - roles: admin - name: apim:tier_view - key: apim:tier_view - - description: "" - roles: admin - name: apim:tier_manage - key: apim:tier_manage - - description: "" - roles: admin - name: apim:subscription_view - key: apim:subscription_view - - description: "" - roles: admin - name: apim:subscription_block - key: apim:subscription_block - - description: "" - roles: admin - name: apim:mediation_policy_view - key: apim:mediation_policy_view - - description: "" - roles: admin - name: apim:api_workflow - key: apim:api_workflow - - -###################################################### -# The "API Collection" resource APIs -###################################################### -paths: - /apis: - -#----------------------------------------------------- -# Retrieving the list of all APIs qualifying under a given search condition -#----------------------------------------------------- - get: - x-scope: apim:api_view - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" https://localhost:9443/api/am/publisher/v0.12/apis" - x-wso2-request: | - GET https://localhost:9443/api/am/publisher/v0.12/apis - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"previous\": \"\",\n \"list\": [\n {\n \"provider\": \"admin\",\n \"version\": \"1.0.0\",\n \"description\": \"This sample API provides Account Status Validation\",\n \"name\": \"AccountVal\",\n \"context\": \"/account\",\n \"id\": \"2e81f147-c8a8-4f68-b4f0-69e0e7510b01\",\n \"status\": \"PUBLISHED\"\n },\n {\n \"provider\": \"admin\",\n \"version\": \"1.0.0\",\n \"description\": null,\n \"name\": \"api1\",\n \"context\": \"/api1\",\n \"id\": \"3e22d2fb-277a-4e9e-8c7e-1c0f7f73960e\",\n \"status\": \"PUBLISHED\"\n }\n ],\n \"next\": \"\",\n \"count\": 2\n}" - summary: | - Retrieve/Search APIs - description: | - This operation provides you a list of available APIs qualifying under a given search condition. - - Each retrieved API is represented with a minimal amount of attributes. If you want to get complete details of an API, you need to use **Get details of an API** operation. - parameters: - - $ref : '#/parameters/limit' - - $ref : '#/parameters/offset' - - name : query - in: query - description: | - **Search condition**. - - You can search in attributes by using an **":"** modifier. - - Eg. - "provider:wso2" will match an API if the provider of the API is exactly "wso2". - - Additionally you can use wildcards. - - Eg. - "provider:wso2*" will match an API if the provider of the API starts with "wso2". - - Supported attribute modifiers are [**version, context, status, - description, subcontext, doc, provider**] - - If no advanced attribute modifier has been specified, the API names containing - the search term will be returned as a result. - - type: string - - $ref : "#/parameters/Accept" - - $ref : "#/parameters/If-None-Match" - tags: - - API (Collection) - responses: - 200: - description: | - OK. - List of qualifying APIs is returned. - schema: - $ref: '#/definitions/APIList' - headers: - Content-Type: - description: The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -#----------------------------------------------------- -# Create a new API -API (Individual) -#----------------------------------------------------- - post: - x-scope: apim:api_create - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -H \"Content-Type: application/json\" -X POST -d @data.json https://localhost:9443/api/am/publisher/v0.12/apis" - x-wso2-request: "POST https://localhost:9443/api/am/publisher/v0.12/apis\nAuthorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\n\n{\r\n \"name\": \"PizzaShackAPI\",\r\n \"description\": \"This document describe a RESTFul API for Pizza Shack online pizza delivery store.\\r\\n\",\r\n \"context\": \"/pizzashack\",\r\n \"version\": \"1.0.0\",\r\n \"provider\": \"admin\",\r\n \"apiDefinition\": \"{\\\"paths\\\":{\\\"/order\\\":{\\\"post\\\":{\\\"x-auth-type\\\":\\\"Application & Application User\\\",\\\"x-throttling-tier\\\":\\\"Unlimited\\\",\\\"description\\\":\\\"Create a new Order\\\",\\\"parameters\\\":[{\\\"schema\\\":{\\\"$ref\\\":\\\"#/definitions/Order\\\"},\\\"description\\\":\\\"Order object that needs to be added\\\",\\\"name\\\":\\\"body\\\",\\\"required\\\":true,\\\"in\\\":\\\"body\\\"}],\\\"responses\\\":{\\\"201\\\":{\\\"headers\\\":{\\\"Location\\\":{\\\"description\\\":\\\"The URL of the newly created resource.\\\",\\\"type\\\":\\\"string\\\"}},\\\"schema\\\":{\\\"$ref\\\":\\\"#/definitions/Order\\\"},\\\"description\\\":\\\"Created.\\\"}}}},\\\"/menu\\\":{\\\"get\\\":{\\\"x-auth-type\\\":\\\"Application & Application User\\\",\\\"x-throttling-tier\\\":\\\"Unlimited\\\",\\\"description\\\":\\\"Return a list of available menu items\\\",\\\"parameters\\\":[],\\\"responses\\\":{\\\"200\\\":{\\\"headers\\\":{},\\\"schema\\\":{\\\"title\\\":\\\"Menu\\\",\\\"properties\\\":{\\\"list\\\":{\\\"items\\\":{\\\"$ref\\\":\\\"#/definitions/MenuItem\\\"},\\\"type\\\":\\\"array\\\"}},\\\"type\\\":\\\"object\\\"},\\\"description\\\":\\\"OK.\\\"}}}}},\\\"schemes\\\":[\\\"https\\\"],\\\"produces\\\":[\\\"application/json\\\"],\\\"swagger\\\":\\\"2.0\\\",\\\"definitions\\\":{\\\"MenuItem\\\":{\\\"title\\\":\\\"Pizza menu Item\\\",\\\"properties\\\":{\\\"price\\\":{\\\"type\\\":\\\"string\\\"},\\\"description\\\":{\\\"type\\\":\\\"string\\\"},\\\"name\\\":{\\\"type\\\":\\\"string\\\"},\\\"image\\\":{\\\"type\\\":\\\"string\\\"}},\\\"required\\\":[\\\"name\\\"]},\\\"Order\\\":{\\\"title\\\":\\\"Pizza Order\\\",\\\"properties\\\":{\\\"customerName\\\":{\\\"type\\\":\\\"string\\\"},\\\"delivered\\\":{\\\"type\\\":\\\"boolean\\\"},\\\"address\\\":{\\\"type\\\":\\\"string\\\"},\\\"pizzaType\\\":{\\\"type\\\":\\\"string\\\"},\\\"creditCardNumber\\\":{\\\"type\\\":\\\"string\\\"},\\\"quantity\\\":{\\\"type\\\":\\\"number\\\"},\\\"orderId\\\":{\\\"type\\\":\\\"string\\\"}},\\\"required\\\":[\\\"orderId\\\"]}},\\\"consumes\\\":[\\\"application/json\\\"],\\\"info\\\":{\\\"title\\\":\\\"PizzaShackAPI\\\",\\\"description\\\":\\\"This document describe a RESTFul API for Pizza Shack online pizza delivery store.\\\\n\\\",\\\"license\\\":{\\\"name\\\":\\\"Apache 2.0\\\",\\\"url\\\":\\\"http://www.apache.org/licenses/LICENSE-2.0.html\\\"},\\\"contact\\\":{\\\"email\\\":\\\"architecture@pizzashack.com\\\",\\\"name\\\":\\\"John Doe\\\",\\\"url\\\":\\\"http://www.pizzashack.com\\\"},\\\"version\\\":\\\"1.0.0\\\"}}\",\r\n \"wsdlUri\": null,\r\n \"status\": \"PUBLISHED\",\r\n \"responseCaching\": \"Disabled\",\r\n \"cacheTimeout\": 300,\r\n \"destinationStatsEnabled\": false,\r\n \"isDefaultVersion\": false,\r\n \"type\": \"HTTP\",\r\n \"transport\": [\r\n \"http\",\r\n \"https\"\r\n ],\r\n \"tags\": [\"pizza\"],\r\n \"tiers\": [\"Unlimited\"],\r\n \"maxTps\": {\r\n \"sandbox\": 5000,\r\n \"production\": 1000\r\n },\r\n \"visibility\": \"PUBLIC\",\r\n \"visibleRoles\": [],\\r\n \"endpointConfig\": \"{\\\"production_endpoints\\\":{\\\"url\\\":\\\"https://localhost:9443/am/sample/pizzashack/v1/api/\\\",\\\"config\\\":null},\\\"sandbox_endpoints\\\":{\\\"url\\\":\\\"https://localhost:9443/am/sample/pizzashack/v1/api/\\\",\\\"config\\\":null},\\\"endpoint_type\\\":\\\"http\\\"}\",\r\n \"endpointSecurity\": {\r\n \"username\": \"user\",\r\n \"type\": \"basic\",\r\n \"password\": \"pass\"\r\n },\r\n \"gatewayEnvironments\": \"Production and Sandbox\",\r\n \"sequences\": [{\"name\":\"json_validator\",\"type\": \"in\"},{\"name\":\"log_out_message\",\"type\": \"out\"}],\r\n \"subscriptionAvailability\": null,\r\n \"subscriptionAvailableTenants\": [],\r\n \"businessInformation\": {\r\n \"businessOwnerEmail\": \"marketing@pizzashack.com\",\r\n \"technicalOwnerEmail\": \"architecture@pizzashack.com\",\r\n \"technicalOwner\": \"John Doe\",\r\n \"businessOwner\": \"Jane Roe\"\r\n },\r\n \"corsConfiguration\": {\r\n \"accessControlAllowOrigins\": [\"*\"],\r\n \"accessControlAllowHeaders\": [\r\n \"authorization\",\r\n \"Access-Control-Allow-Origin\",\r\n \"Content-Type\",\r\n \"SOAPAction\"\r\n ],\r\n \"accessControlAllowMethods\": [\r\n \"GET\",\r\n \"PUT\",\r\n \"POST\",\r\n \"DELETE\",\r\n \"PATCH\",\r\n \"OPTIONS\"\r\n ],\r\n \"accessControlAllowCredentials\": false,\r\n \"corsConfigurationEnabled\": false\r\n }\r\n}" - x-wso2-response: "HTTP/1.1 201 Created\nLocation: https://localhost:9443/api/am/publisher/v0.12/apis/7a2298c4-c905-403f-8fac-38c73301631f\nContent-Type: application/json\n\n{\r\n \"id\": \"7a2298c4-c905-403f-8fac-38c73301631f\",\r\n \"name\": \"PizzaShackAPI\",\r\n \"description\": \"This document describe a RESTFul API for Pizza Shack online pizza delivery store.\\r\\n\",\r\n \"context\": \"/pizzashack\",\r\n \"version\": \"1.0.0\",\r\n \"provider\": \"admin\",\r\n \"apiDefinition\": \"{\\\"paths\\\":{\\\"/order\\\":{\\\"post\\\":{\\\"x-auth-type\\\":\\\"Application & Application User\\\",\\\"x-throttling-tier\\\":\\\"Unlimited\\\",\\\"description\\\":\\\"Create a new Order\\\",\\\"parameters\\\":[{\\\"schema\\\":{\\\"$ref\\\":\\\"#/definitions/Order\\\"},\\\"description\\\":\\\"Order object that needs to be added\\\",\\\"name\\\":\\\"body\\\",\\\"required\\\":true,\\\"in\\\":\\\"body\\\"}],\\\"responses\\\":{\\\"201\\\":{\\\"headers\\\":{\\\"Location\\\":{\\\"description\\\":\\\"The URL of the newly created resource.\\\",\\\"type\\\":\\\"string\\\"}},\\\"schema\\\":{\\\"$ref\\\":\\\"#/definitions/Order\\\"},\\\"description\\\":\\\"Created.\\\"}}}},\\\"/menu\\\":{\\\"get\\\":{\\\"x-auth-type\\\":\\\"Application & Application User\\\",\\\"x-throttling-tier\\\":\\\"Unlimited\\\",\\\"description\\\":\\\"Return a list of available menu items\\\",\\\"parameters\\\":[],\\\"responses\\\":{\\\"200\\\":{\\\"headers\\\":{},\\\"schema\\\":{\\\"title\\\":\\\"Menu\\\",\\\"properties\\\":{\\\"list\\\":{\\\"items\\\":{\\\"$ref\\\":\\\"#/definitions/MenuItem\\\"},\\\"type\\\":\\\"array\\\"}},\\\"type\\\":\\\"object\\\"},\\\"description\\\":\\\"OK.\\\"}}}}},\\\"schemes\\\":[\\\"https\\\"],\\\"produces\\\":[\\\"application/json\\\"],\\\"swagger\\\":\\\"2.0\\\",\\\"definitions\\\":{\\\"MenuItem\\\":{\\\"title\\\":\\\"Pizza menu Item\\\",\\\"properties\\\":{\\\"price\\\":{\\\"type\\\":\\\"string\\\"},\\\"description\\\":{\\\"type\\\":\\\"string\\\"},\\\"name\\\":{\\\"type\\\":\\\"string\\\"},\\\"image\\\":{\\\"type\\\":\\\"string\\\"}},\\\"required\\\":[\\\"name\\\"]},\\\"Order\\\":{\\\"title\\\":\\\"Pizza Order\\\",\\\"properties\\\":{\\\"customerName\\\":{\\\"type\\\":\\\"string\\\"},\\\"delivered\\\":{\\\"type\\\":\\\"boolean\\\"},\\\"address\\\":{\\\"type\\\":\\\"string\\\"},\\\"pizzaType\\\":{\\\"type\\\":\\\"string\\\"},\\\"creditCardNumber\\\":{\\\"type\\\":\\\"string\\\"},\\\"quantity\\\":{\\\"type\\\":\\\"number\\\"},\\\"orderId\\\":{\\\"type\\\":\\\"integer\\\"}},\\\"required\\\":[\\\"orderId\\\"]}},\\\"consumes\\\":[\\\"application/json\\\"],\\\"info\\\":{\\\"title\\\":\\\"PizzaShackAPI\\\",\\\"description\\\":\\\"This document describe a RESTFul API for Pizza Shack online pizza delivery store.\\\\n\\\",\\\"license\\\":{\\\"name\\\":\\\"Apache 2.0\\\",\\\"url\\\":\\\"http://www.apache.org/licenses/LICENSE-2.0.html\\\"},\\\"contact\\\":{\\\"email\\\":\\\"architecture@pizzashack.com\\\",\\\"name\\\":\\\"John Doe\\\",\\\"url\\\":\\\"http://www.pizzashack.com\\\"},\\\"version\\\":\\\"1.0.0\\\"}}\",\r\n \"wsdlUri\": null,\r\n \"responseCaching\": \"Disabled\",\r\n \"cacheTimeout\": 300,\r\n \"destinationStatsEnabled\": null,\r\n \"isDefaultVersion\": false,\r\n \"type\": \"HTTP\",\r\n \"transport\": [\r\n \"http\",\r\n \"https\"\r\n ],\r\n \"tags\": [\"pizza\"],\r\n \"tiers\": [\"Unlimited\"],\r\n \"maxTps\": {\r\n \"sandbox\": 5000,\r\n \"production\": 1000\r\n },\r\n \"thumbnailUri\": null,\r\n \"visibility\": \"PUBLIC\",\r\n \"visibleRoles\": [],\\r\n \"endpointConfig\": \"{\\\"production_endpoints\\\":{\\\"url\\\":\\\"https://localhost:9443/am/sample/pizzashack/v1/api/\\\",\\\"config\\\":null},\\\"sandbox_endpoints\\\":{\\\"url\\\":\\\"https://localhost:9443/am/sample/pizzashack/v1/api/\\\",\\\"config\\\":null},\\\"endpoint_type\\\":\\\"http\\\"}\",\r\n \"endpointSecurity\": {\r\n \"username\": \"user\",\r\n \"type\": \"basic\",\r\n \"password\": \"pass\"\r\n },\r\n \"gatewayEnvironments\": \"Production and Sandbox\",\r\n \"sequences\": [{\"name\":\"json_validator\",\"type\":\"in\",\"id\":\"142ece76-b208-4aab-b29a-f382045ed066\",\"shared\":false},{\"name\":\"log_out_message\",\"type\":\"out\",\"id\":\"b3527be8-95e6-41e0-8097-3276987b7d4b\",\"shared\":false}],\r\n \"subscriptionAvailability\": null,\r\n \"subscriptionAvailableTenants\": [],\r\n \"businessInformation\": {\r\n \"businessOwnerEmail\": \"marketing@pizzashack.com\",\r\n \"technicalOwnerEmail\": \"architecture@pizzashack.com\",\r\n \"technicalOwner\": \"John Doe\",\r\n \"businessOwner\": \"Jane Roe\"\r\n },\r\n \"corsConfiguration\": {\r\n \"accessControlAllowOrigins\": [\"*\"],\r\n \"accessControlAllowHeaders\": [\r\n \"authorization\",\r\n \"Access-Control-Allow-Origin\",\r\n \"Content-Type\",\r\n \"SOAPAction\"\r\n ],\r\n \"accessControlAllowMethods\": [\r\n \"GET\",\r\n \"PUT\",\r\n \"POST\",\r\n \"DELETE\",\r\n \"PATCH\",\r\n \"OPTIONS\"\r\n ],\r\n \"accessControlAllowCredentials\": false,\r\n \"corsConfigurationEnabled\": false\r\n }\r\n}" - summary: Create a new API - description: | - This operation can be used to create a new API specifying the details of the API in the payload. The new API will be in `CREATED` state. - - There is a special capability for a user who has `APIM Admin` permission such that he can create APIs on behalf of other users. For that he can to specify `"provider" : "some_other_user"` in the payload so that the API's creator will be shown as `some_other_user` in the UI. - parameters: - - in: body - name: body - description: | - API object that needs to be added - required: true - schema: - $ref: '#/definitions/API' - - $ref: '#/parameters/Content-Type' - - $ref: '#/parameters/Authorization' - tags: - - API (Individual) - responses: - 201: - description: | - Created. - Successful response with the newly created object as entity in the body. - Location header contains URL of newly created entity. - schema: - $ref: '#/definitions/API' - headers: - Location: - description: | - The URL of the newly created resource. - type: string - Content-Type: - description: | - The content type of the body. - type: string - Authorization: - description: | - The brearer token. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). - type: string - 400: - description: | - Bad Request. - Invalid request or validation error. - schema: - $ref: '#/definitions/Error' - 415: - description: | - Unsupported Media Type. - The entity of the request was in a not supported format. - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Individual API" resource APIs -###################################################### - /apis/{apiId}: - -#----------------------------------------------------- -# Retrieve the details of an API definition -#----------------------------------------------------- - get: - x-scope: apim:api_view - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" https://localhost:9443/api/am/publisher/v0.12/apis/7a2298c4-c905-403f-8fac-38c73301631f" - x-wso2-request: | - GET https://localhost:9443/api/am/publisher/v0.12/apis/7a2298c4-c905-403f-8fac-38c73301631f - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\r\n \"id\": \"7a2298c4-c905-403f-8fac-38c73301631f\",\r\n \"name\": \"PizzaShackAPI\",\r\n \"description\": \"This document describe a RESTFul API for Pizza Shack online pizza delivery store.\\r\\n\",\r\n \"context\": \"/pizzashack\",\r\n \"version\": \"1.0.0\",\r\n \"provider\": \"admin\",\r\n \"apiDefinition\": \"{\\\"paths\\\":{\\\"/order\\\":{\\\"post\\\":{\\\"x-auth-type\\\":\\\"Application & Application User\\\",\\\"x-throttling-tier\\\":\\\"Unlimited\\\",\\\"description\\\":\\\"Create a new Order\\\",\\\"parameters\\\":[{\\\"schema\\\":{\\\"$ref\\\":\\\"#/definitions/Order\\\"},\\\"description\\\":\\\"Order object that needs to be added\\\",\\\"name\\\":\\\"body\\\",\\\"required\\\":true,\\\"in\\\":\\\"body\\\"}],\\\"responses\\\":{\\\"201\\\":{\\\"headers\\\":{\\\"Location\\\":{\\\"description\\\":\\\"The URL of the newly created resource.\\\",\\\"type\\\":\\\"string\\\"}},\\\"schema\\\":{\\\"$ref\\\":\\\"#/definitions/Order\\\"},\\\"description\\\":\\\"Created.\\\"}}}},\\\"/menu\\\":{\\\"get\\\":{\\\"x-auth-type\\\":\\\"Application & Application User\\\",\\\"x-throttling-tier\\\":\\\"Unlimited\\\",\\\"description\\\":\\\"Return a list of available menu items\\\",\\\"parameters\\\":[],\\\"responses\\\":{\\\"200\\\":{\\\"headers\\\":{},\\\"schema\\\":{\\\"title\\\":\\\"Menu\\\",\\\"properties\\\":{\\\"list\\\":{\\\"items\\\":{\\\"$ref\\\":\\\"#/definitions/MenuItem\\\"},\\\"type\\\":\\\"array\\\"}},\\\"type\\\":\\\"object\\\"},\\\"description\\\":\\\"OK.\\\"}}}}},\\\"schemes\\\":[\\\"https\\\"],\\\"produces\\\":[\\\"application/json\\\"],\\\"swagger\\\":\\\"2.0\\\",\\\"definitions\\\":{\\\"MenuItem\\\":{\\\"title\\\":\\\"Pizza menu Item\\\",\\\"properties\\\":{\\\"price\\\":{\\\"type\\\":\\\"string\\\"},\\\"description\\\":{\\\"type\\\":\\\"string\\\"},\\\"name\\\":{\\\"type\\\":\\\"string\\\"},\\\"image\\\":{\\\"type\\\":\\\"string\\\"}},\\\"required\\\":[\\\"name\\\"]},\\\"Order\\\":{\\\"title\\\":\\\"Pizza Order\\\",\\\"properties\\\":{\\\"customerName\\\":{\\\"type\\\":\\\"string\\\"},\\\"delivered\\\":{\\\"type\\\":\\\"boolean\\\"},\\\"address\\\":{\\\"type\\\":\\\"string\\\"},\\\"pizzaType\\\":{\\\"type\\\":\\\"string\\\"},\\\"creditCardNumber\\\":{\\\"type\\\":\\\"string\\\"},\\\"quantity\\\":{\\\"type\\\":\\\"number\\\"},\\\"orderId\\\":{\\\"type\\\":\\\"string\\\"}},\\\"required\\\":[\\\"orderId\\\"]}},\\\"consumes\\\":[\\\"application/json\\\"],\\\"info\\\":{\\\"title\\\":\\\"PizzaShackAPI\\\",\\\"description\\\":\\\"This document describe a RESTFul API for Pizza Shack online pizza delivery store.\\\\n\\\",\\\"license\\\":{\\\"name\\\":\\\"Apache 2.0\\\",\\\"url\\\":\\\"http://www.apache.org/licenses/LICENSE-2.0.html\\\"},\\\"contact\\\":{\\\"email\\\":\\\"architecture@pizzashack.com\\\",\\\"name\\\":\\\"John Doe\\\",\\\"url\\\":\\\"http://www.pizzashack.com\\\"},\\\"version\\\":\\\"1.0.0\\\"}}\",\r\n \"wsdlUri\": null,\r\n \"status\": \"CREATED\",\r\n \"responseCaching\": \"Disabled\",\r\n \"cacheTimeout\": 300,\r\n \"destinationStatsEnabled\": null,\r\n \"isDefaultVersion\": false,\r\n \"type\": \"HTTP\",\r\n \"transport\": [\r\n \"http\",\r\n \"https\"\r\n ],\r\n \"tags\": [\"pizza\"],\r\n \"tiers\": [\"Unlimited\"],\r\n \"maxTps\": {\r\n \"sandbox\": 5000,\r\n \"production\": 1000\r\n },\r\n \"thumbnailUri\": null,\r\n \"visibility\": \"PUBLIC\",\r\n \"visibleRoles\": [],\\r\n \"endpointConfig\": \"{\\\"production_endpoints\\\":{\\\"url\\\":\\\"https://localhost:9443/am/sample/pizzashack/v1/api/\\\",\\\"config\\\":null},\\\"sandbox_endpoints\\\":{\\\"url\\\":\\\"https://localhost:9443/am/sample/pizzashack/v1/api/\\\",\\\"config\\\":null},\\\"endpoint_type\\\":\\\"http\\\"}\",\r\n \"endpointSecurity\": {\r\n \"username\": \"user\",\r\n \"type\": \"basic\",\r\n \"password\": \"pass\"\r\n },\r\n \"gatewayEnvironments\": \"Production and Sandbox\",\r\n \"sequences\": [],\r\n \"subscriptionAvailability\": null,\r\n \"subscriptionAvailableTenants\": [],\r\n \"businessInformation\": {\r\n \"businessOwnerEmail\": \"marketing@pizzashack.com\",\r\n \"technicalOwnerEmail\": \"architecture@pizzashack.com\",\r\n \"technicalOwner\": \"John Doe\",\r\n \"businessOwner\": \"Jane Roe\"\r\n },\r\n \"corsConfiguration\": {\r\n \"accessControlAllowOrigins\": [\"*\"],\r\n \"accessControlAllowHeaders\": [\r\n \"authorization\",\r\n \"Access-Control-Allow-Origin\",\r\n \"Content-Type\",\r\n \"SOAPAction\"\r\n ],\r\n \"accessControlAllowMethods\": [\r\n \"GET\",\r\n \"PUT\",\r\n \"POST\",\r\n \"DELETE\",\r\n \"PATCH\",\r\n \"OPTIONS\"\r\n ],\r\n \"accessControlAllowCredentials\": false,\r\n \"corsConfigurationEnabled\": false\r\n }\r\n}" - summary: Get details of an API - description: | - Using this operation, you can retrieve complete details of a single API. You need to provide the Id of the API to retrive it. - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - - $ref: '#/parameters/If-Modified-Since' - tags: - - API (Individual) - responses: - 200: - description: | - OK. - Requested API is returned - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - schema: - $ref: '#/definitions/API' - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 404: - description: | - Not Found. - Requested API does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -#----------------------------------------------------- -# Update the definition of an API -#----------------------------------------------------- - put: - x-scope: apim:api_create - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -H \"Content-Type: application/json\" -X PUT -d @data.json https://localhost:9443/api/am/publisher/v0.12/apis/7a2298c4-c905-403f-8fac-38c73301631f" - x-wso2-request: "PUT https://localhost:9443/api/am/publisher/v0.12/apis/7a2298c4-c905-403f-8fac-38c73301631f\nAuthorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\nContent-Type: application/json\n\n{\r\n \"id\": \"7a2298c4-c905-403f-8fac-38c73301631f\",\r\n \"name\": \"PizzaShackAPI\",\r\n \"description\": \"This document describe a RESTFul API for Pizza Shack online pizza delivery store.\\r\\n\",\r\n \"context\": \"/pizzashack\",\r\n \"version\": \"1.0.0\",\r\n \"provider\": \"admin\",\r\n \"apiDefinition\": \"{\\\"paths\\\":{\\\"/order\\\":{\\\"post\\\":{\\\"x-auth-type\\\":\\\"Application & Application User\\\",\\\"x-throttling-tier\\\":\\\"Unlimited\\\",\\\"description\\\":\\\"Create a new Order\\\",\\\"parameters\\\":[{\\\"schema\\\":{\\\"$ref\\\":\\\"#/definitions/Order\\\"},\\\"description\\\":\\\"Order object that needs to be added\\\",\\\"name\\\":\\\"body\\\",\\\"required\\\":true,\\\"in\\\":\\\"body\\\"}],\\\"responses\\\":{\\\"201\\\":{\\\"headers\\\":{\\\"Location\\\":{\\\"description\\\":\\\"The URL of the newly created resource.\\\",\\\"type\\\":\\\"string\\\"}},\\\"schema\\\":{\\\"$ref\\\":\\\"#/definitions/Order\\\"},\\\"description\\\":\\\"Created.\\\"}}}},\\\"/menu\\\":{\\\"get\\\":{\\\"x-auth-type\\\":\\\"Application & Application User\\\",\\\"x-throttling-tier\\\":\\\"Unlimited\\\",\\\"description\\\":\\\"Return a list of available menu items\\\",\\\"parameters\\\":[],\\\"responses\\\":{\\\"200\\\":{\\\"headers\\\":{},\\\"schema\\\":{\\\"title\\\":\\\"Menu\\\",\\\"properties\\\":{\\\"list\\\":{\\\"items\\\":{\\\"$ref\\\":\\\"#/definitions/MenuItem\\\"},\\\"type\\\":\\\"array\\\"}},\\\"type\\\":\\\"object\\\"},\\\"description\\\":\\\"OK.\\\"}}}}},\\\"schemes\\\":[\\\"https\\\"],\\\"produces\\\":[\\\"application/json\\\"],\\\"swagger\\\":\\\"2.0\\\",\\\"definitions\\\":{\\\"MenuItem\\\":{\\\"title\\\":\\\"Pizza menu Item\\\",\\\"properties\\\":{\\\"price\\\":{\\\"type\\\":\\\"string\\\"},\\\"description\\\":{\\\"type\\\":\\\"string\\\"},\\\"name\\\":{\\\"type\\\":\\\"string\\\"},\\\"image\\\":{\\\"type\\\":\\\"string\\\"}},\\\"required\\\":[\\\"name\\\"]},\\\"Order\\\":{\\\"title\\\":\\\"Pizza Order\\\",\\\"properties\\\":{\\\"customerName\\\":{\\\"type\\\":\\\"string\\\"},\\\"delivered\\\":{\\\"type\\\":\\\"boolean\\\"},\\\"address\\\":{\\\"type\\\":\\\"string\\\"},\\\"pizzaType\\\":{\\\"type\\\":\\\"string\\\"},\\\"creditCardNumber\\\":{\\\"type\\\":\\\"string\\\"},\\\"quantity\\\":{\\\"type\\\":\\\"number\\\"},\\\"orderId\\\":{\\\"type\\\":\\\"integer\\\"}},\\\"required\\\":[\\\"orderId\\\"]}},\\\"consumes\\\":[\\\"application/json\\\"],\\\"info\\\":{\\\"title\\\":\\\"PizzaShackAPI\\\",\\\"description\\\":\\\"This document describe a RESTFul API for Pizza Shack online pizza delivery store.\\\\n\\\",\\\"license\\\":{\\\"name\\\":\\\"Apache 2.0\\\",\\\"url\\\":\\\"http://www.apache.org/licenses/LICENSE-2.0.html\\\"},\\\"contact\\\":{\\\"email\\\":\\\"architecture@pizzashack.com\\\",\\\"name\\\":\\\"John Doe\\\",\\\"url\\\":\\\"http://www.pizzashack.com\\\"},\\\"version\\\":\\\"1.0.0\\\"}}\",\r\n \"wsdlUri\": null,\r\n \"status\": \"CREATED\",\r\n \"responseCaching\": \"Disabled\",\r\n \"cacheTimeout\": 300,\r\n \"destinationStatsEnabled\": null,\r\n \"isDefaultVersion\": false,\r\n \"type\": \"HTTP\",\r\n \"transport\": [\r\n \"https\"\r\n ],\r\n \"tags\": [\"pizza\",\"chicken\"],\r\n \"tiers\": [\"Unlimited\"],\r\n \"maxTps\": {\r\n \"sandbox\": 500,\r\n \"production\": 100\r\n },\r\n \"thumbnailUri\": null,\r\n \"visibility\": \"PUBLIC\",\r\n \"visibleRoles\": [],\\r\n \"endpointConfig\": \"{\\\"production_endpoints\\\":{\\\"url\\\":\\\"https://localhost:9443/am/sample/pizzashack/v1/api/\\\",\\\"config\\\":null},\\\"sandbox_endpoints\\\":{\\\"url\\\":\\\"https://localhost:9443/am/sample/pizzashack/v1/api/\\\",\\\"config\\\":null},\\\"endpoint_type\\\":\\\"http\\\"}\",\r\n \"endpointSecurity\": {\r\n \"username\": \"user\",\r\n \"type\": \"basic\",\r\n \"password\": \"pass\"\r\n },\r\n \"gatewayEnvironments\": \"Production and Sandbox\",\r\n \"sequences\": [{\"name\":\"json_validator\",\"type\": \"in\"},{\"name\":\"log_out_message\",\"type\": \"out\"}],\r\n \"subscriptionAvailability\": null,\r\n \"subscriptionAvailableTenants\": [],\r\n \"businessInformation\": {\r\n \"businessOwnerEmail\": \"marketing@pizzashack.com\",\r\n \"technicalOwnerEmail\": \"architecture@pizzashack.com\",\r\n \"technicalOwner\": \"John Doe\",\r\n \"businessOwner\": \"Jane Roe\"\r\n },\r\n \"corsConfiguration\": {\r\n \"accessControlAllowOrigins\": [\"*\"],\r\n \"accessControlAllowHeaders\": [\r\n \"authorization\",\r\n \"Access-Control-Allow-Origin\",\r\n \"Content-Type\",\r\n \"SOAPAction\"\r\n ],\r\n \"accessControlAllowMethods\": [\r\n \"GET\",\r\n \"PUT\",\r\n \"POST\",\r\n \"DELETE\",\r\n \"PATCH\",\r\n \"OPTIONS\"\r\n ],\r\n \"accessControlAllowCredentials\": false,\r\n \"corsConfigurationEnabled\": false\r\n }\r\n}" - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\r\n \"id\": \"7a2298c4-c905-403f-8fac-38c73301631f\",\r\n \"name\": \"PizzaShackAPI\",\r\n \"description\": \"This document describe a RESTFul API for Pizza Shack online pizza delivery store.\\r\\n\",\r\n \"context\": \"/pizzashack\",\r\n \"version\": \"1.0.0\",\r\n \"provider\": \"admin\",\r\n \"apiDefinition\": \"{\\\"paths\\\":{\\\"/order\\\":{\\\"post\\\":{\\\"x-auth-type\\\":\\\"Application & Application User\\\",\\\"x-throttling-tier\\\":\\\"Unlimited\\\",\\\"description\\\":\\\"Create a new Order\\\",\\\"parameters\\\":[{\\\"schema\\\":{\\\"$ref\\\":\\\"#/definitions/Order\\\"},\\\"description\\\":\\\"Order object that needs to be added\\\",\\\"name\\\":\\\"body\\\",\\\"required\\\":true,\\\"in\\\":\\\"body\\\"}],\\\"responses\\\":{\\\"201\\\":{\\\"headers\\\":{\\\"Location\\\":{\\\"description\\\":\\\"The URL of the newly created resource.\\\",\\\"type\\\":\\\"string\\\"}},\\\"schema\\\":{\\\"$ref\\\":\\\"#/definitions/Order\\\"},\\\"description\\\":\\\"Created.\\\"}}}},\\\"/menu\\\":{\\\"get\\\":{\\\"x-auth-type\\\":\\\"Application & Application User\\\",\\\"x-throttling-tier\\\":\\\"Unlimited\\\",\\\"description\\\":\\\"Return a list of available menu items\\\",\\\"parameters\\\":[],\\\"responses\\\":{\\\"200\\\":{\\\"headers\\\":{},\\\"schema\\\":{\\\"title\\\":\\\"Menu\\\",\\\"properties\\\":{\\\"list\\\":{\\\"items\\\":{\\\"$ref\\\":\\\"#/definitions/MenuItem\\\"},\\\"type\\\":\\\"array\\\"}},\\\"type\\\":\\\"object\\\"},\\\"description\\\":\\\"OK.\\\"}}}}},\\\"schemes\\\":[\\\"https\\\"],\\\"produces\\\":[\\\"application/json\\\"],\\\"swagger\\\":\\\"2.0\\\",\\\"definitions\\\":{\\\"MenuItem\\\":{\\\"title\\\":\\\"Pizza menu Item\\\",\\\"properties\\\":{\\\"price\\\":{\\\"type\\\":\\\"string\\\"},\\\"description\\\":{\\\"type\\\":\\\"string\\\"},\\\"name\\\":{\\\"type\\\":\\\"string\\\"},\\\"image\\\":{\\\"type\\\":\\\"string\\\"}},\\\"required\\\":[\\\"name\\\"]},\\\"Order\\\":{\\\"title\\\":\\\"Pizza Order\\\",\\\"properties\\\":{\\\"customerName\\\":{\\\"type\\\":\\\"string\\\"},\\\"delivered\\\":{\\\"type\\\":\\\"boolean\\\"},\\\"address\\\":{\\\"type\\\":\\\"string\\\"},\\\"pizzaType\\\":{\\\"type\\\":\\\"string\\\"},\\\"creditCardNumber\\\":{\\\"type\\\":\\\"string\\\"},\\\"quantity\\\":{\\\"type\\\":\\\"number\\\"},\\\"orderId\\\":{\\\"type\\\":\\\"string\\\"}},\\\"required\\\":[\\\"orderId\\\"]}},\\\"consumes\\\":[\\\"application/json\\\"],\\\"info\\\":{\\\"title\\\":\\\"PizzaShackAPI\\\",\\\"description\\\":\\\"This document describe a RESTFul API for Pizza Shack online pizza delivery store.\\\\n\\\",\\\"license\\\":{\\\"name\\\":\\\"Apache 2.0\\\",\\\"url\\\":\\\"http://www.apache.org/licenses/LICENSE-2.0.html\\\"},\\\"contact\\\":{\\\"email\\\":\\\"architecture@pizzashack.com\\\",\\\"name\\\":\\\"John Doe\\\",\\\"url\\\":\\\"http://www.pizzashack.com\\\"},\\\"version\\\":\\\"1.0.0\\\"}}\",\r\n \"wsdlUri\": null,\r\n \"status\": \"CREATED\",\r\n \"responseCaching\": \"Disabled\",\r\n \"cacheTimeout\": 300,\r\n \"destinationStatsEnabled\": null,\r\n \"isDefaultVersion\": false,\r\n \"type\": \"HTTP\",\r\n \"transport\": [\"https\"],\r\n \"tags\": [\r\n \"chicken\",\r\n \"pizza\"\r\n ],\r\n \"tiers\": [\"Unlimited\"],\r\n \"maxTps\": {\r\n \"sandbox\": 500,\r\n \"production\": 100\r\n },\r\n \"thumbnailUri\": null,\r\n \"visibility\": \"PUBLIC\",\r\n \"visibleRoles\": [],\\r\n \"endpointConfig\": \"{\\\"production_endpoints\\\":{\\\"url\\\":\\\"https://localhost:9443/am/sample/pizzashack/v1/api/\\\",\\\"config\\\":null},\\\"sandbox_endpoints\\\":{\\\"url\\\":\\\"https://localhost:9443/am/sample/pizzashack/v1/api/\\\",\\\"config\\\":null},\\\"endpoint_type\\\":\\\"http\\\"}\",\r\n \"endpointSecurity\": {\r\n \"username\": \"user\",\r\n \"type\": \"basic\",\r\n \"password\": \"pass\"\r\n },\r\n \"gatewayEnvironments\": \"Production and Sandbox\",\r\n \"sequences\": [{\"name\":\"json_validator\",\"type\":\"in\",\"id\":\"142ece76-b208-4aab-b29a-f382045ed066\",\"shared\":false},{\"name\":\"log_out_message\",\"type\":\"out\",\"id\":\"b3527be8-95e6-41e0-8097-3276987b7d4b\",\"shared\":false}],\r\n \"subscriptionAvailability\": null,\r\n \"subscriptionAvailableTenants\": [],\r\n \"businessInformation\": {\r\n \"businessOwnerEmail\": \"marketing@pizzashack.com\",\r\n \"technicalOwnerEmail\": \"architecture@pizzashack.com\",\r\n \"technicalOwner\": \"John Doe\",\r\n \"businessOwner\": \"Jane Roe\"\r\n },\r\n \"corsConfiguration\": {\r\n \"accessControlAllowOrigins\": [\"*\"],\r\n \"accessControlAllowHeaders\": [\r\n \"authorization\",\r\n \"Access-Control-Allow-Origin\",\r\n \"Content-Type\",\r\n \"SOAPAction\"\r\n ],\r\n \"accessControlAllowMethods\": [\r\n \"GET\",\r\n \"PUT\",\r\n \"POST\",\r\n \"DELETE\",\r\n \"PATCH\",\r\n \"OPTIONS\"\r\n ],\r\n \"accessControlAllowCredentials\": false,\r\n \"corsConfigurationEnabled\": false\r\n }\r\n}" - summary: Update an API - description: | - This operation can be used to update an existing API. - But the properties `name`, `version`, `context`, `provider`, `state` will not be changed by this operation. - parameters: - - $ref: '#/parameters/apiId' - - in: body - name: body - description: | - API object that needs to be added - required: true - schema: - $ref: '#/definitions/API' - - $ref: '#/parameters/Content-Type' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - tags: - - API (Individual) - responses: - 200: - description: | - OK. - Successful response with updated API object - schema: - $ref: '#/definitions/API' - headers: - Location: - description: | - The URL of the newly created resource. - type: string - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 400: - description: | - Bad Request. - Invalid request or validation error - schema: - $ref: '#/definitions/Error' - 403: - description: | - Forbidden. - The request must be conditional but no condition has been specified. - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - The resource to be updated does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - -#----------------------------------------------------- -# Delete the definition of an API -#----------------------------------------------------- - delete: - x-scope: apim:api_create - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -X DELETE https://localhost:9443/api/am/publisher/v0.12/apis/6fb74674-4ab8-4b52-9886-f9a376985060" - x-wso2-request: | - DELETE https://localhost:9443/api/am/publisher/v0.12/apis/6fb74674-4ab8-4b52-9886-f9a376985060 - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK" - summary: Delete an API - description: | - This operation can be used to delete an existing API proving the Id of the API. - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - tags: - - API (Individual) - responses: - 200: - description: | - OK. - Resource successfully deleted. - 403: - description: | - Forbidden. - The request must be conditional but no condition has been specified. - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - Resource to be deleted does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - -################################################################ -# The swagger resource of "Individual API" resource APIs -################################################################ - - /apis/{apiId}/swagger: -#----------------------------------------------------- -# Retrieve the API swagger definition -#----------------------------------------------------- - get: - x-scope: apim:api_view - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" https://localhost:9443/api/am/publisher/v0.12/apis/890a4f4d-09eb-4877-a323-57f6ce2ed79b/swagger" - x-wso2-request: | - GET https://localhost:9443/api/am/publisher/v0.12/apis/890a4f4d-09eb-4877-a323-57f6ce2ed79b/swagger - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\nContent-Length: 329\n\n{\n \"paths\": {\"/*\": {\"get\": {\n \"x-auth-type\": \"Application\",\n \"x-throttling-tier\": \"Unlimited\",\n \"responses\": {\"200\": {\"description\": \"OK\"}}\n }}},\n \"x-wso2-security\": {\"apim\": {\"x-wso2-scopes\": []}},\n \"swagger\": \"2.0\",\n \"info\": {\n \"title\": \"PhoneVerification\",\n \"description\": \"Verify a phone number\",\n \"contact\": {\n \"email\": \"xx@ee.com\",\n \"name\": \"xx\"\n },\n \"version\": \"1.0.0\"\n }\n}" - summary: Get swagger definition - description: | - This operation can be used to retrieve the swagger definition of an API. - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - - $ref: '#/parameters/If-Modified-Since' - tags: - - API (Individual) - responses: - 200: - description: | - OK. - Requested swagger document of the API is returned - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 404: - description: | - Not Found. - Requested API does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -#----------------------------------------------------- -# Update the API swagger definition -#----------------------------------------------------- - put: - consumes: - - multipart/form-data - x-scope: apim:api_create - x-wso2-curl: "curl -k -H \"Authorization:Bearer 5311eca3-8ac8-354e-ab36-7e2fdd6a4013\" -F apiDefinition=\"{\\\"paths\\\":{\\\"\\/*\\\":{\\\"get\\\":{\\\"x-auth-type\\\":\\\"Application\\\",\\\"x-throttling-tier\\\":\\\"Unlimited\\\",\\\"responses\\\":{\\\"200\\\":{\\\"description\\\":\\\"OK\\\"}}}}},\\\"x-wso2-security\\\":{\\\"apim\\\":{\\\"x-wso2-scopes\\\":[]}},\\\"swagger\\\":\\\"2.0\\\",\\\"info\\\":{\\\"title\\\":\\\"PhoneVerification\\\",\\\"description\\\":\\\"Verify a phone number\\\",\\\"contact\\\":{\\\"email\\\":\\\"xx@ee.com\\\",\\\"name\\\":\\\"xx\\\"},\\\"version\\\":\\\"1.0.0\\\"}}\" -X PUT \"https://localhost:9443/api/am/publisher/v0.12/apis/8848faaa-7fd1-478a-baa2-48a4ebb92c98/swagger\"" - x-wso2-request: | - PUT https://localhost:9443/api/am/publisher/v0.12/apis/8848faaa-7fd1-478a-baa2-48a4ebb92c98/swagger - Authorization:Bearer 5311eca3-8ac8-354e-ab36-7e2fdd6a4013 - Content-Length: 477 - Content-Type: multipart/form-data; boundary=------------------------4f51e636c0003d99 - - --------------------------4f51e636c0003d99 - Content-Disposition: form-data; name="apiDefinition" - - {"paths":{"\/*":{"get":{"x-auth-type":"Application","x-throttling-tier":"Unlimited","responses":{"200":{"description":"OK"}}}}},"x-wso2-security":{"apim":{"x-wso2-scopes":[]}},"swagger":"2.0","info":{"title":"PhoneVerification","description":"Verify a phone number","contact":{"email":"xx@ee.com","name":"xx"},"version":"1.0.0"}} - --------------------------4f51e636c0003d99-- - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"paths\": {\"/*\": {\"get\": {\n \"x-auth-type\": \"Application\",\n \"x-throttling-tier\": \"Unlimited\",\n \"responses\": {\"200\": {\"description\": \"OK\"}}\n }}},\n \"x-wso2-security\": {\"apim\": {\"x-wso2-scopes\": []}},\n \"swagger\": \"2.0\",\n \"info\": {\n \"title\": \"PhoneVerification\",\n \"description\": \"Verify a phone number\",\n \"contact\": {\n \"email\": \"xx@ee.com\",\n \"name\": \"xx\"\n },\n \"version\": \"1.0.0\"\n }\n}" - summary: Update swagger definition - description: | - This operation can be used to update the swagger definition of an existing API. Swagger definition to be updated is passed as a form data parameter `apiDefinition`. - parameters: - - $ref: '#/parameters/apiId' - - in: formData - name: apiDefinition - description: Swagger definition of the API - type: string - required: true - - $ref: '#/parameters/Content-Type' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - tags: - - API (Individual) - responses: - 200: - description: | - OK. - Successful response with updated Swagger definition - headers: - Location: - description: | - The URL of the newly created resource. - type: string - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 400: - description: | - Bad Request. - Invalid request or validation error - schema: - $ref: '#/definitions/Error' - 403: - description: | - Forbidden. - The request must be conditional but no condition has been specified. - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - The resource to be updated does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - -################################################################ -# The thumbnail resource of "Individual API" resource APIs -################################################################ - - /apis/{apiId}/thumbnail: -#------------------------------------------------------------------------------------------------- -# Downloads a thumbnail image of an API -#------------------------------------------------------------------------------------------------- - get: - x-scope: apim:api_view - x-wso2-curl: "curl -k -H \"Authorization: Bearer d34baf74-3f02-3929-814e-88b27f750ba9\" https://localhost:9443/api/am/publisher/v0.12/apis/29c9ec3d-f590-467e-83e6-96d43517080f/thumbnail > image.jpg" - x-wso2-request: | - GET https://localhost:9443/api/am/publisher/v0.12/apis/29c9ec3d-f590-467e-83e6-96d43517080f/thumbnail - Authorization: Bearer d34baf74-3f02-3929-814e-88b27f750ba9 - x-wso2-response: "HTTP/1.1 200 OK\r\nContent-Type: image/jpeg\r\n\r\n[image content]" - summary: Get thumbnail image - description: | - This operation can be used to download a thumbnail image of an API. - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - - $ref: '#/parameters/If-Modified-Since' - tags: - - API (Individual) - responses: - 200: - description: | - OK. - Thumbnail image returned - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 404: - description: | - Not Found. - Requested Document does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -#---------------------------------------------------------------------------- -# Upload a thumbnail image to a certain API -#---------------------------------------------------------------------------- - post: - consumes: - - multipart/form-data - x-scope: apim:api_create - x-wso2-curl: "curl -X POST -H \"Authorization: Bearer d34baf74-3f02-3929-814e-88b27f750ba9\" https://localhost:9443/api/am/publisher/v0.12/apis/29c9ec3d-f590-467e-83e6-96d43517080f/thumbnail -F file=@image.jpg" - x-wso2-request: | - POST https://localhost:9443/api/am/publisher/v0.12/apis/8848faaa-7fd1-478a-baa2-48a4ebb92c98/thumbnail - Authorization: Bearer d34baf74-3f02-3929-814e-88b27f750ba9 - Content-Type: multipart/form-data; boundary=------------------------5e542e0e5b50e1e4 - Content-Length: 18333 - - --------------------------5e542e0e5b50e1e4 - Content-Disposition: form-data; name="file"; filename="image.jpg" - Content-Type: image/jpeg - - [image content] - - --------------------------5e542e0e5b50e1e4-- - x-wso2-response: "HTTP/1.1 201 Created\r\nLocation: https://localhost:9443/api/am/publisher/v0.12/apis/8848faaa-7fd1-478a-baa2-48a4ebb92c98/thumbnail\r\nContent-Type: application/json\r\n\r\n{\r\n \"relativePath\": \"/apis/8848faaa-7fd1-478a-baa2-48a4ebb92c98/thumbnail\",\r\n \"mediaType\": \"image/jpeg\"\r\n}" - summary: Upload a thumbnail image - description: | - This operation can be used to upload a thumbnail image of an API. The thumbnail to be uploaded should be given as a form data parameter `file`. - parameters: - - $ref: '#/parameters/apiId' - - in: formData - name: file - description: Image to upload - type: file - required: true - - $ref: '#/parameters/Content-Type' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - tags: - - API (Individual) - responses: - 200: - description: | - OK. - Image updated - schema: - $ref : '#/definitions/FileInfo' - headers: - Location: - description: | - The URL of the uploaded thumbnail image of the API. - type: string - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 400: - description: | - Bad Request. - Invalid request or validation error. - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - The resource to be updated does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Copy API" Processing Function resource API -###################################################### - /apis/copy-api: - -#----------------------------------------------------- -# Create a new API based on an already existing one -#----------------------------------------------------- - post: - x-scope: apim:api_create - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -X POST \"https://localhost:9443/api/am/publisher/v0.12/apis/copy-api?apiId=890a4f4d-09eb-4877-a323-57f6ce2ed79b&newVersion=2.0.0\"" - x-wso2-request: | - POST https://localhost:9443/api/am/publisher/v0.12/apis/copy-api?apiId=890a4f4d-09eb-4877-a323-57f6ce2ed79b&newVersion=2.0.0 - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 201 Created\nLocation: https://localhost:9443/api/am/publisher/v0.12/apis/25a84fc9-38c0-4578-95e8-29fb6b1c4771\nContent-Type: application/json\n\n{\r\n \"id\": \"25a84fc9-38c0-4578-95e8-29fb6b1c4771\",\r\n \"name\": \"PizzaShackAPI\",\r\n \"description\": \"This document describe a RESTFul API for Pizza Shack online pizza delivery store.\\r\\n\",\r\n \"context\": \"/pizzashack\",\r\n \"version\": \"2.0.0\",\r\n \"provider\": \"admin\",\r\n \"apiDefinition\": \"{\\\"paths\\\":{\\\"\\\\/order\\\":{\\\"post\\\":{\\\"x-auth-type\\\":\\\"Application & Application User\\\",\\\"x-throttling-tier\\\":\\\"Unlimited\\\",\\\"description\\\":\\\"Create a new Order\\\",\\\"parameters\\\":[{\\\"schema\\\":{\\\"$ref\\\":\\\"#\\\\/definitions\\\\/Order\\\"},\\\"description\\\":\\\"Order object that needs to be added\\\",\\\"name\\\":\\\"body\\\",\\\"required\\\":true,\\\"in\\\":\\\"body\\\"}],\\\"responses\\\":{\\\"201\\\":{\\\"schema\\\":{\\\"$ref\\\":\\\"#\\\\/definitions\\\\/Order\\\"},\\\"headers\\\":{\\\"Location\\\":{\\\"description\\\":\\\"The URL of the newly created resource.\\\",\\\"type\\\":\\\"string\\\"}},\\\"description\\\":\\\"Created.\\\"}}}},\\\"\\\\/menu\\\":{\\\"get\\\":{\\\"x-auth-type\\\":\\\"Application & Application User\\\",\\\"x-throttling-tier\\\":\\\"Unlimited\\\",\\\"description\\\":\\\"Return a list of available menu items\\\",\\\"parameters\\\":[],\\\"responses\\\":{\\\"200\\\":{\\\"schema\\\":{\\\"title\\\":\\\"Menu\\\",\\\"properties\\\":{\\\"list\\\":{\\\"items\\\":{\\\"$ref\\\":\\\"#\\\\/definitions\\\\/MenuItem\\\"},\\\"type\\\":\\\"array\\\"}},\\\"type\\\":\\\"object\\\"},\\\"headers\\\":{},\\\"description\\\":\\\"OK.\\\"}}}}},\\\"schemes\\\":[\\\"https\\\"],\\\"produces\\\":[\\\"application\\\\/json\\\"],\\\"swagger\\\":\\\"2.0\\\",\\\"definitions\\\":{\\\"MenuItem\\\":{\\\"title\\\":\\\"Pizza menu Item\\\",\\\"properties\\\":{\\\"price\\\":{\\\"type\\\":\\\"string\\\"},\\\"description\\\":{\\\"type\\\":\\\"string\\\"},\\\"name\\\":{\\\"type\\\":\\\"string\\\"},\\\"image\\\":{\\\"type\\\":\\\"string\\\"}},\\\"required\\\":[\\\"name\\\"]},\\\"Order\\\":{\\\"title\\\":\\\"Pizza Order\\\",\\\"properties\\\":{\\\"customerName\\\":{\\\"type\\\":\\\"string\\\"},\\\"delivered\\\":{\\\"type\\\":\\\"boolean\\\"},\\\"pizzaType\\\":{\\\"type\\\":\\\"string\\\"},\\\"address\\\":{\\\"type\\\":\\\"string\\\"},\\\"creditCardNumber\\\":{\\\"type\\\":\\\"string\\\"},\\\"quantity\\\":{\\\"type\\\":\\\"number\\\"},\\\"orderId\\\":{\\\"type\\\":\\\"string\\\"}},\\\"required\\\":[\\\"orderId\\\"]}},\\\"consumes\\\":[\\\"application\\\\/json\\\"],\\\"info\\\":{\\\"title\\\":\\\"PizzaShackAPI\\\",\\\"description\\\":\\\"This document describe a RESTFul API for Pizza Shack online pizza delivery store.\\\\n\\\",\\\"license\\\":{\\\"name\\\":\\\"Apache 2.0\\\",\\\"url\\\":\\\"http:\\\\/\\\\/www.apache.org\\\\/licenses\\\\/LICENSE-2.0.html\\\"},\\\"contact\\\":{\\\"email\\\":\\\"architecture@pizzashack.com\\\",\\\"name\\\":\\\"John Doe\\\",\\\"url\\\":\\\"http:\\\\/\\\\/www.pizzashack.com\\\"},\\\"version\\\":\\\"2.0.0\\\"}}\",\r\n \"wsdlUri\": null,\r\n \"status\": \"CREATED\",\r\n \"responseCaching\": \"Disabled\",\r\n \"cacheTimeout\": 300,\r\n \"destinationStatsEnabled\": null,\r\n \"isDefaultVersion\": false,\r\n \"type\": \"HTTP\",\r\n \"transport\": [\"https\"],\r\n \"tags\": [\r\n \"chicken\",\r\n \"pizza\"\r\n ],\r\n \"tiers\": [\"Unlimited\"],\r\n \"maxTps\": {\r\n \"sandbox\": 500,\r\n \"production\": 100\r\n },\r\n \"thumbnailUri\": null,\r\n \"visibility\": \"PUBLIC\",\r\n \"visibleRoles\": [],\\r\n \"endpointConfig\": \"{\\\"production_endpoints\\\":{\\\"url\\\":\\\"https://localhost:9443/am/sample/pizzashack/v1/api/\\\",\\\"config\\\":null},\\\"sandbox_endpoints\\\":{\\\"url\\\":\\\"https://localhost:9443/am/sample/pizzashack/v1/api/\\\",\\\"config\\\":null},\\\"endpoint_type\\\":\\\"http\\\"}\",\r\n \"endpointSecurity\": {\r\n \"username\": \"user\",\r\n \"type\": \"basic\",\r\n \"password\": \"pass\"\r\n },\r\n \"gatewayEnvironments\": \"Production and Sandbox\",\r\n \"sequences\": [],\r\n \"subscriptionAvailability\": null,\r\n \"subscriptionAvailableTenants\": [],\r\n \"businessInformation\": {\r\n \"businessOwnerEmail\": \"marketing@pizzashack.com\",\r\n \"technicalOwnerEmail\": \"architecture@pizzashack.com\",\r\n \"technicalOwner\": \"John Doe\",\r\n \"businessOwner\": \"Jane Roe\"\r\n },\r\n \"corsConfiguration\": {\r\n \"accessControlAllowOrigins\": [\"*\"],\r\n \"accessControlAllowHeaders\": [\r\n \"authorization\",\r\n \"Access-Control-Allow-Origin\",\r\n \"Content-Type\",\r\n \"SOAPAction\"\r\n ],\r\n \"accessControlAllowMethods\": [\r\n \"GET\",\r\n \"PUT\",\r\n \"POST\",\r\n \"DELETE\",\r\n \"PATCH\",\r\n \"OPTIONS\"\r\n ],\r\n \"accessControlAllowCredentials\": false,\r\n \"corsConfigurationEnabled\": false\r\n }\r\n}" - summary: Create a new API version - description: | - This operation can be used to create a new version of an existing API. The new version is specified as `newVersion` query parameter. New API will be in `CREATED` state. - parameters: - - name: newVersion - description: Version of the new API. - type: string - in: query - required: true - - $ref: '#/parameters/apiId-Q' - tags: - - API (Individual) - responses: - 201: - description: | - Created. - Successful response with the newly created API as entity in the body. Location header contains URL of newly created API. - headers: - Location: - description: | - The URL of the newly created API. - type: string - 400: - description: | - Bad Request. - Invalid request or validation error - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - API to copy does not exist. - 401: - description: | - Unauthenticated request. - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Change Lifecycle" Processing Function resource API -###################################################### - /apis/change-lifecycle: - -#----------------------------------------------------- -# Change the lifecycle of an API -#----------------------------------------------------- - post: - x-scope: apim:api_publish - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -X POST \"https://localhost:9443/api/am/publisher/v0.12/apis/change-lifecycle?apiId=890a4f4d-09eb-4877-a323-57f6ce2ed79b&action=Publish\"" - x-wso2-request: | - POST https://localhost:9443/api/am/publisher/v0.12/apis/change-lifecycle?apiId=890a4f4d-09eb-4877-a323-57f6ce2ed79b&action=Publish - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK" - summary: Change API Status - description: | - This operation is used to change the lifecycle of an API. Eg: Publish an API which is in `CREATED` state. In order to change the lifecycle, we need to provide the lifecycle `action` as a query parameter. - - For example, to Publish an API, `action` should be `Publish`. Note that the `Re-publish` action is available only after calling `Block`. - - Some actions supports providing additional paramters which should be provided as `lifecycleChecklist` parameter. Please see parameters table for more information. - parameters: - - name: action - description: | - The action to demote or promote the state of the API. - - Supported actions are [ **Publish, Deploy as a Prototype, Demote to Created, Demote to Prototyped, Block, Deprecate, Re-Publish, Retire **] - - in: query - type: string - required: true - enum: - - Publish - - Deploy as a Prototype - - Demote to Created - - Demote to Prototyped - - Block - - Deprecate - - Re-Publish - - Retire - - name: lifecycleChecklist - description: | - - Supported checklist items are as follows. - 1. **Deprecate Old Versions**: Setting this to true will deprecate older versions of a particular API when it is promoted to Published state from Created state. - 2. **Require Re-Subscription**: If you set this to true, users need to re subscribe to the API although they may have subscribed to an older version. - - You can specify additional checklist items by using an **"attribute:"** modifier. - - Eg: "Deprecate Old Versions:true" will deprecate older versions of a particular API when it is promoted to Published state from Created state. Multiple checklist items can be given in "attribute1:true, attribute2:false" format. - - **Sample CURL :** curl -k -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" -X POST "https://localhost:9443/api/am/publisher/v0.12/apis/change-lifecycle?apiId=890a4f4d-09eb-4877-a323-57f6ce2ed79b&action=Publish&lifecycleChecklist=Deprecate Old Versions:true,Require Re-Subscription:true" - - type: string - in: query - - $ref: '#/parameters/apiId-Q' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - tags: - - API (Individual) - responses: - 200: - description: | - OK. - Lifecycle changed successfully. - headers: - ETag: - description: | - Entity Tag of the changed API. Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the API lifecycle has been modified the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 400: - description: | - Bad Request. - Invalid request or validation error - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - Requested API does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Document Collection" resource APIs -###################################################### - /apis/{apiId}/documents: - -#----------------------------------------------------- -# Retrieve the documents associated with an API that qualify under a search condition -#----------------------------------------------------- - get: - x-scope: apim:api_view - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" \"https://localhost:9443/api/am/publisher/v0.12/apis/890a4f4d-09eb-4877-a323-57f6ce2ed79b/documents\"" - x-wso2-request: | - GET https://localhost:9443/api/am/publisher/v0.12/apis/890a4f4d-09eb-4877-a323-57f6ce2ed79b/documents - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"previous\": \"\",\n \"list\": [\n {\n \"visibility\": \"API_LEVEL\",\n \"sourceType\": \"INLINE\",\n \"sourceUrl\": null,\n \"otherTypeName\": null,\n \"documentId\": \"0bcb7f05-599d-4e1a-adce-5cb89bfe58d5\",\n \"summary\": \"This is a sample documentation for v1.0.0\",\n \"name\": \"PhoneVerification API Documentation\",\n \"type\": \"HOWTO\"\n },\n {\n \"visibility\": \"API_LEVEL\",\n \"sourceType\": \"URL\",\n \"sourceUrl\": \"http://wiki.cdyne.com/index.php/Phone_Verification\",\n \"otherTypeName\": null,\n \"documentId\": \"4145df31-04f1-440c-8d08-68952874622c\",\n \"summary\": \"This is the URL for online documentation\",\n \"name\": \"Online Documentation\",\n \"type\": \"SAMPLES\"\n }\n ],\n \"next\": \"\",\n \"count\": 2\n}" - summary: Get a list of documents of an API - description: | - This operation can be used to retrive a list of documents belonging to an API by providing the id of the API. - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/limit' - - $ref: '#/parameters/offset' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - tags: - - Document (Collection) - responses: - 200: - description: | - OK. - Document list is returned. - schema: - $ref: '#/definitions/DocumentList' - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 404: - description: | - Not Found. - Requested API does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -#----------------------------------------------------- -# Add a document to a certain API -#----------------------------------------------------- - post: - x-scope: apim:api_create - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -H \"Content-Type: application/json\" -X POST -d @data.json \"https://localhost:9443/api/am/publisher/v0.12/apis/96077508-fd01-4fae-bc64-5de0e2baf43c/documents\"" - x-wso2-request: "POST https://localhost:9443/api/am/publisher/v0.12/apis/96077508-fd01-4fae-bc64-5de0e2baf43c/documents\nAuthorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\nContent-Type: application/json\n\n{\n \"visibility\": \"API_LEVEL\",\n \"sourceType\": \"INLINE\",\n \"sourceUrl\": null,\n \"otherTypeName\": null,\n \"summary\": \"This is a sample documentation\",\n \"name\": \"Introduction to PhoneVerification API\",\n \"type\": \"HOWTO\"\n}" - x-wso2-response: "HTTP/1.1 201 Created\nLocation: https://localhost:9443/api/am/publisher/v0.12/apis/890a4f4d-09eb-4877-a323-57f6ce2ed79b/documents/ffd5790d-b7a9-4cb6-b76a-f8b83ecdd058\nContent-Type: application/json\n\n{\n \"visibility\": \"API_LEVEL\",\n \"sourceType\": \"INLINE\",\n \"sourceUrl\": null,\n \"otherTypeName\": null,\n \"documentId\": \"ffd5790d-b7a9-4cb6-b76a-f8b83ecdd058\",\n \"summary\": \"This is a sample documentation\",\n \"name\": \"Introduction to PhoneVerification API\",\n \"type\": \"HOWTO\"\n}" - summary: Add a new document to an API - description: | - This operation can be used to add a new documentation to an API. This operation only adds the metadata of a document. To add the actual content we need to use **Upload the content of an API document ** API once we obtain a document Id by this operation. - parameters: - - $ref: '#/parameters/apiId' - - in: body - name: body - description: | - Document object that needs to be added - required: true - schema: - $ref: '#/definitions/Document' - - $ref: '#/parameters/Content-Type' - tags: - - Document (Collection) - responses: - 201: - description: | - Created. - Successful response with the newly created Document object as entity in the body. - Location header contains URL of newly added document. - schema: - $ref: '#/definitions/Document' - headers: - Location: - description: | - Location to the newly created Document. - type: string - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 400: - description: | - Bad Request. - Invalid request or validation error - schema: - $ref: '#/definitions/Error' - 415: - description: | - Unsupported media type. - The entity of the request was in a not supported format. - -###################################################### -# The "Individual Document" resource APIs -###################################################### - '/apis/{apiId}/documents/{documentId}': - -#----------------------------------------------------- -# Retrieve a particular document of a certain API -#----------------------------------------------------- - get: - x-scope: apim:api_view - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" \"https://localhost:9443/api/am/publisher/v0.12/apis/890a4f4d-09eb-4877-a323-57f6ce2ed79b/documents/0bcb7f05-599d-4e1a-adce-5cb89bfe58d5\"" - x-wso2-request: | - GET https://localhost:9443/api/am/publisher/v0.12/apis/890a4f4d-09eb-4877-a323-57f6ce2ed79b/documents/0bcb7f05-599d-4e1a-adce-5cb89bfe58d5 - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"visibility\": \"API_LEVEL\",\n \"sourceType\": \"INLINE\",\n \"sourceUrl\": null,\n \"otherTypeName\": null,\n \"documentId\": \"0bcb7f05-599d-4e1a-adce-5cb89bfe58d5\",\n \"summary\": \"This is a sample documentation\",\n \"name\": \"PhoneVerification API Documentation\",\n \"type\": \"HOWTO\"\n}" - summary: Get a document of an API - description: | - This operation can be used to retrieve a particular document's metadata associated with an API. - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/documentId' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - - $ref: '#/parameters/If-Modified-Since' - tags: - - Document (Individual) - responses: - 200: - description: | - OK. - Document returned. - schema: - $ref: '#/definitions/Document' - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 404: - description: | - Not Found. - Requested Document does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -#----------------------------------------------------- -# Update a particular document of a certain API -#----------------------------------------------------- - put: - x-scope: apim:api_create - x-wso2-curl: "curl -k -H \"Authorization:Bearer b0982cd2aacd463ff5f63cd5ebe58f4a\" -H \"Content-Type: application/json\" -X PUT -d data.json \"https://localhost:9443/api/am/publisher/v0.12/apis/96077508-fd01-4fae-bc64-5de0e2baf43c/documents/0bcb7f05-599d-4e1a-adce-5cb89bfe58d5\"" - x-wso2-request: "PUT https://localhost:9443/api/am/publisher/v0.12/apis/96077508-fd01-4fae-bc64-5de0e2baf43c/documents/0bcb7f05-599d-4e1a-adce-5cb89bfe58d5\nAuthorization:Bearer b0982cd2aacd463ff5f63cd5ebe58f4a\nContent-Type: application/json\n\n{\n \"visibility\": \"API_LEVEL\",\n \"sourceType\": \"INLINE\",\n \"sourceUrl\": null,\n \"otherTypeName\": null,\n \"documentId\": \"0bcb7f05-599d-4e1a-adce-5cb89bfe58d5\",\n \"summary\": \"This is a sample documentation for v1.0.0\",\n \"name\": \"PhoneVerification API Documentation\",\n \"type\": \"HOWTO\"\n}" - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"visibility\": \"API_LEVEL\",\n \"sourceType\": \"INLINE\",\n \"sourceUrl\": null,\n \"otherTypeName\": null,\n \"documentId\": \"0bcb7f05-599d-4e1a-adce-5cb89bfe58d5\",\n \"summary\": \"This is a sample documentation for v1.0.0\",\n \"name\": \"PhoneVerification API Documentation\",\n \"type\": \"HOWTO\"\n}" - summary: Update a document of an API - description: | - This operation can be used to update metadata of an API's document. - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/documentId' - - in: body - name: body - description: | - Document object that needs to be added - required: true - schema: - $ref: '#/definitions/Document' - - $ref: '#/parameters/Content-Type' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - tags: - - Document (Individual) - responses: - 200: - description: | - OK. - Document updated - schema: - $ref: '#/definitions/Document' - headers: - Location: - description: | - The URL of the updated document. - type: string - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 400: - description: | - Bad Request. - Invalid request or validation error. - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - The resource to be updated does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - -#----------------------------------------------------- -# Delete a particular document of a certain API -#----------------------------------------------------- - delete: - x-scope: apim:api_create - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -X DELETE https://localhost:9443/api/am/publisher/v0.12/apis/890a4f4d-09eb-4877-a323-57f6ce2ed79b/documents/ffd5790d-b7a9-4cb6-b76a-f8b83ecdd058" - x-wso2-request: | - DELETE https://localhost:9443/api/am/publisher/v0.12/apis/890a4f4d-09eb-4877-a323-57f6ce2ed79b/documents/ffd5790d-b7a9-4cb6-b76a-f8b83ecdd058 - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK" - summary: Delete a document of an API - description: | - This operation can be used to delete a document associated with an API. - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/documentId' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - tags: - - Document (Individual) - responses: - 200: - description: | - OK. - Resource successfully deleted. - 404: - description: | - Not Found. - Resource to be deleted does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - -################################################################ -# The content resource of "Individual Document" resource APIs -################################################################ - - '/apis/{apiId}/documents/{documentId}/content': - - #------------------------------------------------------------------------------------------------- - # Downloads a FILE type document/get the inline content or source url of a certain document - #------------------------------------------------------------------------------------------------- - get: - x-scope: apim:api_view - x-wso2-curl: "curl -k -H \"Authorization:Bearer b0982cd2aacd463ff5f63cd5ebe58f4a\" \"https://localhost:9443/api/am/publisher/v0.12/apis/890a4f4d-09eb-4877-a323-57f6ce2ed79b/documents/daf732d3-bda2-46da-b381-2c39d901ea61/content\" > sample.pdf" - x-wso2-request: | - GET https://localhost:9443/api/am/publisher/v0.12/apis/890a4f4d-09eb-4877-a323-57f6ce2ed79b/documents/daf732d3-bda2-46da-b381-2c39d901ea61/content - Authorization:Bearer b0982cd2aacd463ff5f63cd5ebe58f4a - x-wso2-response: "HTTP/1.1 200 OK\nContent-Disposition: attachment; filename=\"sample.pdf\"\nContent-Type: application/octet-stream\nContent-Length: 7802\n\n%PDF-1.4\n%äüöß\n2 0 obj\n<>\nstream\n..\n>>\nstartxref\n7279\n%%EOF" - summary: Get the content of an API document - description: | - This operation can be used to retrive the content of an API's document. - - The document can be of 3 types. In each cases responses are different. - - 1. **Inline type**: - The content of the document will be retrieved in `text/plain` content type - - _Sample cURL_ : `curl -k -H "Authorization:Bearer 579f0af4-37be-35c7-81a4-f1f1e9ee7c51" -F inlineContent=@"docs.txt" -X POST "https://localhost:9443/api/am/publisher/v0.12/apis/995a4972-3178-4b17-a374-756e0e19127c/documents/43c2bcce-60e7-405f-bc36-e39c0c5e189e/content` - 2. **FILE type**: - The file will be downloaded with the related content type (eg. `application/pdf`) - 3. **URL type**: - The client will recieve the URL of the document as the Location header with the response with - `303 See Other` - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/documentId' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - - $ref: '#/parameters/If-Modified-Since' - tags: - - Document (Individual) - responses: - 200: - description: | - OK. - File or inline content returned. - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 303: - description: | - See Other. - Source can be retrived from the URL specified at the Location header. - headers: - Location: - description: | - The Source URL of the document. - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 404: - description: | - Not Found. - Requested Document does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - - #---------------------------------------------------------------------------- - # Upload a file or add inline content to a document of a certain API - #---------------------------------------------------------------------------- - post: - consumes: - - multipart/form-data - x-scope: apim:api_create - x-wso2-curl: "curl -k -H \"Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -F file=@\"sample.pdf\" -X POST \"https://localhost:9443/api/am/publisher/v0.12/apis/890a4f4d-09eb-4877-a323-57f6ce2ed79b/documents/daf732d3-bda2-46da-b381-2c39d901ea61/content\"" - x-wso2-request: | - POST https://localhost:9443/api/am/publisher/v0.12/apis/8848faaa-7fd1-478a-baa2-48a4ebb92c98/documents/b3a79270-02bb-4e39-9ac1-90ce8f6c84af/content - Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - Content-Length: 8004 - Content-Type: multipart/form-data; boundary=------------------------7b9a53f1ffa452b9 - - --------------------------7b9a53f1ffa452b9 - Content-Disposition: form-data; name="file"; filename="sample.pdf" - Content-Type: application/octet-stream - - [file content] - - --------------------------7b9a53f1ffa452b9-- - x-wso2-response: "HTTP/1.1 201 Created\nLocation: https://localhost:9443/api/am/publisher/v0.12/apis/8848faaa-7fd1-478a-baa2-48a4ebb92c98/documents/b3a79270-02bb-4e39-9ac1-90ce8f6c84af/content\nContent-Type: application/json\n\n{\n \"visibility\":\"API_LEVEL\",\n \"sourceType\":\"FILE\",\n \"sourceUrl\":null,\n \"otherTypeName\":null,\n \"documentId\":\"daf732d3-bda2-46da-b381-2c39d901ea61\",\n \"summary\":\"This is a sample documentation pdf\",\n \"name\":\"Introduction to PhoneVerification API PDF\",\n \"type\":\"HOWTO\"\n}" - summary: Upload the content of an API document - description: | - Thid operation can be used to upload a file or add inline content to an API document. - - **IMPORTANT:** - * Either **file** or **inlineContent** form data parameters should be specified at one time. - * Document's source type should be **FILE** in order to upload a file to the document using **file** parameter. - * Document's source type should be **INLINE** in order to add inline content to the document using **inlineContent** parameter. - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/documentId' - - in: formData - name: file - description: Document to upload - type: file - required: false - - in: formData - name: inlineContent - description: Inline content of the document - type: string - required: false - - $ref: '#/parameters/Content-Type' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - tags: - - Document (Individual) - responses: - 200: - description: | - OK. - Document updated - schema: - $ref: '#/definitions/Document' - headers: - Location: - description: | - The URL of the updated content of the document. - type: string - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 400: - description: | - Bad Request. - Invalid request or validation error. - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - The resource to be updated does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - - ##pp -###################################################### -# The "specific mediation policy" resource APIs -###################################################### - '/apis/{apiId}/policies/mediation': - - #----------------------------------------------------------------------------------------- - # Retrieving the list of all API specific mediation sequences under a given search condition - #----------------------------------------------------------------------------------------- - get: - x-scope: apim:api_view - x-wso2-curl: "curl -k -H \"Authorization: Bearer fb2a0784-f60c-3276-8fde-5b0f70e61ecc\" https://localhost:9443/api/am/publisher/v0.12/apis/40082986-6488-4b86-801a-b0b069d4588c/policies/mediation" - x-wso2-request: "GET https://localhost:9443/api/am/publisher/v0.12/apis/40082986-6488-4b86-801a-b0b069d4588c/policies/mediation\r\nAuthorization: Bearer fb2a0784-f60c-3276-8fde-5b0f70e61ecc" - x-wso2-response: "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\r\n \"count\": 1,\r\n \"next\": null,\r\n \"previous\": null,\r\n \"list\": [ {\r\n \"name\": \"add_custom_header_fault\",\r\n \"id\": \"6460d7e6-4272-4e3a-9879-437228d83123\",\r\n \"type\": \"fault\"\r\n }]\r\n}" - summary: | - Get all mediation policies of an API - description: | - This operation provides you a list of available mediation policies of an API. - parameters: - - $ref: '#/parameters/apiId' - - $ref : '#/parameters/limit' - - $ref : '#/parameters/offset' - - name : query - in: query - description: "-Not supported yet-" - type: string - - $ref : "#/parameters/Accept" - - $ref : "#/parameters/If-None-Match" - tags: - - Mediation Policy (Collection) - responses: - 200: - description: | - OK. - List of qualifying APIs is returned. - schema: - $ref: '#/definitions/mediationList' - headers: - Content-Type: - description: The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -#---------------------------------------------------------------------------- -# Upload an API specific mediation policy -#---------------------------------------------------------------------------- - post: - x-scope: apim:api_create - x-wso2-curl: "curl -k -H \"Authorization: Bearer 6cea3696-0151-3282-bf79-a0c4db6f308a\" -H \"Content-Type: application/json\" -X POST -d @data.json \"https://localhost:9443/api/am/publisher/v0.12/apis/40082986-6488-4b86-801a-b0b069d4588c/policies/mediation\"" - x-wso2-request: "POST https://localhost:9443/api/am/publisher/v0.12/apis/40082986-6488-4b86-801a-b0b069d4588c/policies/mediation\r\nContent-Type: application/json\r\nAuthorization: Bearer 6cea3696-0151-3282-bf79-a0c4db6f308a\r\n\r\n{\r\n \"name\": \"add_custom_header_fault\",\r\n \"type\": \"fault\",\r\n \"config\": \"\\n \\n<\\/sequence>\\n\"\r\n}" - x-wso2-response: "HTTP/1.1 201 Created\r\nLocation: https://localhost:9443/api/am/publisher/v0.12/registry/resource/_system/governance/apimgt/applicationdata/provider/admin/hello/1.0.0/fault/add_custom_header_fault.xml\r\nContent-Type: application/json\r\n\r\n{ \r\n \"id\":\"624b9f7d-bfaf-484b-94cc-e84491f5d725\",\r\n \"name\":\"add_custom_header_fault\",\r\n \"type\":\"fault\",\r\n \"config\":\"\\n \\n\\n\"\r\n}" - summary: Add an API specific mediation policy - description: | - This operation can be used to add an API specifc mediation policy. - parameters: - - in: body - name: body - description: mediation policy to upload - required: true - schema: - $ref: '#/definitions/Mediation' - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/Content-Type' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - tags: - - Mediation Policy (Collection) - responses: - 200: - description: | - OK. - mediation policy uploaded - schema: - $ref : '#/definitions/Mediation' - headers: - Location: - description: | - The URL of the uploaded thumbnail image of the API. - type: string - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 400: - description: | - Bad Request. - Invalid request or validation error. - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - The resource to be updated does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Individual API specific mediation sequence" resource -###################################################### - /apis/{apiId}/policies/mediation/{mediationPolicyId}: - -#----------------------------------------------------- -# Retrieve a particular API specific mediation squence -#----------------------------------------------------- - get: - x-scope: apim:api_view - x-wso2-curl: "curl -k -H \"Authorization: Bearer 5aa0acc0-0ce3-3a0b-8cc8-db5ef696ee23\" https://localhost:9443/api/am/publisher/v0.12/apis/40082986-6488-4b86-801a-b0b069d4588c/policies/mediation/624b9f7d-bfaf-484b-94cc-e84491f5d725" - x-wso2-request: "GET https://localhost:9443/api/am/publisher/v0.12/apis/40082986-6488-4b86-801a-b0b069d4588c/policies/mediation/624b9f7d-bfaf-484b-94cc-e84491f5d725\r\nAuthorization: Bearer 5aa0acc0-0ce3-3a0b-8cc8-db5ef696ee23" - x-wso2-response: "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\r\n \"id\": \"624b9f7d-bfaf-484b-94cc-e84491f5d725\",\r\n \"name\": \"add_custom_header_fault\",\r\n \"type\": \"fault\",\r\n \"config\": \"\\n \\n<\\/sequence>\\n\"\r\n}" - summary: Get an API specific mediation policy - description: | - This operation can be used to retrieve a particular API specific mediation policy. - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/mediationPolicyId' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - - $ref: '#/parameters/If-Modified-Since' - tags: - - Mediation Policy (Individual) - responses: - 200: - description: | - OK. - Mediation policy returned. - schema: - $ref: '#/definitions/Mediation' - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 404: - description: | - Not Found. - Requested Document does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -#----------------------------------------------------- -# Delete the mediation policy -#----------------------------------------------------- - delete: - x-scope: apim:api_create - x-wso2-curl: "curl -k -H \"Authorization: Bearer fb2a0784-f60c-3276-8fde-5b0f70e61ecc\" -X DELETE https://localhost:9443/api/am/publisher/v0.12/apis/40082986-6488-4b86-801a-b0b069d4588c/policies/mediation/60f5146d-1774-405d-86b3-9b040ac266d5" - x-wso2-request: "DELETE https://localhost:9443/api/am/publisher/v0.12/apis/40082986-6488-4b86-801a-b0b069d4588c/policies/mediation/60f5146d-1774-405d-86b3-9b040ac266d5\r\nAuthorization: Bearer fb2a0784-f60c-3276-8fde-5b0f70e61ecc" - x-wso2-response: "HTTP/1.1 200 OK" - summary: Delete an API specific mediation policy - description: | - This operation can be used to delete an existing API specific mediation policy providing the Id of the API and the Id of the mediation policy. - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/mediationPolicyId' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - tags: - - Mediation Policy (Individual) - responses: - 200: - description: | - OK. - Resource successfully deleted. - 403: - description: | - Forbidden. - The request must be conditional but no condition has been specified. - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - Resource to be deleted does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - -#----------------------------------------------------- -# Update the a mediation policy -#----------------------------------------------------- - put: - x-scope: apim:api_create - x-wso2-curl: "curl -k -H \"Authorization: Bearer 9e41fae2-3ada-3dd1-8f12-2077202f4285\" -H \"Content-Type: application/json\" -X PUT -d @data.json https://localhost:9443/api/am/publisher/v0.12/apis/40082986-6488-4b86-801a-b0b069d4588c/policies/mediation/820fdcf7-7258-42b5-809e-674b893644d1" - x-wso2-request: "PUT https://localhost:9443/api/am/publisher/v0.12/apis/40082986-6488-4b86-801a-b0b069d4588c/policies/mediation/820fdcf7-7258-42b5-809e-674b893644d1\r\nContent-Type: application/json\r\nAuthorization: Bearer 9e41fae2-3ada-3dd1-8f12-2077202f4285\r\n\r\n{\r\n \"name\": \"add_custom_header_fault\",\r\n \"type\": \"fault\",\r\n \"config\": \"\\n \\n<\\/sequence>\\n\"\r\n}" - x-wso2-response: "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\r\n \"id\": \"a7365481-5b3f-463c-a646-a498895ac210\",\r\n \"name\": \"add_custom_header_fault\",\r\n \"type\": \"fault\",\r\n \"config\": \"\\n \\n<\\/sequence>\\n\"\r\n}" - summary: Update an API specific mediation policy - description: | - This operation can be used to update an existing mediation policy of an API. - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/mediationPolicyId' - - in: body - name: body - description: | - Mediation policy object that needs to be updated - required: true - schema: - $ref: '#/definitions/Mediation' - - $ref: '#/parameters/Content-Type' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - tags: - - Mediation Policy (Individual) - responses: - 200: - description: | - OK. - Successful response with updated API object - schema: - $ref: '#/definitions/Mediation' - headers: - Location: - description: | - The URL of the newly created resource. - type: string - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 400: - description: | - Bad Request. - Invalid request or validation error - schema: - $ref: '#/definitions/Error' - 403: - description: | - Forbidden. - The request must be conditional but no condition has been specified. - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - The resource to be updated does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - -###################################################### -# The wsdl Resource -###################################################### - /apis/{apiId}/wsdl: - -#----------------------------------------------------- -# Retrieve the details about a certain wsdl -#----------------------------------------------------- - get: - x-scope: apim:api_view - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" \"https://localhost:9443/api/am/publisher/v0.12/apis/7f82f6b0-2667-441e-af23-c0fc44cf3a17/wsdl\"" - x-wso2-request: | - GET https://localhost:9443/api/am/publisher/v0.12/apis/7f82f6b0-2667-441e-af23-c0fc44cf3a17/wsdl - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\r\n \"name\": \"admin--hello1.0.0.wsdl\",\r\n \"wsdlDefinition\": \"\\n \\n \\n <\\/part>\\n <\\/message>\\n \\n \\n <\\/part>\\n <\\/message>\\n \\n \\n \\n <\\/input>\\n \\n <\\/output>\\n <\\/operation>\\n <\\/portType>\\n \\n \\n \\n \\n \\n \\n <\\/input>\\n \\n \\n <\\/output>\\n <\\/operation>\\n <\\/binding>\\n \\nWSDL File for HelloService<\\/documentation>\\n \\n \\n <\\/port>\\n <\\/service>\\n<\\/definitions>\"\r\n}" - summary: Get the WSDL of an API - description: | - This operation can be used to retrieve the WSDL definition of an API. - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - - $ref: '#/parameters/If-Modified-Since' - tags: - - Wsdl (Individual) - responses: - 200: - description: | - OK. - Requested WSDL DTO object belongs to the API - schema: - $ref: '#/definitions/Wsdl' - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 404: - description: | - Not Found. - Requested API does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' -#----------------------------------------------------- -# Add a wsdl to the registry -#----------------------------------------------------- - post: - x-scope: apim:api_create - x-wso2-curl: "curl -k -H \"Authorization:Bearer 5311eca3-8ac8-354e-ab36-7e2fdd6a4013\" -H \"Content-Type: application/json\" -X POST -d @data.json \"https://localhost:9443/api/am/publisher/v0.12/apis/af3f96da-9ccf-463f-8cee-13ec8530a9cd/wsdl\"" - x-wso2-request: "POST https://localhost:9443/api/am/publisher/v0.12/apis/af3f96da-9ccf-463f-8cee-13ec8530a9cd/wsdl\r\nContent-Type: application/json\r\nAuthorization: Bearer 7d237cab-7011-3f81-b384-24d03e750873\r\n\r\n{\r\n \"name\": \"admin--PizzaShackAPI1.0.0.wsdl\",\r\n \"wsdlDefinition\": \"\\n \\n \\n <\\/part>\\n <\\/message>\\n \\n \\n <\\/part>\\n <\\/message>\\n \\n \\n \\n <\\/input>\\n \\n <\\/output>\\n <\\/operation>\\n <\\/portType>\\n \\n \\n \\n \\n \\n \\n <\\/input>\\n \\n \\n <\\/output>\\n <\\/operation>\\n <\\/binding>\\n \\nWSDL File for HelloService<\\/documentation>\\n \\n \\n <\\/port>\\n <\\/service>\\n<\\/definitions>\"\r\n}" - x-wso2-response: "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\r\n \"name\": \"admin--PizzaShackAPI1.0.0.wsdl\",\r\n \"wsdlDefinition\": \"\\n \\n \\n <\\/part>\\n <\\/message>\\n \\n \\n <\\/part>\\n <\\/message>\\n \\n \\n \\n <\\/input>\\n \\n <\\/output>\\n <\\/operation>\\n <\\/portType>\\n \\n \\n \\n \\n \\n \\n <\\/input>\\n \\n \\n <\\/output>\\n <\\/operation>\\n <\\/binding>\\n \\nWSDL File for HelloService<\\/documentation>\\n \\n \\n <\\/port>\\n <\\/service>\\n<\\/definitions>\"\r\n}" - summary: Add a WSDL to an API - description: | - This operation can be used to add a WSDL definition to an existing API. - parameters: - - $ref: '#/parameters/apiId' - - in: body - name: body - description: | - JSON payload including WSDL definition that needs to be added - required: true - schema: - $ref: '#/definitions/Wsdl' - - $ref: '#/parameters/Content-Type' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - tags: - - Wsdl (Individual) - responses: - 200: - description: | - OK. - Successful response with updated wsdl definition - headers: - Location: - description: | - The URL of the newly created resource. - type: string - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 400: - description: | - Bad Request. - Invalid request or validation error - schema: - $ref: '#/definitions/Error' - 403: - description: | - Forbidden. - The request must be conditional but no condition has been specified. - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - The resource to be updated does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - - -###################################################### -# The "Individual Application" resource APIs -###################################################### - '/applications/{applicationId}': - -#----------------------------------------------------- -# Retrieve the details about a certain application -#----------------------------------------------------- - get: - x-scope: apim:api_create - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" https://localhost:9443/api/am/publisher/v0.12/applications/896658a0-b4ee-4535-bbfa-806c894a4015" - x-wso2-request: | - GET https://localhost:9443/api/am/publisher/v0.12/applications/896658a0-b4ee-4535-bbfa-806c894a4015 - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"groupId\": \"\",\n \"subscriber\": \"admin\",\n \"throttlingTier\": \"Unlimited\",\n \"applicationId\": \"896658a0-b4ee-4535-bbfa-806c894a4015\",\n \"description\": null,\n \"name\": \"DefaultApplication\"\n}" - summary: Get details of an application - description: | - This operation can be used to retrieve details of an individual application specifying the application id in the URI. - parameters: - - $ref: '#/parameters/applicationId' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - - $ref: '#/parameters/If-Modified-Since' - tags: - - Application (Individual) - responses: - 200: - description: | - OK. - Application returned. - schema: - $ref: '#/definitions/Application' - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 404: - description: | - Not Found. - Requested application does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Subscription Collection" resource APIs -###################################################### - /subscriptions: - -#----------------------------------------------------- -# Retrieve all subscriptions of a certain API -#----------------------------------------------------- - get: - x-scope: apim:subscription_view - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" \"https://localhost:9443/api/am/publisher/v0.12/subscriptions?apiId=890a4f4d-09eb-4877-a323-57f6ce2ed79b\"" - x-wso2-request: | - GET https://localhost:9443/api/am/publisher/v0.12/subscriptions?apiId=890a4f4d-09eb-4877-a323-57f6ce2ed79b - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n \n{\n \"previous\": \"\",\n \"list\": [\n {\n \"subscriptionId\": \"64eca60b-2e55-4c38-8603-e9e6bad7d809\",\n \"tier\": \"Gold\",\n \"apiIdentifier\": \"admin-PhoneVerification-1.0.0\",\n \"applicationId\": \"896658a0-b4ee-4535-bbfa-806c894a4015\",\n \"status\": \"UNBLOCKED\"\n },\n {\n \"subscriptionId\": \"7ac22c34-8745-4cfe-91e0-262c50b2f2e3\",\n \"tier\": \"Gold\",\n \"apiIdentifier\": \"admin-PhoneVerification-1.0.0\",\n \"applicationId\": \"367a2361-8db5-4140-8133-c6c8dc7fa0c4\",\n \"status\": \"UNBLOCKED\"\n }\n ],\n \"next\": \"\",\n \"count\": 2\n}" - summary: Get all Subscriptions - description: | - This operation can be used to retrieve a list of subscriptions of the user associated with the provided access token. This operation is capable of - - 1. Retrieving all subscriptions for the user's APIs. - `GET https://localhost:9443/api/am/publisher/v0.12/subscriptions` - - 2. Retrieving subscriptions for a specific API. - `GET https://localhost:9443/api/am/publisher/v0.12/subscriptions?apiId=c43a325c-260b-4302-81cb-768eafaa3aed` - parameters: - - $ref: '#/parameters/apiId-Q' - - $ref: '#/parameters/limit' - - $ref: '#/parameters/offset' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - tags: - - Subscription (Collection) - responses: - 200: - description: | - OK. - Subscription list returned. - schema: - $ref: '#/definitions/SubscriptionList' - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 406: - description: | - Not Acceptable. The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Individual Subscription" resource APIs -###################################################### - '/subscriptions/{subscriptionId}': - -#----------------------------------------------------- -# Retrieve a certain subscription -#----------------------------------------------------- - get: - x-scope: apim:subscription_view - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" https://localhost:9443/api/am/publisher/v0.12/subscriptions/64eca60b-2e55-4c38-8603-e9e6bad7d809" - x-wso2-request: | - GET https://localhost:9443/api/am/publisher/v0.12/subscriptions/64eca60b-2e55-4c38-8603-e9e6bad7d809 - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"subscriptionId\": \"64eca60b-2e55-4c38-8603-e9e6bad7d809\",\n \"tier\": \"Gold\",\n \"apiIdentifier\": \"admin-PhoneVerification-1.0.0\",\n \"applicationId\": \"896658a0-b4ee-4535-bbfa-806c894a4015\",\n \"status\": \"UNBLOCKED\"\n}" - summary: Get details of a subscription - description: | - This operation can be used to get details of a single subscription. - parameters: - - $ref: '#/parameters/subscriptionId' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - - $ref: '#/parameters/If-Modified-Since' - tags: - - Subscription (Individual) - responses: - 200: - description: | - OK. - Subscription returned - schema: - $ref: '#/definitions/ExtendedSubscription' - headers: - Content-Type: - description: The content type of the body. - type: string - ETag: - description: 'Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future).' - type: string - Last-Modified: - description: 'Date and time the resource has been modifed the last time. Used by caches, or in conditional requests (Will be supported in future).' - type: string - '304': - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - '404': - description: | - Not Found. - Requested Subscription does not exist. - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Block Subscription" Processing Function resource API -###################################################### - /subscriptions/block-subscription: - -#----------------------------------------------------- -# Block a certain subscription -#----------------------------------------------------- - post: - x-scope: apim:subscription_block - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -X POST \"https://localhost:9443/api/am/publisher/v0.12/subscriptions/block-subscription?subscriptionId=64eca60b-2e55-4c38-8603-e9e6bad7d809&blockState=PROD_ONLY_BLOCKED\"" - x-wso2-request: | - POST https://localhost:9443/api/am/publisher/v0.12/subscriptions/block-subscription?subscriptionId=64eca60b-2e55-4c38-8603-e9e6bad7d809&blockState=PROD_ONLY_BLOCKED - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n \n{\n \"subscriptionId\": \"64eca60b-2e55-4c38-8603-e9e6bad7d809\",\n \"tier\": \"Gold\",\n \"apiIdentifier\": \"admin-PhoneVerification-1.0.0\",\n \"applicationId\": \"896658a0-b4ee-4535-bbfa-806c894a4015\",\n \"status\": \"PROD_ONLY_BLOCKED\"\n}" - summary: Block a subscription - description: | - This operation can be used to block a subscription. Along with the request, `blockState` must be specified as a query parameter. - - 1. `BLOCKED` : Subscription is completely blocked for both Production and Sandbox environments. - 2. `PROD_ONLY_BLOCKED` : Subscription is blocked for Production environment only. - parameters: - - $ref: '#/parameters/subscriptionId-Q' - - name: blockState - in: query - description: | - Subscription block state. - type: string - required: true - enum: - - BLOCKED - - PROD_ONLY_BLOCKED - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - tags: - - Subscription (Individual) - responses: - 200: - description: | - OK. - Subscription was blocked successfully. - headers: - ETag: - description: | - Entity Tag of the blocked subscription. - Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the subscription has been blocked. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 400: - description: | - Bad Request. - Invalid request or validation error - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - Requested subscription does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Unblock Subscription" Processing Function resource API -###################################################### - /subscriptions/unblock-subscription: - -#----------------------------------------------------- -# Unblock a certain subscription -#----------------------------------------------------- - post: - x-scope: apim:subscription_block - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -X POST \"https://localhost:9443/api/am/publisher/v0.12/subscriptions/unblock-subscription?subscriptionId=64eca60b-2e55-4c38-8603-e9e6bad7d809\"" - x-wso2-request: | - POST https://localhost:9443/api/am/publisher/v0.12/subscriptions/unblock-subscription?subscriptionId=64eca60b-2e55-4c38-8603-e9e6bad7d809 - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8` - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"subscriptionId\": \"64eca60b-2e55-4c38-8603-e9e6bad7d809\",\n \"tier\": \"Gold\",\n \"apiIdentifier\": \"admin-PhoneVerification-1.0.0\",\n \"applicationId\": \"896658a0-b4ee-4535-bbfa-806c894a4015\",\n \"status\": \"UNBLOCKED\"\n} " - summary: Unblock a Subscription - parameters: - - $ref: '#/parameters/subscriptionId-Q' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - description: | - This operation can be used to unblock a subscription specifying the subscription Id. The subscription will be fully unblocked after performing this operation. - tags: - - Subscription (Individual) - responses: - 200: - description: | - OK. - Subscription was unblocked successfully. - headers: - ETag: - description: | - Entity Tag of the unblocked subscription. - Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the subscription has been unblocked. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 400: - description: | - Bad Request. - Invalid request or validation error - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - Requested subscription does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Tier Collection" resource APIs -###################################################### - '/tiers/{tierLevel}': - -#----------------------------------------------------- -# Retrieve the list of all available tiers -#----------------------------------------------------- - get: - x-scope: apim:tier_view - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" https://localhost:9443/api/am/publisher/v0.12/tiers/api" - x-wso2-request: | - GET https://localhost:9443/api/am/publisher/v0.12/tiers/api - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n\n{\n \"previous\": \"\",\n \"list\": [\n {\n \"unitTime\": 60000,\n \"tierPlan\": \"FREE\",\n \"tierLevel\": \"api\",\n \"stopOnQuotaReach\": true,\n \"requestCount\": 1,\n \"description\": \"Allows 1 request(s) per minute.\",\n \"name\": \"Bronze\",\n \"attributes\": {}\n },\n {\n \"unitTime\": 60000,\n \"tierPlan\": \"FREE\",\n \"tierLevel\": \"api\",\n \"stopOnQuotaReach\": true,\n \"requestCount\": 20,\n \"description\": \"Allows 20 request(s) per minute.\",\n \"name\": \"Gold\",\n \"attributes\": {}\n },\n {\n \"unitTime\": 60000,\n \"tierPlan\": \"FREE\",\n \"tierLevel\": \"api\",\n \"stopOnQuotaReach\": true,\n \"requestCount\": 5,\n \"description\": \"Allows 5 request(s) per minute.\",\n \"name\": \"Silver\",\n \"attributes\": {}\n },\n {\n \"unitTime\": 0,\n \"tierPlan\": null,\n \"tierLevel\": \"api\",\n \"stopOnQuotaReach\": true,\n \"requestCount\": 0,\n \"description\": \"Allows unlimited requests\",\n \"name\": \"Unlimited\",\n \"attributes\": {}\n }\n ],\n \"next\": \"\",\n \"count\": 4\n}" - summary: Get all tiers - description: | - This operation can be used to list the available tiers for a given tier level. Tier level should be specified as a path parameter and should be one of `api`, `application` and `resource`. - parameters: - - $ref: '#/parameters/limit' - - $ref: '#/parameters/offset' - - $ref: '#/parameters/tierLevel' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - tags: - - Throttling Tier (Collection) - responses: - 200: - description: | - OK. - List of tiers returned. - schema: - $ref: '#/definitions/TierList' - headers: - Content-Type: - description: The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -#----------------------------------------------------- -# Create a new tier -#----------------------------------------------------- - post: - x-scope: apim:tier_manage - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -H \"Content-Type: application/json\" -X POST -d @data.json \"https://localhost:9443/api/am/publisher/v0.12/tiers/api\"" - x-wso2-request: "POST https://localhost:9443/api/am/publisher/v0.12/tiers/api\nAuthorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\nContent-Type: application/json\n\n{\n \"unitTime\": 60000,\n \"tierPlan\": \"FREE\",\n \"tierLevel\": \"api\",\n \"stopOnQuotaReach\": true,\n \"requestCount\": 5,\n \"description\": \"Allows 5 request(s) per minute.\",\n \"name\": \"Low\",\n \"attributes\": {\n \"a\":10,\n \"b\":30\n }\n}" - x-wso2-response: "HTTP/1.1 201 Created\nLocation: https://localhost:9443/api/am/publisher/v0.12/tiers/Low\nContent-Type: application/json\n\n{\n \"unitTime\": 60000,\n \"tierPlan\": \"FREE\",\n \"tierLevel\": \"api\",\n \"stopOnQuotaReach\": true,\n \"requestCount\": 5,\n \"description\": \"Allows 5 request(s) per minute.\",\n \"name\": \"Low\",\n \"attributes\": {\n \"b\": \"30\",\n \"a\": \"10\"\n }\n}" - summary: Create a Tier - description: | - This operation can be used to create a new throttling tier. The only supported tier level is `api` tiers. - `POST https://localhost:9443/api/am/publisher/v0.12/tiers/api` - - **IMPORTANT:** - * This is only effective when Advanced Throttling is disabled in the Server. If enabled, we need to use Admin REST API for throttling tiers modification related operations. - parameters: - - in: body - name: body - description: | - Tier object that should to be added - required: true - schema: - $ref: '#/definitions/Tier' - - $ref: '#/parameters/tierLevel-A' - - $ref: '#/parameters/Content-Type' - tags: - - Throttling Tier (Collection) - responses: - 201: - description: | - Created. - Successful response with the newly created object as entity in the body. - Location header contains URL of newly created entity. - schema: - $ref: '#/definitions/Tier' - headers: - Location: - description: | - Location of the newly created tier. - type: string - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional request' - type: string - 400: - description: | - Bad Request. - Invalid request or validation error - schema: - $ref: '#/definitions/Error' - 415: - description: | - Unsupported media type. - The entity of the request was in a not supported format. - -###################################################### -# The "Individual Tier" resource APIs -###################################################### - '/tiers/{tierLevel}/{tierName}': - -#----------------------------------------------------- -# Retrieve a certain tier -#----------------------------------------------------- - get: - x-scope: apim:tier_view - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" https://localhost:9443/api/am/publisher/v0.12/tiers/api/Bronze" - x-wso2-request: | - GET https://localhost:9443/api/am/publisher/v0.12/tiers/api/Bronze - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"unitTime\": 60000,\n \"tierPlan\": \"FREE\",\n \"tierLevel\": \"api\",\n \"stopOnQuotaReach\": true,\n \"requestCount\": 1,\n \"description\": \"Allows 1 request(s) per minute.\",\n \"name\": \"Bronze\",\n \"attributes\": {}\n}" - summary: Get details of a tier - description: | - This operation can be used to retrieve details of a single tier by specifying the tier level and tier name. - Note that the scope of the API is mandatory while retreiving the access token with the following cURL command : `curl -k -d \"grant_type=password&username=username&password=password&scope=apim:tier_view\" -H \"Authorization: Basic \" https://localhost:8243/token`. - You will receive the access token as the response, for example `"access_token":"8644c013-7ff1-3217-b150-d7b92cae6be7"`. - parameters: - - $ref: '#/parameters/tierName' - - $ref: '#/parameters/tierLevel' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - - $ref: '#/parameters/If-Modified-Since' - tags: - - Throttling Tier (Individual) - responses: - 200: - description: | - OK. - Tier returned - schema: - $ref: '#/definitions/Tier' - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 404: - description: | - Not Found. - Requested Tier does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported. - schema: - $ref: '#/definitions/Error' - -#----------------------------------------------------- -# Update a certain tier -#----------------------------------------------------- - put: - x-scope: apim:tier_manage - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -H \"Content-Type: application/json\" -X PUT -d @data.json \"https://localhost:9443/api/am/publisher/v0.12/tiers/api/Low\"" - x-wso2-request: "PUT https://localhost:9443/api/am/publisher/v0.12/tiers/api/Low\nAuthorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\nContent-Type: application/json\n\n{\n \"unitTime\": 60000,\n \"tierPlan\": \"FREE\",\n \"tierLevel\": \"api\",\n \"stopOnQuotaReach\": true,\n \"requestCount\": 10,\n \"description\": \"Allows 10 request(s) per minute.\",\n \"name\": \"Low\",\n \"attributes\": {\n \"a\": \"30\",\n \"b\": \"10\",\n \"c\": \"20\"\n }\n}\n" - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"unitTime\": 60000,\n \"tierPlan\": \"FREE\",\n \"tierLevel\": \"api\",\n \"stopOnQuotaReach\": true,\n \"requestCount\": 10,\n \"description\": \"Allows 10 request(s) per minute.\",\n \"name\": \"Low\",\n \"attributes\": {\n \"b\": \"10\",\n \"c\": \"20\",\n \"a\": \"30\"\n }\n}" - summary: Update a Tier - description: | - This operation can be used to update an existing tier. The only supported tier level is `api` tiers. - `PUT https://localhost:9443/api/am/publisher/v0.12/tiers/api/Low` - - **IMPORTANT:** - * This is only effective when Advanced Throttling is disabled in the Server. If enabled, we need to use Admin REST API for throttling tiers modification related operations. - parameters: - - $ref: '#/parameters/tierName' - - in: body - name: body - description: | - Tier object that needs to be modified - required: true - schema: - $ref: '#/definitions/Tier' - - $ref: '#/parameters/tierLevel-A' - - $ref: '#/parameters/Content-Type' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - tags: - - Throttling Tier (Individual) - responses: - 200: - description: | - OK. - Subscription updated. - schema: - $ref: '#/definitions/Tier' - headers: - Location: - description: | - The URL of the newly created resource. - type: string - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 400: - description: | - Bad Request. - Invalid request or validation error. - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - The resource to be updated does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - -#----------------------------------------------------- -# Delete a certain tier -#----------------------------------------------------- - delete: - x-scope: apim:tier_manage - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -X DELETE \"https://localhost:9443/api/am/publisher/v0.12/tiers/api/Low\"" - x-wso2-request: | - DELETE https://localhost:9443/api/am/publisher/v0.12/tiers/api/Low - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK" - summary: Delete a Tier - description: | - This operation can be used to delete an existing tier. The only supported tier level is `api` tiers. - `DELETE https://localhost:9443/api/am/publisher/v0.12/tiers/api/Low` - - **IMPORTANT:** - * This is only effective when Advanced Throttling is disabled in the Server. If enabled, we need to use Admin REST API for throttling tiers modification related operations. - parameters: - - $ref: '#/parameters/tierName' - - $ref: '#/parameters/tierLevel-A' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - tags: - - Throttling Tier (Individual) - responses: - 200: - description: | - OK. - Resource successfully deleted. - 404: - description: | - Not Found. - Resource to be deleted does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Update Permission" Processing Function resource API -###################################################### - '/tiers/update-permission': - -#----------------------------------------------------- -# Update the permission of a certain tier -#----------------------------------------------------- - post: - x-scope: apim:tier_manage - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -H \"Content-Type: application/json\" -X POST -d @data.json \"https://localhost:9443/api/am/publisher/v0.12/tiers/update-permission?tierName=Bronze&tierLevel=api\"" - x-wso2-request: "POST https://localhost:9443/api/am/publisher/v0.12/tiers/update-permission?tierName=Bronze&tierLevel=api\nAuthorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\nContent-Type: application/json\n\n{\n \"permissionType\":\"deny\",\n \"roles\": [\"Internal/everyone\",\"admin\"]\n}" - x-wso2-response: "HTTP/1.1 200 OK" - summary: Update tier permission - description: | - This operation can be used to update tier permissions which controls access for the particular tier based on the subscribers' roles. - parameters: - - $ref: '#/parameters/tierName-Q' - - $ref: '#/parameters/tierLevel-Q' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - - in: body - name: permissions - schema: - $ref: '#/definitions/TierPermission' - tags: - - Throttling Tier (Individual) - responses: - 200: - description: | - OK. - Successfully updated tier permissions - schema: - type: array - items: - $ref: '#/definitions/Tier' - headers: - ETag: - description: | - Entity Tag of the modified tier. - Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the tier has been modified. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 400: - description: | - Bad Request. - Invalid request or validation error. - schema: - $ref: '#/definitions/Error' - 403: - description: | - Forbidden. - The request must be conditional but no condition has been specified. - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - Requested tier does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - - -###################################################### -# The "Environment Collection" resource API -###################################################### - /environments: - -#----------------------------------------------------- -# Retrieve the list of environments configured for a certain API -#----------------------------------------------------- - get: - x-scope: apim:api_view - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" \"https://localhost:9443/api/am/publisher/v0.12/environments\"" - x-wso2-request: | - GET https://localhost:9443/api/am/publisher/v0.12/environments - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"list\": [ {\n \"showInApiConsole\": true,\n \"serverUrl\": \"https://localhost:9443/services/\",\n \"endpoints\": {\n \"http\": \"http://localhost:8280\",\n \"https\": \"https://localhost:8243\"\n },\n \"name\": \"Production and Sandbox\",\n \"type\": \"hybrid\"\n }],\n \"count\": 1\n}" - summary: Get all gateway environments - description: | - This operation can be used to retrieve the list of gateway environments available. - parameters: - - $ref: '#/parameters/apiId-Q' - tags: - - Environment (Collection) - responses: - 200: - description: | - OK. - Environment list is returned. - schema: - $ref: '#/definitions/EnvironmentList' - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 404: - description: | - Not Found. - Requested API does not exist. - schema: - $ref: '#/definitions/Error' - /policies/mediation: - -#----------------------------------------------------------------------------------------- -# Retrieving the list of all global mediation sequences under a given search condition -#----------------------------------------------------------------------------------------- - get: - x-scope: apim:mediation_policy_view - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" https://localhost:9443/api/am/publisher/v0.12/policies/mediation" - x-wso2-request: | - GET https://localhost:9443/api/am/publisher/v0.12/policies/mediation - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\r\n \"count\": 10,\r\n \"next\": null,\r\n \"previous\": null,\r\n \"list\": [\r\n {\r\n \"name\": \"debug_json_fault\",\r\n \"id\": \"563de8f3-dd1d-4ec7-afc2-d158c663ed34\",\r\n \"type\": \"fault\"\r\n },\r\n {\r\n \"name\": \"json_fault\",\r\n \"id\": \"f9c36f4d-a2b6-41e7-b311-d358a47916be\",\r\n \"type\": \"fault\"\r\n },\r\n {\r\n \"name\": \"json_to_xml_in_message\",\r\n \"id\": \"3921225b-7918-4b95-a851-22c4e4e3e911\",\r\n \"type\": \"in\"\r\n },\r\n {\r\n \"name\": \"debug_in_flow\",\r\n \"id\": \"2bc15f93-4455-4763-89b8-83600fb9d731\",\r\n \"type\": \"in\"\r\n },\r\n {\r\n \"name\": \"log_in_message\",\r\n \"id\": \"4d287cca-76ab-44ca-b22e-919fc27c50e3\",\r\n \"type\": \"in\"\r\n },\r\n {\r\n \"name\": \"preserve_accept_header\",\r\n \"id\": \"3776b215-b3bc-40b6-bdcb-06efa7de64be\",\r\n \"type\": \"in\"\r\n },\r\n {\r\n \"name\": \"xml_to_json_in_message\",\r\n \"id\": \"50ac2002-769e-4f90-8549-6d0248dff7d2\",\r\n \"type\": \"in\"\r\n },\r\n {\r\n \"name\": \"xml_to_json_out_message\",\r\n \"id\": \"2af75853-ed75-4d25-81aa-0ebbeca691ea\",\r\n \"type\": \"out\"\r\n },\r\n {\r\n \"name\": \"json_to_xml_out_message\",\r\n \"id\": \"d9fa3ffc-f6b6-4171-ab97-eb44196cb66e\",\r\n \"type\": \"out\"\r\n },\r\n {\r\n \"name\": \"debug_out_flow\",\r\n \"id\": \"260b7701-4071-46bd-9b66-900ac6fffed6\",\r\n \"type\": \"out\"\r\n },\r\n {\r\n \"name\": \"apply_accept_header\",\r\n \"id\": \"15c17c2f-33e3-4c37-a262-04dfa49983a4\",\r\n \"type\": \"out\"\r\n },\r\n {\r\n \"name\": \"log_out_message\",\r\n \"id\": \"d37dca41-c048-492a-82cf-9a2292c6fff0\",\r\n \"type\": \"out\"\r\n }\r\n ]\r\n}" - summary: | - Get all global level mediation policies - description: | - This operation provides you a list of available all global level mediation policies. - parameters: - - $ref : '#/parameters/limit' - - $ref : '#/parameters/offset' - - name : query - in: query - description: "-Not supported yet-" - type: string - - $ref : "#/parameters/Accept" - - $ref : "#/parameters/If-None-Match" - tags: - - Mediation Policy (Collection) - responses: - 200: - description: | - OK. - List of mediation policies is returned. - schema: - $ref: '#/definitions/mediationList' - headers: - Content-Type: - description: The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - - - -###################################################### -# The "Workflow approval" resource API -###################################################### - /workflows/update-workflow-status: - -#------------------------------------------------------------------- -# Resume the workflow by approving or rejecting the workflow request -#------------------------------------------------------------------- - post: - x-scope: apim:api_workflow - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -H \"Content-Type: application/json\" -X POST -d @data.json \"https://localhost:9443/api/am/publisher/v0.12/workflows/update-workflow-status?workflowReferenceId=56e3a170-a7a7-45f8-b051-7e43a58a67e1\"" - x-wso2-request: "POST https://localhost:9443/api/am/publisher/v0.12/workflows/update-workflow-status?workflowReferenceId=56e3a170-a7a7-45f8-b051-7e43a58a67e1\nAuthorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\nContent-Type: application/json\n\n{\n \"status\" : \"APPROVED\",\n \"attributes\" : {\n \"apiCurrentState\": \"Created\",\n \"apiLCAction\": \"Publish\",\n \"apiName\":\"APIname\",\n \"apiVersion\" : \"1.0.0\",\n \"apiProvider\" : \"admin\",\n \"invoker\": \"admin\"\n }\n}" - x-wso2-response: "HTTP/1.1 200 OK" - summary: Update workflow status - description: | - This operation can be used to approve or reject a workflow task. - parameters: - - $ref: '#/parameters/workflowReferenceId-Q' - - in: body - name: body - description: | - Workflow event that need to be updated - required: true - schema: - $ref: '#/definitions/Workflow' - tags: - - Workflows (Individual) - responses: - 200: - description: | - OK. - Workflow request information is returned. - schema: - $ref: '#/definitions/Workflow' - headers: - Content-Type: - description: | - The content type of the body. - type: string - 400: - description: | - Bad Request. - Invalid request or validation error. - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - Workflow for the given reference in not found. - schema: - $ref: '#/definitions/Error' -###################################################### -# Parameters - required by some of the APIs above -###################################################### -parameters: - -# API Identifier -# Specified as part of the path expression - apiId: - name: apiId - in: path - description: | - **API ID** consisting of the **UUID** of the API. Using the **UUID** in the API call is recommended. - The combination of the provider of the API, name of the API and the version is also accepted as a valid API ID. - Should be formatted as **provider-name-version**. - required: true - type: string - x-encoded: true - -# API Identifier -# Specified as part of the query string - apiId-Q: - name: apiId - in: query - description: | - **API ID** consisting of the **UUID** of the API. Using the **UUID** in the API call is recommended. - The combination of the provider of the API, name of the API and the version is also accepted as a valid API I. - Should be formatted as **provider-name-version**. - required: true - type: string - x-encoded: true - - -# Document Identifier -# Specified as part of the path expression - documentId: - name: documentId - in: path - description: | - Document Identifier - required: true - type: string - -# Application Identifier -# Specified as part of the path expression - applicationId: - name: applicationId - in: path - description: | - **Application Identifier** consisting of the UUID of the Application. - required: true - type: string - -# Subscription Identifier -# Specified as part of the path expression - subscriptionId: - name: subscriptionId - in: path - description: | - Subscription Id - required: true - type: string - -# Mediation policy identifier -# Specified as part of the path expression - mediationPolicyId: - name: mediationPolicyId - in: path - description: | - Mediation policy Id - required: true - type: string - - - -# Subscription Identifier -# Specified as part of the query string - subscriptionId-Q: - name: subscriptionId - in: query - description: | - Subscription Id - required: true - type: string - -# Tier Name -# Specified as part of the path expression - tierName: - name: tierName - in: path - description: | - Tier name - required: true - type: string - -# Tier Name -# Specified as part of the query string - tierName-Q: - name: tierName - in: query - description: | - Name of the tier - required: true - type: string - -# Tier Type -# Specified as part of the path expression - tierLevel: - name: tierLevel - in: path - description: | - List API or Application or Resource type tiers. - type: string - enum: - - api - - application - - resource - required: true - -# Tier Type -# Specified as part of the path expression - tierLevel-A: - name: tierLevel - in: path - description: | - List API or Application or Resource type tiers. - type: string - enum: - - api - required: true - -# Tier Type -# Specified as part of the query string - tierLevel-Q: - name: tierLevel - in: query - description: | - List API or Application or Resource type tiers. - type: string - enum: - - api - - application - - resource - required: true - -# Used for pagination: -# The maximum number of resoures to be returned by a GET - limit: - name: limit - in: query - description: | - Maximum length of resource array to return. - default: 25 - type: integer - -# Used for pagination: -# The order number of an instance in a qualified set of resoures -# at which to start to return the next batch of qualified resources - offset: - name: offset - in: query - description: | - Starting point within the complete list of items qualified. - default: 0 - type: integer - -# The HTTP Accept header - Accept: - name: Accept - in: header - description: | - Media types acceptable for the response. Default is application/json. - default: application/json - type: string - -# The HTTP Content-Type header - Content-Type: - name: Content-Type - in: header - description: | - Media type of the entity in the body. Default is application/json. - default: application/json - required: true - type : string - -# The HTTP Authorization header - Authorization: - name: Authorization - in: header - description: | - Holds the bearer token for apis that require authentication. - required: true - type : string - -# The HTTP If-None-Match header -# Used to avoid retrieving data that are already cached - If-None-Match: - name: If-None-Match - in: header - description: | - Validator for conditional requests; based on the ETag of the formerly retrieved - variant of the resource (Will be supported in future). - type : string - -# The HTTP If-Modified-Since header -# Used to avoid retrieving data that are already cached - If-Modified-Since: - name: If-Modified-Since - in: header - description: | - Validator for conditional requests; based on Last Modified header of the - formerly retrieved variant of the resource (Will be supported in future). - type: string - -# The HTTP If-Match header -# Used to avoid concurrent updates - If-Match: - name: If-Match - in: header - description: | - Validator for conditional requests; based on ETag (Will be supported in future). - type: string - -# The HTTP If-Unmodified-Since header -# Used to avoid concurrent updates - If-Unmodified-Since: - name: If-Unmodified-Since - in: header - description: | - Validator for conditional requests; based on Last Modified header (Will be supported in future). - type: string - - -# Workflow reference ID -# Specified as part of the path expression - workflowReferenceId-Q: - name: workflowReferenceId - in: query - description: | - Workflow reference id - required: true - type: string - -###################################################### -# The resources used by some of the APIs above within the message body -###################################################### -definitions: - -#----------------------------------------------------- -# The API List resource -#----------------------------------------------------- - APIList: - title: API List - properties: - count: - type: integer - description: | - Number of APIs returned. - example: 1 - next: - type: string - description: | - Link to the next subset of resources qualified. - Empty if no more resources are to be returned. - example: "/apis?limit=1&offset=2&query=" - previous: - type: string - description: | - Link to the previous subset of resources qualified. - Empty if current subset is the first subset returned. - example: "/apis?limit=1&offset=0&query=" - list: - type: array - items: - $ref: '#/definitions/APIInfo' - pagination: - properties: - offset: - type: integer - example: 12 - limit: - type: integer - example: 25 - total: - type: integer - example: 1290 - -#----------------------------------------------------- -# The API Info resource -#----------------------------------------------------- - APIInfo: - title: API Info object with basic API details. - properties: - id: - type: string - example: 01234567-0123-0123-0123-012345678901 - name: - type: string - example: CalculatorAPI - description: - type: string - example: A calculator API that supports basic operations - context: - type: string - example: CalculatorAPI - version: - type: string - example: 1.0.0 - provider: - description: | - If the provider value is not given, the user invoking the API will be used as the provider. - type: string - example: admin - status: - type: string - example: CREATED - thumbnailUri: - type: string - example: /apis/01234567-0123-0123-0123-012345678901/thumbnail - -#----------------------------------------------------- -# The API resource -#----------------------------------------------------- - API: - title: API object - required: - - name - - context - - version - - tiers - - isDefaultVersion - - transport - - endpointConfig - - visibility - - type - properties: - id: - type: string - description: | - UUID of the api registry artifact - example: 01234567-0123-0123-0123-012345678901 - name: - type: string - description: Name of the API - example: CalculatorAPI - description: - type: string - description: A brief description about the API - example: A calculator API that supports basic operations - context: - type: string - description: A string that represents the context of the user's request - example: CalculatorAPI - version: - type: string - description: The version of the API - example: 1.0.0 - provider: - description: | - If the provider value is not given user invoking the api will be used as the provider. - type: string - example: admin - apiDefinition: - description: | - Swagger definition of the API which contains details about URI templates and scopes - type: string - example: "{\"paths\":{\"/substract\":{\"get\":{\"x-auth-type\":\"Application & Application User\",\"x-throttling-tier\":\"Unlimited\",\"parameters\":[{\"name\":\"x\",\"required\":true,\"type\":\"string\",\"in\":\"query\"},{\"name\":\"y\",\"required\":true,\"type\":\"string\",\"in\":\"query\"}],\"responses\":{\"200\":{}}}},\"/add\":{\"get\":{\"x-auth-type\":\"Application & Application User\",\"x-throttling-tier\":\"Unlimited\",\"parameters\":[{\"name\":\"x\",\"required\":true,\"type\":\"string\",\"in\":\"query\"},{\"name\":\"y\",\"required\":true,\"type\":\"string\",\"in\":\"query\"}],\"responses\":{\"200\":{}}}}},\"swagger\":\"2.0\",\"info\":{\"title\":\"CalculatorAPI\",\"version\":\"1.0.0\"}}" - wsdlUri: - description: | - WSDL URL if the API is based on a WSDL endpoint - type: string - example: "http://www.webservicex.com/globalweather.asmx?wsdl" - status: - type: string - description: This describes in which status of the lifecycle the API is - example: CREATED - responseCaching: - type: string - example: Disabled - cacheTimeout: - type: integer - example: 300 - destinationStatsEnabled: - type: string - example: Disabled - isDefaultVersion: - type: boolean - example: false - type: - type: string - description: The transport to be set. Accepted values are HTTP, WS - enum: - - HTTP - - WS - example: HTTP - default: HTTP - transport: - description: | - Supported transports for the API (http and/or https). - type: array - items: - type: string - example: ["http","https"] - tags: - type: array - description: Search keywords related to the API - items: - type: string - example: ["substract","add"] - tiers: - type: array - description: The subscription tiers selected for the particular API - items: - type: string - example: ["Unlimited"] - apiLevelPolicy: - description: The policy selected for the particular API - type: string - example: "Unlimited" - maxTps: - properties: - production: - type: integer - format: int64 - example: 1000 - sandbox: - type: integer - format: int64 - example: 1000 - thumbnailUri: - type: string - example: "/apis/01234567-0123-0123-0123-012345678901/thumbnail" - visibility: - type: string - description: The visibility level of the API. Accepts one of the following. PUBLIC, PRIVATE, RESTRICTED OR CONTROLLED. - enum: - - PUBLIC - - PRIVATE - - RESTRICTED - - CONTROLLED - example: PUBLIC - visibleRoles: - type: array - description: The user roles that are able to access the API - items: - type: string - example: [] - endpointConfig: - type: string - example: "{\"production_endpoints\":{\"url\":\"https://localhost:9443/am/sample/pizzashack/v1/api/\",\"config\":{\"suspendErrorCode\":\"101000\",\"suspendDuration\":\"2000\",\"suspendMaxDuration\":\"3\",\"factor\":\"2\",\"retryErroCode\":\"101000\",\"retryTimeOut\":\"4\",\"retryDelay\":\"1000\",\"actionSelect\":\"fault\",\"actionDuration\":\"3000\"}},\"sandbox_endpoints\":{\"url\":\"https://localhost:9443/am/sample/pizzashack/v1/api/\",\"config\":null},\"endpoint_type\":\"http\"}" - endpointSecurity: - properties: - type: - type: string - example: basic - description: Accepts one of the following, basic or digest. - enum: - - basic - - digest - username: - type: string - example: admin - password: - type: string - example: password - gatewayEnvironments: - description: | - Comma separated list of gateway environments. - type: string - example: Production and Sandbox - sequences: - type: array - items: - $ref: '#/definitions/Sequence' - example: [] - subscriptionAvailability: - type: string - description: The subscription availability. Accepts one of the following. current_tenant, all_tenants or specific_tenants. - enum: - - current_tenant - - all_tenants - - specific_tenants - example: current_tenant - subscriptionAvailableTenants: - type: array - items: - type: string - example: ["tenant1", "tenant2"] - additionalProperties: - type: object - description : Map of custom properties of API - accessControl: - type: string - description: | - Is the API is restricted to certain set of publishers or creators or is it visible to all the - publishers and creators. If the accessControl restriction is none, this API can be modified by all the - publishers and creators, if not it can only be viewable/modifiable by certain set of publishers and creators, - based on the restriction. enum: - - NONE - - RESTRICTED - accessControlRoles: - type: array - description: The user roles that are able to view/modify as API publisher or creator. - items: - type: string - example: [admin] - businessInformation: - properties: - businessOwner: - type: string - example: businessowner - businessOwnerEmail: - type: string - example: businessowner@wso2.com - technicalOwner: - type: string - example: technicalowner - technicalOwnerEmail: - type: string - example: technicalowner@wso2.com - corsConfiguration: - description: | - CORS configuration for the API - properties: - corsConfigurationEnabled: - type: boolean - default: false - accessControlAllowOrigins: - type: array - items: - type: string - accessControlAllowCredentials: - type: boolean - default: false - accessControlAllowHeaders: - type: array - items: - type: string - accessControlAllowMethods: - type: array - items: - type: string - -#----------------------------------------------------- -# The Application resource -#----------------------------------------------------- - Application: - title: Application - required: - - name - - throttlingTier - properties: - applicationId: - type: string - example: 01234567-0123-0123-0123-012345678901 - name: - type: string - example: CalculatorApp - subscriber: - type: string - example: admin - throttlingTier: - type: string - example: Unlimited - description: - type: string - example: Sample calculator application - groupId: - type: string - example: "" - -#----------------------------------------------------- -# The Document List resource -#----------------------------------------------------- - DocumentList: - title: Document List - properties: - count: - type: integer - description: | - Number of Documents returned. - example: 1 - next: - type: string - description: | - Link to the next subset of resources qualified. - Empty if no more resources are to be returned. - example: "/apis/01234567-0123-0123-0123-012345678901/documents?limit=1&offset=2" - previous: - type: string - description: | - Link to the previous subset of resources qualified. - Empty if current subset is the first subset returned. - example: "/apis/01234567-0123-0123-0123-012345678901/documents?limit=1&offset=0" - list: - type: array - items: - $ref: '#/definitions/Document' - -#----------------------------------------------------- -# The Document resource -#----------------------------------------------------- - Document: - title: Document - required: - - name - - type - - sourceType - - visibility - properties: - documentId: - type: string - example: 01234567-0123-0123-0123-012345678901 - name: - type: string - example: CalculatorDoc - type: - type: string - enum: - - HOWTO - - SAMPLES - - PUBLIC_FORUM - - SUPPORT_FORUM - - API_MESSAGE_FORMAT - - SWAGGER_DOC - - OTHER - example: HOWTO - summary: - type: string - example: "Summary of Calculator Documentation" - sourceType: - type: string - enum: - - INLINE - - URL - - FILE - example: INLINE - sourceUrl: - type: string - example: "" - otherTypeName: - type: string - example: "" - visibility: - type: string - enum: - - OWNER_ONLY - - PRIVATE - - API_LEVEL - example: API_LEVEL - -#----------------------------------------------------- -# The Mediation List resource -#----------------------------------------------------- - mediationList: - title: Mediation List - properties: - count: - type: integer - description: | - Number of mediation sequences returned. - example: 1 - next: - type: string - description: | - Link to the next subset of sequences qualified. - Empty if no more sequences are to be returned. - example: "" - previous: - type: string - description: | - Link to the previous subset of sequences qualified. - Empty if current subset is the first subset returned. - example: "" - list: - type: array - items: - $ref: '#/definitions/MediationInfo' - -#----------------------------------------------------- -# The MediationInfo resource -#----------------------------------------------------- - MediationInfo: - title: MediationInfo - required: - - name - - type - - id - properties: - name: - type: string - example: json_fault.xml - id: - type: string - example: 01234567-0123-0123-0123-012345678901 - type: - type: string - enum: - - in - - out - - fault - example: in -#----------------------------------------------------- -# The Mediation resource -#----------------------------------------------------- - Mediation: - title: Mediation - required: - - name - - type - - config - properties: - id: - type: string - example: 01234567-0123-0123-0123-012345678901 - name: - type: string - example: json_fault.xml - type: - type: string - enum: - - in - - out - - fault - example: in - config: - type: string - example: ' - - - - ' - -#----------------------------------------------------- -# The MediationInfo resource -#----------------------------------------------------- - Wsdl: - title: Wsdl - required: - - name - properties: - name: - type: string - example: admin--calculatorAPI2.0.wsdl - wsdlDefinition: - type: string - - -# The Tier List resource -#----------------------------------------------------- - TierList: - title: Tier List - properties: - count: - type: integer - description: | - Number of Tiers returned. - example: 1 - next: - type: string - description: | - Link to the next subset of resources qualified. - Empty if no more resources are to be returned. - example: "/tiers/api?limit=1&offset=2" - previous: - type: string - description: | - Link to the previous subset of resources qualified. - Empty if current subset is the first subset returned. - example: "/tiers/api?limit=1&offset=0" - list: - type: array - items: - $ref: '#/definitions/Tier' - -#----------------------------------------------------- -# The Tier resource -#----------------------------------------------------- - Tier: - title: Tier - required: - - name - - tierPlan - - requestCount - - unitTime - - stopOnQuotaReach - properties: - name: - type: string - example: Platinum - description: - type: string - example: "Allows 50 request(s) per minute." - tierLevel: - type: string - enum: - - api - - application - - resource - example: api - attributes: - description: | - Custom attributes added to the tier policy - type: object - additionalProperties: - type: string - example: {} - requestCount: - description: | - Maximum number of requests which can be sent within a provided unit time - type: integer - format: int64 - example: 50 - unitTime: - type: integer - format: int64 - example: 60000 - timeUnit: - type: string - example: "min" - tierPlan: - description: | - This attribute declares whether this tier is available under commercial or free - type: string - enum: - - FREE - - COMMERCIAL - example: FREE - stopOnQuotaReach: - description: | - By making this attribute to false, you are capabale of sending requests - even if the request count exceeded within a unit time - type: boolean - example: true - -#----------------------------------------------------- -# The Tier Permission resource -#----------------------------------------------------- - TierPermission: - title: tierPermission - required: - - permissionType - - roles - properties: - permissionType: - type: string - enum: - - allow - - deny - example: deny - roles: - type: array - items: - type: string - example: ["Internal/everyone"] - -#----------------------------------------------------- -# The Subscription List resource -#----------------------------------------------------- - SubscriptionList: - title: Subscription List - properties: - count: - type: integer - description: | - Number of Subscriptions returned. - example: 1 - next: - type: string - description: | - Link to the next subset of resources qualified. - Empty if no more resources are to be returned. - example: "/subscriptions?limit=1&offset=2&apiId=01234567-0123-0123-0123-012345678901&groupId=" - previous: - type: string - description: | - Link to the previous subset of resources qualified. - Empty if current subset is the first subset returned. - example: "/subscriptions?limit=1&offset=0&apiId=01234567-0123-0123-0123-012345678901&groupId=" - list: - type: array - items: - $ref: '#/definitions/Subscription' - -#----------------------------------------------------- -# The Subscription resource -#----------------------------------------------------- - Subscription: - title: Subscription - required: - - applicationId - - apiIdentifier - - tier - properties: - subscriptionId: - type: string - example: 01234567-0123-0123-0123-012345678901 - applicationId: - type: string - example: 01234567-0123-0123-0123-012345678901 - apiIdentifier: - type: string - example: 01234567-0123-0123-0123-012345678901 - tier: - type: string - example: Unlimited - status: - type: string - enum: - - BLOCKED - - PROD_ONLY_BLOCKED - - UNBLOCKED - - ON_HOLD - - REJECTED - example: UNBLOCKED - -#----------------------------------------------------- -# The Extended Subscription resource -#----------------------------------------------------- - ExtendedSubscription: - title: Subscription with Ext. Workflow Reference - required: - - workflowId - allOf: - - $ref: '#/definitions/Subscription' - - properties: - workflowId: - type: string - example: 01234567-0123-0123-0123-012345678901 - -#----------------------------------------------------- -# The Sequence resource -#----------------------------------------------------- - Sequence: - title: Sequence - required: - - name - properties: - name: - type: string - example: log_in_message - type: - type: string - example: in - id: - type: string - example: 69ea3fa6-55c6-472e-896d-e449dd34a824 - shared: - type: boolean - example: true - -#----------------------------------------------------- -# The Error resource -#----------------------------------------------------- - Error: - title: Error object returned with 4XX HTTP status - required: - - code - - message - properties: - code: - type: integer - format: int64 - message: - type: string - description: Error message. - description: - type: string - description: | - A detail description about the error message. - moreInfo: - type: string - description: | - Preferably an url with more details about the error. - error: - type: array - description: | - If there are more than one error list them out. - For example, list out validation errors by each field. - items: - $ref: '#/definitions/ErrorListItem' - -#----------------------------------------------------- -# The Error List Item resource -#----------------------------------------------------- - ErrorListItem: - title: Description of individual errors that may have occurred during a request. - required: - - code - - message - properties: - code: - type: string - message: - type: string - description: | - Description about individual errors occurred - -#----------------------------------------------------- -# The Environment resource -#----------------------------------------------------- - Environment: - title: Environment - required: - - name - - type - - serverUrl - - endpoints - - showInApiConsole - properties: - name: - type: string - example: Production and Sandbox - type: - type: string - example: hybrid - serverUrl: - type: string - example: "https://localhost:9443/services/" - showInApiConsole: - type: boolean - example: true - endpoints: - $ref: '#/definitions/EnvironmentEndpoints' - -#----------------------------------------------------- -# The Environment List resource -#----------------------------------------------------- - EnvironmentList: - title: Environment List - properties: - count: - type: integer - description: | - Number of Environments returned. - example: 1 - list: - type: array - items: - $ref: '#/definitions/Environment' - - -#----------------------------------------------------- -# The Environment Endpoint resource -#----------------------------------------------------- - EnvironmentEndpoints : - title: Environment Endpoints - properties: - http: - type: string - description: HTTP environment URL - example: "http://localhost:8280" - https: - type: string - description: HTTPS environment URL - example: "https://localhost:8243" - -#----------------------------------------------------- -# The File Information resource -#----------------------------------------------------- - FileInfo : - title: File Information including meta data - properties: - relativePath: - type: string - description: relative location of the file (excluding the base context and host of the Publisher API) - example: "apis/01234567-0123-0123-0123-012345678901/thumbnail" - mediaType: - type: string - description: media-type of the file - example: "image/jpeg" - - -#----------------------------------------------------- -# The workflow response resource -#----------------------------------------------------- - Workflow: - title: workflow - required: - - status - properties: - status: - description: | - This attribute declares whether this workflow task is approved or rejected. - type: string - enum: - - APPROVED - - REJECTED - example: APPROVED - attributes: - description: | - Custom attributes to complete the workflow task - type: object - additionalProperties: - type: string - example: {} - description: - type: string - example: "Approve workflow request." \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/src/main/resources/store-api.yaml b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/src/main/resources/store-api.yaml deleted file mode 100644 index a57b96d4ab..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/src/main/resources/store-api.yaml +++ /dev/null @@ -1,2693 +0,0 @@ -# Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -# -# 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. -################################################################################ - -swagger: '2.0' -###################################################### -# Prolog -###################################################### -info: - version: "0.12.0" - title: "WSO2 API Manager - Store" - description: | - This specifies a **RESTful API** for WSO2 **API Manager** - Store. - - Please see [full swagger definition](https://raw.githubusercontent.com/wso2/carbon-apimgt/v6.1.66/components/apimgt/org.wso2.carbon.apimgt.rest.api.store/src/main/resources/store-api.yaml) of the API which is written using [swagger 2.0](http://swagger.io/) specification. - contact: - name: "WSO2" - url: "http://wso2.com/products/api-manager/" - email: "architecture@wso2.com" - license: - name: "Apache 2.0" - url: "http://www.apache.org/licenses/LICENSE-2.0.html" - -###################################################### -# The fixed parts of the URLs of the API -###################################################### - -# The schemes supported by the API -schemes: - - https - -# The domain of the API. -# This is configured by the customer during deployment. -# The given host is just an example. -host: apis.wso2.com - -# The base path of the API. -# Will be prefixed to all paths. -basePath: /api/am/store/v0.12 - -# The following media types can be passed as input in message bodies of the API. -# The actual media type must be specified in the Content-Type header field of the request. -# The default is json, i.e. the Content-Type header is not needed to -# be set, but supporting it serves extensibility. -consumes: - - application/json - -# The following media types may be passed as output in message bodies of the API. -# The media type(s) consumable by the requestor is specified in the Accept header field -# of the corresponding request. -# The actual media type returned will be specfied in the Content-Type header field -# of the of the response. -# The default of the Accept header is json, i.e. there is not needed to -# set the value, but supporting it serves extensibility. -produces: - - application/json - -x-wso2-security: - apim: - x-wso2-scopes: - - description: "" - roles: Internal/subscriber - name: apim:subscribe - key: apim:subscribe - -###################################################### -# The "API Collection" resource APIs -###################################################### -paths: - /apis: - -#----------------------------------------------------- -# Retrieving the list of all APIs qualifying under a given search condition -#----------------------------------------------------- - get: - x-wso2-curl: "curl https://localhost:9443/api/am/store/v0.12/apis" - x-wso2-curl-tenant: "curl -k -H \"X-WSO2-Tenant:test.com\" https://localhost:9443/api/am/store/v0.12/apis" - x-wso2-request: | - GET https://localhost:9443/api/am/store/v0.12/apis - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"previous\": \"\",\n \"list\": [\n {\n \"provider\": \"admin\",\n \"version\": \"1.0.0\",\n \"description\": \"This API provide Account Status Validation.\",\n \"status\": \"PUBLISHED\",\n \"name\": \"AccountVal\",\n \"context\": \"/account/1.0.0\",\n \"id\": \"2e81f147-c8a8-4f68-b4f0-69e0e7510b01\"\n },\n {\n \"provider\": \"admin\",\n \"version\": \"1.0.0\",\n \"description\": null,\n \"status\": \"PUBLISHED\",\n \"name\": \"api1\",\n \"context\": \"/api1/1.0.0\",\n \"id\": \"3e22d2fb-277a-4e9e-8c7e-1c0f7f73960e\"\n },\n {\n \"provider\": \"admin\",\n \"version\": \"2.0.0\",\n \"description\": \"Verify a phone number\",\n \"status\": \"PUBLISHED\",\n \"name\": \"PhoneVerification\",\n \"context\": \"/phoneverify/2.0.0\",\n \"id\": \"c43a325c-260b-4302-81cb-768eafaa3aed\"\n }\n ],\n \"count\": 3,\n \"next\": \"\"\n}" - summary: | - Retrieve/Search APIs - description: | - This operation provides you a list of available APIs qualifying under a given search condition. - - Each retrieved API is represented with a minimal amount of attributes. If you want to get complete details of an API, you need to use **Get details of an API** operation. - - This operation supports retriving APIs of other tenants. The required tenant domain need to be specified as a header `X-WSO2-Tenant`. If not specified super tenant's APIs will be retrieved. If you used an Authorization header, the user's tenant associated with the access token will be used. - - **NOTE:** - * By default, this operation retrieves Published APIs. In order to retrieve Prototyped APIs, you need to use **query** parameter and specify **status:PROTOTYPED**. - * This operation does not require an Authorization header by default. But if it is provided, it will be validated and checked for permissions of the user, hence you may be able to see APIs which are restricted for special permissions/roles. - parameters: - - $ref : '#/parameters/limit' - - $ref : '#/parameters/offset' - - $ref : '#/parameters/requestedTenant' - - name : query - in: query - description: | - **Search condition**. - - You can search in attributes by using an **":"** modifier. - - Eg. - "provider:wso2" will match an API if the provider of the API is exactly "wso2". - - Additionally you can use wildcards. - - Eg. - "provider:wso2*" will match an API if the provider of the API starts with "wso2". - - Supported attribute modifiers are [**version, context, status, - description, subcontext, doc, provider, tag**] - - If no advanced attribute modifier has been specified, search will match the - given query string against API Name. - - type: string - - $ref : "#/parameters/Accept" - - $ref : "#/parameters/If-None-Match" - tags: - - API (Collection) - responses: - 200: - description: | - OK. - List of qualifying APIs is returned. - schema: - $ref: '#/definitions/APIList' - headers: - Content-Type: - description: The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Individual API" resource APIs -###################################################### - /apis/{apiId}: - -#----------------------------------------------------- -# Retrieve the details of an API definition -#----------------------------------------------------- - get: - x-wso2-curl: "curl https://localhost:9443/api/am/store/v0.12/apis/c43a325c-260b-4302-81cb-768eafaa3aed" - x-wso2-curl-tenant: "curl -k -H \"X-WSO2-Tenant:test.com\" https://localhost:9443/api/am/store/v0.12/apis/c43a325c-260b-4302-81cb-768eafaa3aed" - x-wso2-request: | - GET https://localhost:9443/api/am/store/v0.12/apis/c43a325c-260b-4302-81cb-768eafaa3aed - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\r\n \"thumbnailUrl\": null,\r\n \"tiers\": [\"Unlimited\"],\r\n \"businessInformation\": {\r\n \"technicalOwner\": \"John Doe\",\r\n \"technicalOwnerEmail\": \"architecture@pizzashack.com\",\r\n \"businessOwner\": \"Jane Roe\",\r\n \"businessOwnerEmail\": \"marketing@pizzashack.com\"\r\n },\r\n \"apiDefinition\": \"{\\\"paths\\\":{\\\"/order\\\":{\\\"post\\\":{\\\"x-auth-type\\\":\\\"Application & Application User\\\",\\\"x-throttling-tier\\\":\\\"Unlimited\\\",\\\"description\\\":\\\"Create a new Order\\\",\\\"parameters\\\":[{\\\"schema\\\":{\\\"$ref\\\":\\\"#/definitions/Order\\\"},\\\"description\\\":\\\"Order object that needs to be added\\\",\\\"name\\\":\\\"body\\\",\\\"required\\\":true,\\\"in\\\":\\\"body\\\"}],\\\"responses\\\":{\\\"201\\\":{\\\"headers\\\":{\\\"Location\\\":{\\\"description\\\":\\\"The URL of the newly created resource.\\\",\\\"type\\\":\\\"string\\\"},\\\"Content-Type\\\":{\\\"description\\\":\\\"The content type of the body.\\\",\\\"type\\\":\\\"string\\\"}},\\\"schema\\\":{\\\"$ref\\\":\\\"#/definitions/Order\\\"},\\\"description\\\":\\\"Created. Successful response with the newly created object as entity in the body. Location header contains URL of newly created entity.\\\"}}}},\\\"/order/{orderId}\\\":{\\\"get\\\":{\\\"x-auth-type\\\":\\\"Application & Application User\\\",\\\"x-throttling-tier\\\":\\\"Unlimited\\\",\\\"description\\\":\\\"Get details of an Order\\\",\\\"parameters\\\":[{\\\"description\\\":\\\"Order Id\\\",\\\"name\\\":\\\"orderId\\\",\\\"format\\\":\\\"string\\\",\\\"type\\\":\\\"string\\\",\\\"required\\\":true,\\\"in\\\":\\\"path\\\"}],\\\"responses\\\":{\\\"200\\\":{\\\"schema\\\":{\\\"$ref\\\":\\\"#/definitions/Order\\\"},\\\"headers\\\":{},\\\"description\\\":\\\"OK Requested Order will be returned\\\"}}}}},\\\"schemes\\\":[\\\"https\\\"],\\\"produces\\\":[\\\"application/json\\\"],\\\"swagger\\\":\\\"2.0\\\",\\\"definitions\\\":{\\\"Order\\\":{\\\"title\\\":\\\"Pizza Order\\\",\\\"properties\\\":{\\\"customerName\\\":{\\\"type\\\":\\\"string\\\"},\\\"delivered\\\":{\\\"type\\\":\\\"boolean\\\"},\\\"address\\\":{\\\"type\\\":\\\"string\\\"},\\\"pizzaType\\\":{\\\"type\\\":\\\"string\\\"},\\\"creditCardNumber\\\":{\\\"type\\\":\\\"string\\\"},\\\"quantity\\\":{\\\"type\\\":\\\"number\\\"},\\\"orderId\\\":{\\\"type\\\":\\\"string\\\"}},\\\"required\\\":[\\\"orderId\\\"]}},\\\"consumes\\\":[\\\"application/json\\\"],\\\"info\\\":{\\\"title\\\":\\\"PizzaShackAPI\\\",\\\"description\\\":\\\"This document describe a RESTFul API for Pizza Shack online pizza delivery store.\\\\n\\\",\\\"license\\\":{\\\"name\\\":\\\"Apache 2.0\\\",\\\"url\\\":\\\"http://www.apache.org/licenses/LICENSE-2.0.html\\\"},\\\"contact\\\":{\\\"email\\\":\\\"architecture@pizzashack.com\\\",\\\"name\\\":\\\"John Doe\\\",\\\"url\\\":\\\"http://www.pizzashack.com\\\"},\\\"version\\\":\\\"1.0.0\\\"}}\",\r\n \"wsdlUri\": null,\r\n \"isDefaultVersion\": false,\r\n \"endpointURLs\": [ {\r\n \"environmentName\": \"Production and Sandbox\",\r\n \"environmentType\": \"hybrid\",\r\n \"environmentURLs\": {\r\n \"http\": \"http://localhost:8280//pizzashack/1.0.0\",\r\n \"https\": \"https://localhost:8243//pizzashack/1.0.0\"\r\n }\r\n }],\r\n \"transport\": [\r\n \"http\",\r\n \"https\"\r\n ],\r\n \"tags\": [\"pizza\"],\r\n \"version\": \"1.0.0\",\r\n \"description\": \"This document describe a RESTFul API for Pizza Shack online pizza delivery store.\\r\\n\",\r\n \"provider\": \"admin\",\r\n \"name\": \"PizzaShackAPI\",\r\n \"context\": \"/pizzashack/1.0.0\",\r\n \"id\": \"8848faaa-7fd1-478a-baa2-48a4ebb92c98\",\r\n \"status\": \"PUBLISHED\"\r\n} " - summary: | - Get details of an API - description: | - Using this operation, you can retrieve complete details of a single API. You need to provide the Id of the API to retrive it. - - `X-WSO2-Tenant` header can be used to retrive an API of a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used. - - **NOTE:** - * This operation does not require an Authorization header by default. But if it is provided, it will be validated and checked for permissions of the user, hence you may be able to see APIs which are restricted for special permissions/roles. \n - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - - $ref: '#/parameters/If-Modified-Since' - - $ref: '#/parameters/requestedTenant' - tags: - - API (Individual) - responses: - 200: - description: | - OK. - Requested API is returned - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests. - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - schema: - $ref: '#/definitions/API' - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource. - 404: - description: | - Not Found. - Requested API does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - - - /apis/{apiId}/swagger: -#----------------------------------------------------- -# Retrieve the API swagger definition -#----------------------------------------------------- - get: - x-wso2-request: | - GET https://localhost:9443/api/am/store/v0.12/apis/c43a325c-260b-4302-81cb-768eafaa3aed/swagger - x-wso2-curl: "curl https://localhost:9443/api/am/store/v0.12/apis/c43a325c-260b-4302-81cb-768eafaa3aed/swagger" - x-wso2-curl-tenant: "curl -k -H \"X-WSO2-Tenant:test.com\" https://localhost:9443/api/am/store/v0.12/apis/c43a325c-260b-4302-81cb-768eafaa3aed/swagger" - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"paths\": {\"/*\": {\"get\": {\n \"x-auth-type\": \"Application\",\n \"x-throttling-tier\": \"Unlimited\",\n \"responses\": {\"200\": {\"description\": \"OK\"}}\n }}},\n \"x-wso2-security\": {\"apim\": {\"x-wso2-scopes\": []}},\n \"swagger\": \"2.0\",\n \"info\": {\n \"title\": \"PhoneVerification\",\n \"description\": \"Verify a phone number\",\n \"contact\": {\n \"email\": \"xx@ee.com\",\n \"name\": \"xx\"\n },\n \"version\": \"2.0.0\"\n }\n}\n" - summary: | - Get swagger definition - description: | - You can use this operation to retrieve the swagger definition of an API. - - `X-WSO2-Tenant` header can be used to retrive the swagger definition an API of a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used. - - **NOTE:** - * This operation does not require an Authorization header by default. But in order to see a restricted API's swagger definition, you need to provide Authorization header. - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - - $ref: '#/parameters/If-Modified-Since' - - $ref: '#/parameters/requestedTenant' - tags: - - API (Individual) - responses: - 200: - description: | - OK. - Requested swagger document of the API is returned - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests. - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource. - 404: - description: | - Not Found. - Requested API does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -#----------------------------------------------------- -# Generate SDK for an API -#----------------------------------------------------- - /apis/generate-sdk/: - post: - x-scope: apim:subscribe - x-wso2-request: | - POST https://localhost:9443/api/am/store/v0.12/apis/generate-sdk?apiId=e93fb282-b456-48fc-8981-003fb89086ae&language=java - Authorization: Bearer 2e29904b-f3b0-366e-ba13-b469abedd88e - x-wso2-curl: "curl -k -H \"Authorization: Bearer 2e29904b-f3b0-366e-ba13-b469abedd88e\" -X POST 'https://localhost:9443/api/am/store/v0.12/apis/generate-sdk?apiId=5721d128-76d0-4cb9-b300-2bd9578beddb&language=java' > PizzaAPI_Java_SDK.zip" - x-wso2-response: "HTTP/1.1 200 OK \nContent-Disposition: attachment; filename=\"PizzaShackAPI_1.0.0_java.zip\"\nContent-Type: application/zip\n\n[zip content]" - summary: | - Generate SDK for an API - description: | - This operation can be used to generate SDK for an API by providing the id of the API along with the preferred language. - parameters: - - $ref: '#/parameters/apiId-Q' - - $ref: '#/parameters/language' - - $ref : '#/parameters/requestedTenant' - tags: - - API (Individual) - responses: - 200: - description: | - OK. - SDK generated successfully. - headers: - Content-Type: - description: | - The content type of the body. - type: string - 400: - description: | - Bad request. - SDK language is not supported. - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - Requested API does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Document Collection" resource APIs -###################################################### - /apis/{apiId}/documents: - -#----------------------------------------------------- -# Retrieve the documents associated with an API that qualify under a search condition -#----------------------------------------------------- - get: - x-wso2-request: | - GET https://localhost:9443/api/am/store/v0.12/apis/c43a325c-260b-4302-81cb-768eafaa3aed/documents - x-wso2-curl: "curl https://localhost:9443/api/am/store/v0.12/apis/c43a325c-260b-4302-81cb-768eafaa3aed/documents" - x-wso2-curl-tenant: "curl -k -H \"X-WSO2-Tenant:test.com\" https://localhost:9443/api/am/store/v0.12/apis/c43a325c-260b-4302-81cb-768eafaa3aed/documents" - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"previous\": \"\",\n \"list\": [\n {\n \"sourceType\": \"INLINE\",\n \"sourceUrl\": null,\n \"otherTypeName\": null,\n \"documentId\": \"850a4f34-db2c-4d23-9d85-3f95fbfb082c\",\n \"summary\": \"This is a sample documentation for v1.0.0\",\n \"name\": \"PhoneVerification API Documentation\",\n \"type\": \"HOWTO\"\n },\n {\n \"sourceType\": \"URL\",\n \"sourceUrl\": \"http://wiki.cdyne.com/index.php/Phone_Verification\",\n \"otherTypeName\": null,\n \"documentId\": \"98e18be8-5861-43c7-ba26-8cbbccd3a76f\",\n \"summary\": \"This is the URL for online documentation\",\n \"name\": \"Online Documentation\",\n \"type\": \"SAMPLES\"\n },\n {\n \"sourceType\": \"FILE\",\n \"sourceUrl\": null,\n \"otherTypeName\": null,\n \"documentId\": \"b66451ff-c6c2-4f6a-b91d-3821dc119b04\",\n \"summary\": \"This is a sample documentation pdf\",\n \"name\": \"Introduction to PhoneVerification API PDF\",\n \"type\": \"HOWTO\"\n }\n ],\n \"count\": 3,\n \"next\": \"\"\n}" - summary: | - Get a list of documents of an API - description: | - This operation can be used to retrive a list of documents belonging to an API by providing the id of the API. - - `X-WSO2-Tenant` header can be used to retrive documents of an API that belongs to a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used. - - **NOTE:** - * This operation does not require an Authorization header by default. But in order to see a restricted API's documents, you need to provide Authorization header. - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/limit' - - $ref: '#/parameters/offset' - - $ref: '#/parameters/requestedTenant' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - tags: - - Document (Collection) - responses: - 200: - description: | - OK. - Document list is returned. - schema: - $ref: '#/definitions/DocumentList' - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 404: - description: | - Not Found. - Requested API does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Individual Document" resource APIs -###################################################### - '/apis/{apiId}/documents/{documentId}': - -#----------------------------------------------------- -# Retrieve a particular document of a certain API -#----------------------------------------------------- - get: - x-wso2-request: | - GET https://localhost:9443/api/am/store/v0.12/apis/c43a325c-260b-4302-81cb-768eafaa3aed/documents/850a4f34-db2c-4d23-9d85-3f95fbfb082c - x-wso2-curl: "curl \"https://localhost:9443/api/am/store/v0.12/apis/c43a325c-260b-4302-81cb-768eafaa3aed/documents/850a4f34-db2c-4d23-9d85-3f95fbfb082c\"" - x-wso2-curl-tenant: "curl -k -H \"X-WSO2-Tenant:test.com\" https://localhost:9443/api/am/store/v0.12/apis/c43a325c-260b-4302-81cb-768eafaa3aed/documents/850a4f34-db2c-4d23-9d85-3f95fbfb082c" - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"sourceType\": \"INLINE\",\n \"sourceUrl\": null,\n \"otherTypeName\": null,\n \"documentId\": \"850a4f34-db2c-4d23-9d85-3f95fbfb082c\",\n \"summary\": \"This is a sample documentation for v1.0.0\",\n \"name\": \"PhoneVerification API Documentation\",\n \"type\": \"HOWTO\"\n}" - summary: | - Get a document of an API - description: | - This operation can be used to retrieve a particular document's metadata associated with an API. - - `X-WSO2-Tenant` header can be used to retrive a document of an API that belongs to a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used. - - **NOTE:** - * This operation does not require an Authorization header by default. But in order to see a restricted API's document, you need to provide Authorization header. - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/documentId' - - $ref: '#/parameters/requestedTenant' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - - $ref: '#/parameters/If-Modified-Since' - tags: - - Document (Individual) - responses: - 200: - description: | - OK. - Document returned. - schema: - $ref: '#/definitions/Document' - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests. - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource. - 404: - description: | - Not Found. - Requested Document does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - - -################################################################ -# The content resource of "Individual Document" resource APIs -################################################################ - - '/apis/{apiId}/documents/{documentId}/content': - - #------------------------------------------------------------------------------------------------- - # Downloads a FILE type document/get the inline content or source url of a certain document - #------------------------------------------------------------------------------------------------- - get: - x-wso2-request: | - GET https://localhost:9443/api/am/store/v0.12/apis/890a4f4d-09eb-4877-a323-57f6ce2ed79b/documents/0bcb7f05-599d-4e1a-adce-5cb89bfe58d5/content - x-wso2-curl: "curl \"https://localhost:9443/api/am/store/v0.12/apis/890a4f4d-09eb-4877-a323-57f6ce2ed79b/documents/0bcb7f05-599d-4e1a-adce-5cb89bfe58d5/content\" > sample.pdf" - x-wso2-curl-tenant: "curl -k -H \"X-WSO2-Tenant:test.com\" \"https://localhost:9443/api/am/store/v0.12/apis/890a4f4d-09eb-4877-a323-57f6ce2ed79b/documents/0bcb7f05-599d-4e1a-adce-5cb89bfe58d5/content\" > sample.pdf" - x-wso2-response: "HTTP/1.1 200 OK\nContent-Disposition: attachment; filename=\"sample.pdf\"\nContent-Type: application/octet-stream\nContent-Length: 7802\n\n%PDF-1.4\n%äüöß\n2 0 obj\n<>\nstream\n..\n>>\nstartxref\n7279\n%%EOF" - - summary: | - Get the content of an API document - description: | - This operation can be used to retrive the content of an API's document. - - The document can be of 3 types. In each cases responses are different. - - 1. **Inline type**: - The content of the document will be retrieved in `text/plain` content type - 2. **FILE type**: - The file will be downloaded with the related content type (eg. `application/pdf`) - 3. **URL type**: - The client will recieve the URL of the document as the Location header with the response with - `303 See Other` - - `X-WSO2-Tenant` header can be used to retrive the content of a document of an API that belongs to a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used. - - **NOTE:** - * This operation does not require an Authorization header by default. But in order to see a restricted API's document content, you need to provide Authorization header. - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/documentId' - - $ref: '#/parameters/requestedTenant' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - - $ref: '#/parameters/If-Modified-Since' - tags: - - Document (Individual) - responses: - 200: - description: | - OK. - File or inline content returned. - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests. - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 303: - description: | - See Other. - Source can be retrived from the URL specified at the Location header. - headers: - Location: - description: | - The Source URL of the document. - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource. - 404: - description: | - Not Found. - Requested Document does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -################################################################ -# The thumbnail resource of "Individual API" resource APIs -################################################################ - - /apis/{apiId}/thumbnail: -#------------------------------------------------------------------------------------------------- -# Downloads a thumbnail image of an API -#------------------------------------------------------------------------------------------------- - get: - x-wso2-request: | - GET https://localhost:9443/api/am/store/v0.12/apis/e93fb282-b456-48fc-8981-003fb89086ae/thumbnail - x-wso2-curl: "curl https://localhost:9443/api/am/store/v0.12/apis/e93fb282-b456-48fc-8981-003fb89086ae/thumbnail > image.jpg" - x-wso2-curl-tenant: "curl -k -H \"X-WSO2-Tenant:test.com\" https://localhost:9443/api/am/store/v0.12/apis/e93fb282-b456-48fc-8981-003fb89086ae/thumbnail > image.jpg" - x-wso2-response: "HTTP/1.1 200 OK\r\nContent-Type: image/jpeg\r\n\r\n[image content]" - summary: Get thumbnail image - description: | - This operation can be used to download a thumbnail image of an API. - - `X-WSO2-Tenant` header can be used to retrive a thumbnail of an API that belongs to a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used. - - **NOTE:** - * This operation does not require an Authorization header by default. But in order to see a restricted API's thumbnail, you need to provide Authorization header. - parameters: - - $ref: '#/parameters/apiId' - - $ref: '#/parameters/requestedTenant' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - - $ref: '#/parameters/If-Modified-Since' - tags: - - API (Individual) - responses: - 200: - description: | - OK. - Thumbnail image returned - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests. - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource. - 404: - description: | - Not Found. - Requested Document does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Application Collection" resource APIs -###################################################### - /applications: - -#----------------------------------------------------- -# Retrieve a list of all applications of a certain subscriber -#----------------------------------------------------- - get: - x-scope: apim:subscribe - x-wso2-request: | - GET https://localhost:9443/api/am/store/v0.12/applications - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" \"https://localhost:9443/api/am/store/v0.12/applications\"" - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"previous\": \"\",\n \"list\": [\n {\n \"groupId\": \"\",\n \"subscriber\": \"admin\",\n \"throttlingTier\": \"Unlimited\",\n \"applicationId\": \"367a2361-8db5-4140-8133-c6c8dc7fa0c4\",\n \"description\": \"\",\n \"status\": \"APPROVED\",\n \"name\": \"app1\"\n },\n {\n \"groupId\": \"\",\n \"subscriber\": \"admin\",\n \"throttlingTier\": \"Unlimited\",\n \"applicationId\": \"896658a0-b4ee-4535-bbfa-806c894a4015\",\n \"description\": null,\n \"status\": \"APPROVED\",\n \"name\": \"DefaultApplication\"\n }\n ],\n \"count\": 2,\n \"next\": \"\"\n}" - summary: | - Retrieve/Search applications - description: | - This operation can be used to retrieve list of applications that is belonged to the user associated with the provided access token. - parameters: - - $ref: '#/parameters/groupId' - - name : query - in: query - description: | - **Search condition**. - - You can search for an application by specifying the name as "query" attribute. - - Eg. - "app1" will match an application if the name is exactly "app1". - - Currently this does not support wildcards. Given name must exactly match the application name. - type: string - - $ref: '#/parameters/limit' - - $ref: '#/parameters/offset' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - tags: - - Application (Collection) - responses: - 200: - description: | - OK. - Application list returned. - schema: - $ref: '#/definitions/ApplicationList' - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 400: - description: | - Bad Request. - Invalid request or validation error. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported. - schema: - $ref: '#/definitions/Error' - -#----------------------------------------------------- -# Create a new application -#----------------------------------------------------- - post: - x-scope: apim:subscribe - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -H \"Content-Type: application/json\" -X POST -d @data.json \"https://localhost:9443/api/am/store/v0.12/applications\"" - x-wso2-request: "POST https://localhost:9443/api/am/store/v0.12/applications\nAuthorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\n\n{\n \"throttlingTier\": \"Unlimited\",\n \"description\": \"sample app description\",\n \"name\": \"sampleapp\",\n \"callbackUrl\": \"http://my.server.com/callback\"\n}" - x-wso2-response: "HTTP/1.1 201 Created\nLocation: https://localhost:9443/api/am/store/v0.12/applications/c30f3a6e-ffa4-4ae7-afce-224d1f820524\nContent-Type: application/json\n\n{\n \"groupId\": null,\n \"callbackUrl\": \"http://my.server.com/callback\",\n \"subscriber\": \"admin\",\n \"throttlingTier\": \"Unlimited\",\n \"applicationId\": \"c30f3a6e-ffa4-4ae7-afce-224d1f820524\",\n \"description\": \"sample app description\",\n \"status\": \"APPROVED\",\n \"name\": \"sampleapp\",\n \"keys\": []\n}" - summary: | - Create a new application - description: | - This operation can be used to create a new application specifying the details of the application in the payload. - parameters: - - in: body - name: body - description: | - Application object that is to be created. - required: true - schema: - $ref: '#/definitions/Application' - - $ref: '#/parameters/Content-Type' - tags: - - Application (Individual) - responses: - 201: - description: | - Created. - Successful response with the newly created object as entity in the body. - Location header contains URL of newly created entity. - schema: - $ref: '#/definitions/Application' - headers: - Location: - description: | - Location of the newly created Application. - type: string - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). - type: string - 400: - description: | - Bad Request. - Invalid request or validation error - schema: - $ref: '#/definitions/Error' - 409: - description: | - Conflict. - Application already exists. - schema: - $ref: '#/definitions/Error' - 415: - description: | - Unsupported media type. - The entity of the request was in a not supported format. - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Individual Application" resource APIs -###################################################### - '/applications/{applicationId}': - -#----------------------------------------------------- -# Retrieve the details about a certain application -#----------------------------------------------------- - get: - x-scope: apim:subscribe - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" \"https://localhost:9443/api/am/store/v0.12/applications/896658a0-b4ee-4535-bbfa-806c894a4015\"" - x-wso2-request: | - GET https://localhost:9443/api/am/store/v0.12/applications/896658a0-b4ee-4535-bbfa-806c894a4015 - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"groupId\": \"\",\n \"callbackUrl\": null,\n \"subscriber\": \"admin\",\n \"throttlingTier\": \"Unlimited\",\n \"applicationId\": \"896658a0-b4ee-4535-bbfa-806c894a4015\",\n \"description\": null,\n \"status\": \"APPROVED\",\n \"name\": \"DefaultApplication\",\n \"keys\": [ {\n \"consumerKey\": \"AVoREWiB16kY_GTIzscl40GYYZQa\",\n \"consumerSecret\": \"KXQxmS8W3xDvvJH4AfR6xrhKIeIa\",\n \"keyState\": \"COMPLETED\",\n \"keyType\": \"PRODUCTION\",\n \"supportedGrantTypes\": null,\n \"token\": {\n \"validityTime\": 3600,\n \"accessToken\": \"3887da6d111f0429c6dff47a46e87209\",\n \"tokenScopes\": [\n \"am_application_scope\",\n \"default\"\n ]\n }\n }]\n}" - summary: | - Get details of an application - description: | - This operation can be used to retrieve details of an individual application specifying the application id in the URI. - parameters: - - $ref: '#/parameters/applicationId' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - - $ref: '#/parameters/If-Modified-Since' - tags: - - Application (Individual) - responses: - 200: - description: | - OK. - Application returned. - schema: - $ref: '#/definitions/Application' - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests. - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource. - 404: - description: | - Not Found. - Requested application does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -#----------------------------------------------------- -# Update a certain application -#----------------------------------------------------- - put: - x-scope: apim:subscribe - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -H \"Content-Type: application/json\" -X PUT -d @data.json \"https://localhost:9443/api/am/store/v0.12/applications/c30f3a6e-ffa4-4ae7-afce-224d1f820524\"" - x-wso2-request: "PUT https://localhost:9443/api/am/store/v0.12/applications/c30f3a6e-ffa4-4ae7-afce-224d1f820524\nAuthorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\n\n{\n \"callbackUrl\": \"\",\n \"throttlingTier\": \"Bronze\",\n \"description\": \"sample app description updated\",\n \"name\": \"sampleapp\"\n}" - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"groupId\": null,\n \"callbackUrl\": \"\",\n \"subscriber\": \"admin\",\n \"throttlingTier\": \"Bronze\",\n \"applicationId\": \"c30f3a6e-ffa4-4ae7-afce-224d1f820524\",\n \"description\": \"sample app description updated\",\n \"status\": \"APPROVED\",\n \"name\": \"sampleapp\",\n \"keys\": []\n}" - summary: | - Update an application - description: | - This operation can be used to update an application. Upon succesfull you will retrieve the updated application as the response. - parameters: - - $ref: '#/parameters/applicationId' - - in: body - name: body - description: | - Application object that needs to be updated - required: true - schema: - $ref: '#/definitions/Application' - - $ref: '#/parameters/Content-Type' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - tags: - - Application (Individual) - responses: - 200: - description: | - OK. - Application updated. - schema: - $ref: '#/definitions/Application' - headers: - Location: - description: | - The URL of the newly created resource. - type: string - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests. - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 400: - description: | - Bad Request. - Invalid request or validation error - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - The resource to be updated does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - -#----------------------------------------------------- -# Delete a certain application -#----------------------------------------------------- - delete: - x-scope: apim:subscribe - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -X DELETE \"https://localhost:9443/api/am/store/v0.12/applications/367a2361-8db5-4140-8133-c6c8dc7fa0c4\"" - x-wso2-request: | - DELETE https://localhost:9443/api/am/store/v0.12/applications/367a2361-8db5-4140-8133-c6c8dc7fa0c4 - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK" - summary: | - Remove an application - description: | - This operation can be used to remove an application specifying its id. - parameters: - - $ref: '#/parameters/applicationId' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - tags: - - Application (Individual) - responses: - 200: - description: | - OK. - Resource successfully deleted. - 404: - description: | - Not Found. - Resource to be deleted does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Application Keys of a Given Type" resource APIs -###################################################### - '/applications/{applicationId}/keys/{keyType}': - -#----------------------------------------------------------- -# Retrieve key details of a given type (PRODUCTION/SANDBOX) -#----------------------------------------------------------- - get: - x-scope: apim:subscribe - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" \"https://localhost:9443/api/am/store/v0.12/applications/896658a0-b4ee-4535-bbfa-806c894a4015/keys/PRODUCTION\"" - x-wso2-request: | - GET https://localhost:9443/api/am/store/v0.12/applications/896658a0-b4ee-4535-bbfa-806c894a4015/keys/PRODUCTION - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n {\n \"consumerKey\": \"QwEtRHd4NJkcFuRUfAT5af8XEEoa\",\n \"consumerSecret\": \"7Fairfeu321ENjOR9w2xgJl3i70a\",\n \"supportedGrantTypes\": [\n \"refresh_token\",\n \"urn:ietf:params:oauth:grant-type:saml2-bearer\",\n \"password\",\n \"client_credentials\",\n \"iwa:ntlm\"\n ],\n \"callbackUrl\": \"http://sample/com/callback\",\n \"keyState\": \"COMPLETED\",\n \"keyType\": \"PRODUCTION\"}\n" - summary: | - Get key details of a given type - description: | - This operation can be used to retrieve key details of an individual application specifying the key type in the URI. - parameters: - - $ref: '#/parameters/applicationId' - - $ref: '#/parameters/keyType' - - $ref: '#/parameters/groupId' - - $ref: '#/parameters/Accept' - tags: - - Application (Individual) - - Application Keys - responses: - 200: - description: | - OK. - Application key details returned. - schema: - $ref: '#/definitions/ApplicationKey' - headers: - Content-Type: - description: | - The content type of the body. - type: string - 404: - description: | - Not Found. - Requested application does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -#----------------------------------------------------- -# Update grant types and callback url of an application -#----------------------------------------------------- - put: - x-scope: apim:subscribe - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -H \"Content-Type: application/json\" -X PUT -d @data.json \"https://localhost:9443/api/am/store/v0.12/applications/c30f3a6e-ffa4-4ae7-afce-224d1f820524/keys/SANDBOX\"" - x-wso2-request: | - PUT https://localhost:9443/api/am/store/v0.12/applications/896658a0-b4ee-4535-bbfa-806c894a4015/keys/SANDBOX - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - { - "supportedGrantTypes": [ - "refresh_token", - "urn:ietf:params:oauth:grant-type:saml2-bearer", - "password", - "client_credentials", - "iwa:ntlm" - ], - "callbackUrl": "http://sample/com/callback" - } - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n {\n \"consumerKey\": \"QwEtRHd4NJkcFuRUfAT5af8XEEoa\",\n \"consumerSecret\": \"7Fairfeu321ENjOR9w2xgJl3i70a\",\n \"supportedGrantTypes\": [\n \"refresh_token\",\n \"urn:ietf:params:oauth:grant-type:saml2-bearer\",\n \"password\",\n \"client_credentials\",\n \"iwa:ntlm\"\n ],\n \"callbackUrl\": \"http://sample/com/callback\",\n \"keyState\": \"COMPLETED\",\n \"keyType\": \"PRODUCTION\"}\n" - summary: | - Update grant types and callback url of an application - description: | - This operation can be used to update grant types and callback url of an application. (Consumer Key and Consumer Secret are ignored) Upon succesfull you will retrieve the updated key details as the response. - parameters: - - $ref: '#/parameters/applicationId' - - $ref: '#/parameters/keyType' - - in: body - name: body - description: | - Grant types/Callback URL update request object - required: true - schema: - $ref: '#/definitions/ApplicationKey' - tags: - - Application (Individual) - - Application Keys - responses: - 200: - description: | - Ok. - Grant types or/and callback url is/are updated. - schema: - $ref: '#/definitions/ApplicationKey' - 400: - description: | - Bad Request. - Invalid request or validation error - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - The resource to be updated does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - - -###################################################### -# The "Generate Keys" Processing Function resource API -###################################################### - '/applications/generate-keys': - -#----------------------------------------------------- -# Generate keys for an application -#----------------------------------------------------- - post: - x-scope: apim:subscribe - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -H \"Content-Type: application/json\" -X POST -d @data.json \"https://localhost:9443/api/am/store/v0.12/applications/generate-keys?applicationId=c30f3a6e-ffa4-4ae7-afce-224d1f820524\"" - x-wso2-request: "POST https://localhost:9443/api/am/store/v0.12/applications/generate-keys?applicationId=c30f3a6e-ffa4-4ae7-afce-224d1f820524\nAuthorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\n\n{\n \"validityTime\": \"3600\",\n \"keyType\": \"PRODUCTION\",\n \"accessAllowDomains\": [\"ALL\"\n ]\n}" - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"consumerSecret\": \"8V7DDKtKGtuG_9GDjaOJ5sijdX0a\",\n \"consumerKey\": \"LOFL8He72MSGVil4SS_bsh9O8MQa\",\n \"keyState\": \"APPROVED\",\n \"keyType\": \"PRODUCTION\",\n \"supportedGrantTypes\": [\n \"urn:ietf:params:oauth:grant-type:saml2-bearer\",\n \"iwa:ntlm\",\n \"refresh_token\",\n \"client_credentials\",\n \"password\"\n ],\n \"token\": {\n \"validityTime\": 3600,\n \"accessToken\": \"fd2cdc4906fbc162e033d57f85a71c21\",\n \"tokenScopes\": [\n \"am_application_scope\",\n \"default\"\n ]\n }\n}" - summary: | - Generate keys for application - description: | - This operation can be used to generate client Id and client secret for an application - parameters: - - $ref: '#/parameters/applicationId-Q' - - in: body - name: body - description: | - Application object the keys of which are to be generated - required: true - schema: - $ref: '#/definitions/ApplicationKeyGenerateRequest' - - $ref: '#/parameters/Content-Type' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - tags: - - Application (Individual) - responses: - 200: - description: | - OK. - Keys are generated. - schema: - $ref: '#/definitions/ApplicationKey' - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future).‚ - type: string - 400: - description: | - Bad Request. - Invalid request or validation error - schema: - $ref: '#/definitions/Error' - 404: - description: | - Not Found. - The resource to be updated does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met (Will be supported in future). - schema: - $ref: '#/definitions/Error' - '/applications/scopes/{applicationId}': - get: - x-scope: 'apim:subscribe' - x-wso2-request: |- - GET https://127.0.0.1:9443/api/am/store/v0.12/applications/scopes/896658a0-b4ee-4535-bbfa-806c894a4015 - Authorization: Beareraa0ddec1ac656744234477f20fafcb0d - x-wso2-curl: 'curl -k -H "Authorization: Bearer aa0ddec1ac656744234477f20fafcb0d" "https://127.0.0.1:9443/api/am/store/v0.12/applications/scopes/896658a0-b4ee-4535-bbfa-806c894a4015"' - x-wso2-response: |- - HTTP/1.1 200 OK - Content-Type: application/json - - { - "groupId": "", - "callbackUrl": null, - "subscriber": "admin", - "throttlingTier": "Unlimited", - "applicationId": "896658a0-b4ee-4535-bbfa-806c894a4015", - "description": null, - "status": "APPROVED", - "name": "DefaultApplication", - "keys": [ { - "consumerKey": "AVoREWiB16kY_GTIzscl40GYYZQa", - "consumerSecret": "KXQxmS8W3xDvvJH4AfR6xrhKIeIa", - "keyState": "COMPLETED", - "keyType": "PRODUCTION", - "supportedGrantTypes": null, - "token": { - "validityTime": 3600, - "accessToken": "3887da6d111f0429c6dff47a46e87209", - "tokenScopes": [ - "am_application_scope", - "default" - ] - } - }] - } - summary: | - Get scopes associated with a particular application based on subscribed APIs - description: | - Get scopes associated with a particular application based on subscribed APIs - parameters: - - $ref: '#/parameters/applicationId' - - $ref: '#/parameters/filterByUserRoles' - - $ref: '#/parameters/If-None-Match' - - $ref: '#/parameters/If-Modified-Since' - tags: - - Application (Individual) - responses: - '200': - description: | - OK. - Scope returned. - schema: - $ref: '#/definitions/ScopeList' - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests. - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional reuquests. - type: string - '304': - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource. - '401': - description: | - Un authorized. - The user is not authorized to view the application . - schema: - $ref: '#/definitions/Error' - '404': - description: | - Not Found. - Requested application does not exist. - schema: - $ref: '#/definitions/Error' - '406': - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Subscription Collection" resource APIs -###################################################### - /subscriptions: - -#----------------------------------------------------- -# Retrieve all subscriptions of a certain API and application -#----------------------------------------------------- - get: - x-scope: apim:subscribe - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" \"https://localhost:9443/api/am/store/v0.12/subscriptions?apiId=c43a325c-260b-4302-81cb-768eafaa3aed\"" - x-wso2-request: | - GET https://localhost:9443/api/am/store/v0.12/subscriptions?apiId=c43a325c-260b-4302-81cb-768eafaa3aed - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"previous\": \"\",\n \"list\": [\n {\n \"tier\": \"Bronze\",\n \"subscriptionId\": \"03b8ef2b-5ae5-41f5-968e-52fa7fbd5d33\",\n \"apiIdentifier\": \"admin-PhoneVerification-2.0.0\",\n \"applicationId\": \"896658a0-b4ee-4535-bbfa-806c894a4015\",\n \"status\": \"UNBLOCKED\"\n },\n {\n \"tier\": \"Bronze\",\n \"subscriptionId\": \"5ed42650-9f5e-4dd4-94f3-3f09f1b17354\",\n \"apiIdentifier\": \"admin-PhoneVerification-2.0.0\",\n \"applicationId\": \"846118a5-3b25-4c22-a983-2d0278936f09\",\n \"status\": \"UNBLOCKED\"\n }\n ],\n \"count\": 2,\n \"next\": \"\"\n}" - summary: | - Get all subscriptions - description: | - This operation can be used to retrieve a list of subscriptions of the user associated with the provided access token. This operation is capable of - - 1. Retrieving applications which are subscibed to a specific API. - `GET https://localhost:9443/api/am/store/v0.12/subscriptions?apiId=c43a325c-260b-4302-81cb-768eafaa3aed` - - 2. Retrieving APIs which are subscribed by a specific application. - `GET https://localhost:9443/api/am/store/v0.12/subscriptions?applicationId=c43a325c-260b-4302-81cb-768eafaa3aed` - - **IMPORTANT:** - * It is mandatory to provide either **apiId** or **applicationId**. - parameters: - - $ref: '#/parameters/apiId-Q' - - $ref: '#/parameters/applicationId-Q' - - $ref: '#/parameters/groupId' - - $ref: '#/parameters/offset' - - $ref: '#/parameters/limit' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - tags: - - Subscription (Collection) - responses: - 200: - description: | - OK. - Subscription list returned. - schema: - $ref: '#/definitions/SubscriptionList' - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 406: - description: | - Not Acceptable. The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -#----------------------------------------------------- -# Create a new subscription -#----------------------------------------------------- - post: - x-scope: apim:subscribe - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -H \"Content-Type: application/json\" -X POST -d @data.json \"https://localhost:9443/api/am/store/v0.12/subscriptions\"" - x-wso2-request: "POST https://localhost:9443/api/am/store/v0.12/subscriptions\nAuthorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\n\n{\n \"tier\": \"Gold\",\n \"apiIdentifier\": \"c43a325c-260b-4302-81cb-768eafaa3aed\",\n \"applicationId\": \"c30f3a6e-ffa4-4ae7-afce-224d1f820524\"\n}" - x-wso2-response: "HTTP/1.1 201 Created\nLocation: https://localhost:9443/api/am/store/v0.12/subscriptions/5b65808c-cdf2-43e1-a695-de63e3ad0ae9\nContent-Type: application/json\n\n{\n \"tier\": \"Gold\",\n \"subscriptionId\": \"5b65808c-cdf2-43e1-a695-de63e3ad0ae9\",\n \"apiIdentifier\": \"admin-PhoneVerification-2.0.0\",\n \"applicationId\": \"c30f3a6e-ffa4-4ae7-afce-224d1f820524\",\n \"status\": \"UNBLOCKED\"\n}" - summary: | - Add a new subscription - description: | - This operation can be used to add a new subscription providing the id of the API and the application. - parameters: - - in: body - name: body - description: | - Subscription object that should to be added - required: true - schema: - $ref: '#/definitions/Subscription' - - $ref: '#/parameters/Content-Type' - tags: - - Subscription (Individual) - responses: - 201: - description: | - Created. - Successful response with the newly created object as entity in the body. - Location header contains URL of newly created entity. - schema: - $ref: '#/definitions/Subscription' - headers: - Location: - description: | - Location to the newly created subscription. - type: string - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). - type: string - 400: - description: | - Bad Request. - Invalid request or validation error. - schema: - $ref: '#/definitions/Error' - 415: - description: | - Unsupported media type. - The entity of the request was in a not supported format. - -###################################################### -# The "Multiple Subscriptions" resource API -###################################################### - '/subscriptions/multiple': -#----------------------------------------------------- -# Create a batch of Subscriptions -#----------------------------------------------------- - post: - x-scope: apim:subscribe - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -H \"Content-Type: application/json\" -X POST -d @data.json \"https://localhost:9443/api/am/store/v0.12/subscriptions/multiple\"" - x-wso2-request: "POST https://localhost:9443/api/am/store/v0.12/subscriptions/multiple\nAuthorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\n\n{\n \"tier\": \"Gold\",\n \"apiIdentifier\": \"c43a325c-260b-4302-81cb-768eafaa3aed\",\n \"applicationId\": \"c30f3a6e-ffa4-4ae7-afce-224d1f820524\"\n}" - x-wso2-response: "HTTP/1.1 201 Created\nLocation: https://localhost:9443/api/am/store/v0.12/subscriptions/5b65808c-cdf2-43e1-a695-de63e3ad0ae9\nContent-Type: application/json\n\n{\n \"tier\": \"Gold\",\n \"subscriptionId\": \"5b65808c-cdf2-43e1-a695-de63e3ad0ae9\",\n \"apiIdentifier\": \"admin-PhoneVerification-2.0.0\",\n \"applicationId\": \"c30f3a6e-ffa4-4ae7-afce-224d1f820524\",\n \"status\": \"UNBLOCKED\"\n}" - summary: | - Add new subscriptions - description: | - This operation can be used to add a new subscriptions providing the ids of the APIs and the applications. - parameters: - - in: body - name: body - description: | - Subscription objects that should to be added - required: true - schema: - type: array - items: - $ref: '#/definitions/Subscription' - - $ref: '#/parameters/Content-Type' - tags: - - Subscription (Multitple) - responses: - 200: - description: | - OK. - Successful response with the newly created objects as entity in the body. - schema: - type: array - items: - $ref: '#/definitions/Subscription' - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). - type: string - 400: - description: | - Bad Request. - Invalid request or validation error. - schema: - $ref: '#/definitions/Error' - 415: - description: | - Unsupported media type. - The entity of the request was in a not supported format. - -###################################################### -# The "Individual Subscription" resource APIs -###################################################### - '/subscriptions/{subscriptionId}': - -#----------------------------------------------------- -# Retrieve a certain subscription -#----------------------------------------------------- - get: - x-scope: apim:subscribe - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" \"https://localhost:9443/api/am/store/v0.12/subscriptions/5b65808c-cdf2-43e1-a695-de63e3ad0ae9\"" - x-wso2-request: | - GET https://localhost:9443/api/am/store/v0.12/subscriptions/5b65808c-cdf2-43e1-a695-de63e3ad0ae9 - Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8 - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"tier\": \"Gold\",\n \"subscriptionId\": \"5b65808c-cdf2-43e1-a695-de63e3ad0ae9\",\n \"apiIdentifier\": \"admin-PhoneVerification-2.0.0\",\n \"applicationId\": \"c30f3a6e-ffa4-4ae7-afce-224d1f820524\",\n \"status\": \"UNBLOCKED\"\n}" - summary: | - Get details of a subscription - description: | - This operation can be used to get details of a single subscription. - parameters: - - $ref: '#/parameters/subscriptionId' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - - $ref: '#/parameters/If-Modified-Since' - tags: - - Subscription (Individual) - responses: - 200: - description: | - OK. - Subscription returned - schema: - $ref: '#/definitions/Subscription' - headers: - Content-Type: - description: The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. Used by caches, or in conditional requests. - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. Used by caches, or in conditional requests (Will be supported in future). - type: string - '304': - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource. - '404': - description: | - Not Found. - Requested Subscription does not exist. - schema: - $ref: '#/definitions/Error' - -#----------------------------------------------------- -# Delete a certain subscription -#----------------------------------------------------- - delete: - x-scope: apim:subscribe - x-wso2-curl: "curl -k -H \"Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8\" -X DELETE \"https://localhost:9443/api/am/store/v0.12/subscriptions/5b65808c-cdf2-43e1-a695-de63e3ad0ae9\"" - x-wso2-request: | - DELETE https://localhost:9443/api/am/store/v0.12/subscriptions/5b65808c-cdf2-43e1-a695-de63e3ad0ae9 - x-wso2-response: "HTTP/1.1 200 OK" - summary: | - Remove a subscription - description: | - This operation can be used to remove a subscription. - parameters: - - $ref: '#/parameters/subscriptionId' - - $ref: '#/parameters/If-Match' - - $ref: '#/parameters/If-Unmodified-Since' - tags: - - Subscription (Individual) - responses: - 200: - description: | - OK. - Resource successfully deleted. - 404: - description: | - Not Found. - Resource to be deleted does not exist. - schema: - $ref: '#/definitions/Error' - 412: - description: | - Precondition Failed. - The request has not been performed because one of the preconditions is not met. - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Tier Collection" resource APIs -###################################################### - /tiers/{tierLevel}: - -#----------------------------------------------------- -# Retrieve the list of all available tiers -#----------------------------------------------------- - get: - x-wso2-curl: "curl \"https://localhost:9443/api/am/store/v0.12/tiers/api\"" - x-wso2-request: | - GET https://localhost:9443/api/am/store/v0.12/tiers/api - x-wso2-curl-tenant: "curl -k -H \"X-WSO2-Tenant:test.com\" https://localhost:9443/api/am/store/v0.12/tiers/api" - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"previous\": \"\",\n \"list\": [\n {\n \"unitTime\": 60000,\n \"tierPlan\": \"FREE\",\n \"stopOnQuotaReach\": true,\n \"tierLevel\": \"api\",\n \"requestCount\": 1,\n \"description\": \"Allows 1 request(s) per minute.\",\n \"name\": \"Bronze\",\n \"attributes\": {}\n },\n {\n \"unitTime\": 60000,\n \"tierPlan\": \"FREE\",\n \"stopOnQuotaReach\": true,\n \"tierLevel\": \"api\",\n \"requestCount\": 20,\n \"description\": \"Allows 20 request(s) per minute.\",\n \"name\": \"Gold\",\n \"attributes\": {}\n },\n {\n \"unitTime\": 60000,\n \"tierPlan\": \"FREE\",\n \"stopOnQuotaReach\": true,\n \"tierLevel\": \"api\",\n \"requestCount\": 5,\n \"description\": \"Allows 5 request(s) per minute.\",\n \"name\": \"Silver\",\n \"attributes\": {}\n },\n {\n \"unitTime\": 0,\n \"tierPlan\": null,\n \"stopOnQuotaReach\": true,\n \"tierLevel\": \"api\",\n \"requestCount\": 0,\n \"description\": \"Allows unlimited requests\",\n \"name\": \"Unlimited\",\n \"attributes\": {}\n }\n ],\n \"count\": 4,\n \"next\": \"\"\n}" - summary: | - Get available tiers - description: | - This operation can be used to retrieve all the tiers available for the provided tier level. Tier level should be specified as a path parameter and should be one of `api` and `application`. - - `X-WSO2-Tenant` header can be used to retrive tiers that belongs to a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used. - - **NOTE**: - * API tiers are the ones that is available during subscription of an application to an API. Hence they are also called subscription tiers and are same as the subscription policies in Admin REST API. - parameters: - - $ref: '#/parameters/limit' - - $ref: '#/parameters/offset' - - $ref: '#/parameters/tierLevel' - - $ref: '#/parameters/requestedTenant' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - tags: - - Throttling Tier (Collection) - responses: - 200: - description: | - OK. - List of tiers returned. - schema: - type: array - items: - $ref: '#/definitions/TierList' - headers: - Content-Type: - description: The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 406: - description: | - Not Acceptable. - The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Individual Tier" resource APIs -###################################################### - '/tiers/{tierLevel}/{tierName}': - -#----------------------------------------------------- -# Retrieve a certain tier -#----------------------------------------------------- - get: - x-wso2-curl: "curl \"https://localhost:9443/api/am/store/v0.12/tiers/api/Bronze\"" - x-wso2-request: | - GET https://localhost:9443/api/am/store/v0.12/tiers/api/Bronze - x-wso2-curl-tenant: "curl -k -H \"X-WSO2-Tenant:test.com\" https://localhost:9443/api/am/store/v0.12/tiers/api/Bronze" - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"unitTime\": 60000,\n \"tierPlan\": \"FREE\",\n \"stopOnQuotaReach\": true,\n \"tierLevel\": \"api\",\n \"requestCount\": 1,\n \"description\": \"Allows 1 request(s) per minute.\",\n \"name\": \"Bronze\",\n \"attributes\": {}\n}" - summary: | - Get details of a tier - description: | - This operation can be used to retrieve details of a single tier by specifying the tier level and tier name. - - `X-WSO2-Tenant` header can be used to retrive tiers that belongs to a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used. - parameters: - - $ref: '#/parameters/tierName' - - $ref: '#/parameters/tierLevel' - - $ref: '#/parameters/requestedTenant' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - - $ref: '#/parameters/If-Modified-Since' - tags: - - Throttling Tier (Individual) - responses: - 200: - description: | - OK. - Tier returned - schema: - $ref: '#/definitions/Tier' - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - Last-Modified: - description: | - Date and time the resource has been modifed the last time. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 404: - description: | - Not Found. - Requested Tier does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. - The requested media type is not supported. - schema: - $ref: '#/definitions/Error' - -###################################################### -# The "Tag Collection" resource API -###################################################### - /tags: - -#----------------------------------------------------- -# Retrieve the list of tags qualifying under a search condition -#----------------------------------------------------- - get: - x-wso2-curl: "curl \"https://localhost:9443/api/am/store/v0.12/tags\"" - x-wso2-request: | - GET https://localhost:9443/api/am/store/v0.12/tags - x-wso2-curl-tenant: "curl -k -H \"X-WSO2-Tenant:test.com\" https://localhost:9443/api/am/store/v0.12/tags" - x-wso2-response: "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\n \"previous\": \"\",\n \"list\": [\n {\n \"weight\": 1,\n \"name\": \"mobile\"\n },\n {\n \"weight\": 1,\n \"name\": \"multimedia\"\n },\n {\n \"weight\": 1,\n \"name\": \"phone\"\n }\n ],\n \"count\": 3,\n \"next\": \"\"\n}" - summary: | - Get all tags - description: | - This operation can be used to retrieve a list of tags that are already added to APIs. - - `X-WSO2-Tenant` header can be used to retrive tags that belongs to a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used. - - **NOTE:** - * This operation does not require an Authorization header by default. But in order to see a restricted API's tags, you need to provide Authorization header. - parameters: - - $ref: '#/parameters/limit' - - $ref: '#/parameters/offset' - - $ref: '#/parameters/requestedTenant' - - $ref: '#/parameters/Accept' - - $ref: '#/parameters/If-None-Match' - tags: - - Tag (Collection) - responses: - 200: - description: | - OK. - Tag list is returned. - schema: - $ref: '#/definitions/TagList' - headers: - Content-Type: - description: | - The content type of the body. - type: string - ETag: - description: | - Entity Tag of the response resource. - Used by caches, or in conditional requests (Will be supported in future). - type: string - 304: - description: | - Not Modified. - Empty body because the client has already the latest version of the requested resource (Will be supported in future). - 404: - description: | - Not Found. Requested API does not exist. - schema: - $ref: '#/definitions/Error' - 406: - description: | - Not Acceptable. The requested media type is not supported - schema: - $ref: '#/definitions/Error' - -###################################################### -# Parameters - required by some of the APIs above -###################################################### -parameters: - -# Requested Tenant domain -# Specified as a header parameter - requestedTenant: - name: X-WSO2-Tenant - in: header - description: | - For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be - retirieved from. - required: false - type: string - -# API Identifier -# Specified as part of the path expression - apiId: - name: apiId - in: path - description: | - **API ID** consisting of the **UUID** of the API. Using the **UUID** in the API call is recommended. - The combination of the provider of the API, name of the API and the version is also accepted as a valid API ID. - Should be formatted as **provider-name-version**. - required: true - type: string - x-encoded: true - -# API Identifier -# Specified as part of the query string - apiId-Q: - name: apiId - in: query - description: | - **API ID** consisting of the **UUID** of the API. Using the **UUID** in the API call is recommended. - The combination of the provider of the API, name of the API and the version is also accepted as a valid API I. - Should be formatted as **provider-name-version**. - required: true - type: string - x-encoded: true - -# API Identifier -# Specified as part of the path expression - language: - name: language - in: query - description: | - Programming language to generate SDK. - required: true - type: string - - -# Document Identifier -# Specified as part of the path expression - documentId: - name: documentId - in: path - description: | - Document Identifier - required: true - type: string - -# Application Identifier -# Specified as part of the path expression - applicationId: - name: applicationId - in: path - description: | - Application Identifier consisting of the UUID of the Application. - required: true - type: string - -# Filter By user roles -# Specified as part of the query string - filterByUserRoles: - name: filterByUserRoles - in: query - description : | - Filter user by roles. - required : false - type: boolean - -# Application Identifier -# Specified as part of the query string - applicationId-Q: - name: applicationId - in: query - description: | - Application Identifier consisting of the UUID of the Application. - required: true - type: string - -# Group Identifier of the application - groupId: - name: groupId - in: query - description: | - Application Group Id - required: false - type: string - -# Subscription Identifier -# Specified as part of the path expression - subscriptionId: - name: subscriptionId - in: path - description: | - Subscription Id - required: true - type: string - -# Tier Name -# Specified as part of the path expression - tierName: - name: tierName - in: path - description: | - Tier name - required: true - type: string - -# Tier Type -# Specified as part of the path expression - tierLevel: - name: tierLevel - in: path - description: | - List API or Application type tiers. - type: string - enum: - - api - - application - required: true - -# Used for pagination: -# The maximum number of resoures to be returned by a GET - limit: - name: limit - in: query - description: | - Maximum length of resource array to return. - default: 25 - type: integer - -# Used for pagination: -# The order number of an instance in a qualified set of resoures -# at which to start to return the next batch of qualified resources - offset: - name: offset - in: query - description: | - Starting point within the complete list of items qualified. - default: 0 - type: integer - -# Application Key Type -# Specified as part of the path expression - keyType: - name: keyType - in: path - description: | - **Application Key Type** standing for the type of the keys (i.e. Production or Sandbox). - required: true - type: string - enum: - - PRODUCTION - - SANDBOX - -# The HTTP Accept header - Accept: - name: Accept - in: header - description: | - Media types acceptable for the response. Default is application/json. - default: application/json - type: string - -# The HTTP Content-Type header - Content-Type: - name: Content-Type - in: header - description: | - Media type of the entity in the body. Default is application/json. - default: application/json - required: true - type : string - -# The HTTP If-None-Match header -# Used to avoid retrieving data that are already cached - If-None-Match: - name: If-None-Match - in: header - description: | - Validator for conditional requests; based on the ETag of the formerly retrieved - variant of the resource. - type : string - -# The HTTP If-Modified-Since header -# Used to avoid retrieving data that are already cached - If-Modified-Since: - name: If-Modified-Since - in: header - description: | - Validator for conditional requests; based on Last Modified header of the - formerly retrieved variant of the resource (Will be supported in future). - type: string - -# The HTTP If-Match header -# Used to avoid concurrent updates - If-Match: - name: If-Match - in: header - description: | - Validator for conditional requests; based on ETag. - type: string - -# The HTTP If-Unmodified-Since header -# Used to avoid concurrent updates - If-Unmodified-Since: - name: If-Unmodified-Since - in: header - description: | - Validator for conditional requests; based on Last Modified header (Will be supported in future). - type: string - -###################################################### -# The resources used by some of the APIs above within the message body -###################################################### -definitions: - -#----------------------------------------------------- -# The API List resource -#----------------------------------------------------- - APIList: - title: API List - properties: - count: - type: integer - description: | - Number of APIs returned. - example: 1 - next: - type: string - description: | - Link to the next subset of resources qualified. - Empty if no more resources are to be returned. - example: "/apis?limit=1&offset=2&query=" - previous: - type: string - description: | - Link to the previous subset of resources qualified. - Empty if current subset is the first subset returned. - example: "/apis?limit=1&offset=0&query=" - list: - type: array - items: - $ref: '#/definitions/APIInfo' - pagination: - properties: - offset: - type: integer - example: 12 - limit: - type: integer - example: 25 - total: - type: integer - example: 1290 -#----------------------------------------------------- -# The API Info resource -#----------------------------------------------------- - APIInfo: - title: API Info object with basic API details. - properties: - id: - type: string - example: 01234567-0123-0123-0123-012345678901 - name: - type: string - example: CalculatorAPI - description: - type: string - example: A calculator API that supports basic operations - context: - type: string - example: CalculatorAPI - version: - type: string - example: 1.0.0 - provider: - description: | - If the provider value is not given, the user invoking the API will be used as the provider. - type: string - example: admin - status: - type: string - example: PUBLISHED - thumbnailUri: - type: string - example: /apis/01234567-0123-0123-0123-012345678901/thumbnail - scopes: - type: array - items: - $ref: '#/definitions/ScopeInfo' -#----------------------------------------------------- -# The API resource -#----------------------------------------------------- - API: - title: API object - required: - - name - - context - - version - - provider - - status - - apiDefinition - properties: - id: - type: string - description: | - UUID of the api registry artifact - example: 01234567-0123-0123-0123-012345678901 - name: - type: string - description: Name of the API - example: CalculatorAPI - description: - type: string - description: A brief description about the API - example: A calculator API that supports basic operations - context: - type: string - description: A string that represents thecontext of the user's request - example: CalculatorAPI - version: - type: string - description: The version of the API - example: 1.0.0 - provider: - description: | - If the provider value is not given user invoking the api will be used as the provider. - type: string - example: admin - apiDefinition: - description: | - Swagger definition of the API which contains details about URI templates and scopes - type: string - example: "{'paths':{'/substract':{'get':{'x-auth-type':'Application & Application User','x-throttling-tier':'Unlimited','parameters':[{'name':'x','required':true,'type':'string','in':'query'},{'name':'y','required':true,'type':'string','in':'query'}],'responses':{'200':{}}}},'/add':{'get':{'x-auth-type':'Application & Application User','x-throttling-tier':'Unlimited','parameters':[{'name':'x','required':true,'type':'string','in':'query'},{'name':'y','required':true,'type':'string','in':'query'}],'responses':{'200':{}}}}},'swagger':'2.0','info':{'title':'CalculatorAPI','version':'1.0.0'}}" - wsdlUri: - description: | - WSDL URL if the API is based on a WSDL endpoint - type: string - example: "http://www.webservicex.com/globalweather.asmx?wsdl" - status: - type: string - description: This describes in which status of the lifecycle the API is. - example: PUBLISHED - isDefaultVersion: - type: boolean - example: false - transport: - type: array - items: - description: | - Supported transports for the API (http and/or https). - type: string - example: ["http","https"] - tags: - type: array - description: Search keywords related to the API - items: - type: string - example: ["substract","add"] - tiers: - type: array - description: The subscription tiers selected for the particular API - items: - type: string - example: ["Unlimited"] - thumbnailUrl: - type: string - example: "" - additionalProperties: - description: | - Custom(user defined) properties of API - type: object - additionalProperties: - type: string - example: {} - endpointURLs: - type: array - items: - properties: - environmentName: - type: string - example: Production and Sandbox - environmentType: - type: string - example: hybrid - environmentURLs: - properties: - http: - type: string - description: HTTP environment URL - example: "http://localhost:8280/phoneverify/1.0.0" - https: - type: string - description: HTTPS environment URL - example: "https://localhost:8243/phoneverify/1.0.0" - businessInformation: - properties: - businessOwner: - type: string - example: businessowner - businessOwnerEmail: - type: string - example: businessowner@wso2.com - technicalOwner: - type: string - example: technicalowner - technicalOwnerEmail: - type: string - example: technicalowner@wso2.com - -#----------------------------------------------------- -# The Application List resource -#----------------------------------------------------- - ApplicationList: - title: Application List - properties: - count: - type: integer - description: | - Number of applications returned. - example: 1 - next: - type: string - description: | - Link to the next subset of resources qualified. - Empty if no more resources are to be returned. - example: "/applications?limit=1&offset=2&groupId=" - previous: - type: string - description: | - Link to the previous subset of resources qualified. - Empty if current subset is the first subset returned. - example: "/applications?limit=1&offset=0&groupId=" - list: - type: array - items: - $ref: '#/definitions/ApplicationInfo' - -#----------------------------------------------------- -# The Application resource -#----------------------------------------------------- - Application: - title: Application - required: - - name - - throttlingTier - properties: - applicationId: - type: string - example: 01234567-0123-0123-0123-012345678901 - name: - type: string - example: CalculatorApp - subscriber: - description: | - If subscriber is not given user invoking the API will be taken as the subscriber. - type: string - example: admin - throttlingTier: - type: string - example: Unlimited - callbackUrl: - type: string - example: "" - description: - type: string - example: Sample calculator application - status: - type: string - example: APPROVED - default: "" - groupId: - type: string - example: "" - keys: - type: array - items: - $ref: '#/definitions/ApplicationKey' - example: [] - -#----------------------------------------------------- -# The Application Info resource -#----------------------------------------------------- - ApplicationInfo: - title: Application info object with basic application details - properties: - applicationId: - type: string - example: 01234567-0123-0123-0123-012345678901 - name: - type: string - example: CalculatorApp - subscriber: - type: string - example: admin - throttlingTier: - type: string - example: Unlimited - description: - type: string - example: Sample calculator application - status: - type: string - example: APPROVED - groupId: - type: string - example: "" - -#----------------------------------------------------- -# The Document List resource -#----------------------------------------------------- - DocumentList: - title: Document List - properties: - count: - type: integer - description: | - Number of Documents returned. - example: 1 - next: - type: string - description: | - Link to the next subset of resources qualified. - Empty if no more resources are to be returned. - example: "/apis/01234567-0123-0123-0123-012345678901/documents?limit=1&offset=2" - previous: - type: string - description: | - Link to the previous subset of resources qualified. - Empty if current subset is the first subset returned. - example: "/apis/01234567-0123-0123-0123-012345678901/documents?limit=1&offset=0" - list: - type: array - items: - $ref: '#/definitions/Document' - -#----------------------------------------------------- -# The Document resource -#----------------------------------------------------- - Document: - title: Document - required: - - name - - type - - sourceType - properties: - documentId: - type: string - example: 01234567-0123-0123-0123-012345678901 - name: - type: string - example: CalculatorDoc - type: - type: string - enum: - - HOWTO - - SAMPLES - - PUBLIC_FORUM - - SUPPORT_FORUM - - API_MESSAGE_FORMAT - - SWAGGER_DOC - - OTHER - example: HOWTO - summary: - type: string - example: "Summary of Calculator Documentation" - sourceType: - type: string - enum: - - INLINE - - URL - - FILE - example: INLINE - sourceUrl: - type: string - example: "" - otherTypeName: - type: string - example: "" - -#----------------------------------------------------- -# The Tier List resource -#----------------------------------------------------- - TierList: - title: Tier List - properties: - count: - type: integer - description: | - Number of Tiers returned. - example: 1 - next: - type: string - description: | - Link to the next subset of resources qualified. - Empty if no more resources are to be returned. - example: "/tiers/api?limit=1&offset=2" - previous: - type: string - description: | - Link to the previous subset of resources qualified. - Empty if current subset is the first subset returned. - example: "/tiers/api?limit=1&offset=0" - list: - type: array - items: - $ref: '#/definitions/Tier' - -#----------------------------------------------------- -# The Tier resource -#----------------------------------------------------- - Tier: - title: Tier - required: - - name - - tierPlan - - requestCount - - unitTime - - stopOnQuotaReach - properties: - name: - type: string - example: Platinum - description: - type: string - example: "Allows 50 request(s) per minute." - tierLevel: - type: string - enum: - - api - - application - example: api - attributes: - description: | - Custom attributes added to the tier policy - type: object - additionalProperties: - type: string - example: {} - requestCount: - description: | - Maximum number of requests which can be sent within a provided unit time - type: integer - format: int64 - example: 50 - unitTime: - type: integer - format: int64 - example: 60000 - tierPlan: - description: | - This attribute declares whether this tier is available under commercial or free - type: string - enum: - - FREE - - COMMERCIAL - example: FREE - stopOnQuotaReach: - description: | - If this attribute is set to false, you are capabale of sending requests - even if the request count exceeded within a unit time - type: boolean - example: true - TierPermissions: - $ref: '#/definitions/TierPermissionInfo' -#----------------------------------------------------- -# The Subscription List resource -#----------------------------------------------------- - SubscriptionList: - title: Subscription List - properties: - count: - type: integer - description: | - Number of Subscriptions returned. - example: 1 - next: - type: string - description: | - Link to the next subset of resources qualified. - Empty if no more resources are to be returned. - example: "/subscriptions?limit=1&offset=2&apiId=01234567-0123-0123-0123-012345678901&groupId=" - previous: - type: string - description: | - Link to the previous subset of resources qualified. - Empty if current subset is the first subset returned. - example: "/subscriptions?limit=1&offset=0&apiId=01234567-0123-0123-0123-012345678901&groupId=" - list: - type: array - items: - $ref: '#/definitions/Subscription' - -#----------------------------------------------------- -# The Subscription resource -#----------------------------------------------------- - Subscription: - title: Subscription - required: - - applicationId - - apiIdentifier - - tier - properties: - subscriptionId: - type: string - description: The UUID of the subscription - example: faae5fcc-cbae-40c4-bf43-89931630d313 - applicationId: - type: string - description: The UUID of the application - example: b3ade481-30b0-4b38-9a67-498a40873a6d - apiIdentifier: - type: string - description: The unique identifier of the API. - example: admin-PizzaShackAPI-1.0.0 - tier: - type: string - example: Unlimited - status: - type: string - enum: - - BLOCKED - - PROD_ONLY_BLOCKED - - UNBLOCKED - - ON_HOLD - - REJECTED - example: UNBLOCKED - - -#----------------------------------------------------- -# The Tag resource -#----------------------------------------------------- - Tag: - title: Tag - required: - - name - - weight - properties: - name: - type: string - example: tag1 - weight: - type: integer - example: 5 - -#----------------------------------------------------- -# The Tag List resource -#----------------------------------------------------- - TagList: - title: Tag List - properties: - count: - type: integer - description: | - Number of Tags returned. - example: 1 - next: - type: string - description: | - Link to the next subset of resources qualified. - Empty if no more resources are to be returned. - example: "/tags?limit=1&offset=2" - previous: - type: string - description: | - Link to the previous subset of resources qualified. - Empty if current subset is the first subset returned. - example: "/tags?limit=1&offset=0" - list: - type: array - items: - $ref: '#/definitions/Tag' - -#----------------------------------------------------- -# The Error resource -#----------------------------------------------------- - Error: - title: Error object returned with 4XX HTTP status - required: - - code - - message - properties: - code: - type: integer - format: int64 - message: - type: string - description: Error message. - description: - type: string - description: | - A detail description about the error message. - moreInfo: - type: string - description: | - Preferably an url with more details about the error. - error: - type: array - description: | - If there are more than one error list them out. - For example, list out validation errors by each field. - items: - $ref: '#/definitions/ErrorListItem' - -#----------------------------------------------------- -# The Error List Item resource -#----------------------------------------------------- - ErrorListItem: - title: Description of Individual errors that may have occurred during a request. - required: - - code - - message - properties: - code: - type: string - message: - type: string - description: | - Description about Individual errors occurred - -#----------------------------------------------------- -# The Token resource -#----------------------------------------------------- - Token : - title: Token details for invoking APIs - properties: - accessToken: - type: string - description: Access token - example: 01234567890123456789012345678901 - tokenScopes: - type: array - items: - type: string - description: Valid scopes for the access token - example: ["default"] - validityTime: - type: integer - format: int64 - description: Maximum validity time for the access token - example: 3600 - -#----------------------------------------------------- -# The Application Key resource -#----------------------------------------------------- - ApplicationKey : - title: Application key details - properties: - consumerKey: - type: string - description: The consumer key associated with the application and identifying the client - example: vYDoc9s7IgAFdkSyNDaswBX7ejoa - consumerSecret: - type: string - description: The client secret that is used to authenticate the client with the authentication server - example: TIDlOFkpzB7WjufO3OJUhy1fsvAa - supportedGrantTypes: - type: array - items: - type: string - description: The grant types that are supported by the application - example: ["client_credentials","password"] - callbackUrl: - type: string - description: Callback URL - example: "http://sample.com/callback/url" - keyState: - type: string - description: Describes the state of the key generation. - example: APPROVED - keyType: - description: Describes to which endpoint the key belongs - type: string - enum: - - PRODUCTION - - SANDBOX - example: PRODUCTION - groupId: - type: string - description: Application group id (if any). - example: 02 - token: - $ref: '#/definitions/Token' - -#----------------------------------------------------- -# The Application Key Generation Request schema -#----------------------------------------------------- - ApplicationKeyGenerateRequest : - title: Application key generation request object - required: - - keyType - - validityTime - - accessAllowDomains - properties: - keyType: - type: string - enum: - - PRODUCTION - - SANDBOX - example: PRODUCTION - validityTime: - type: string - example: 3600 - supportedGrantTypes: - type: array - items: - type: string - description: The grant types that are supported by the application - example: ["client_credentials","password"] - callbackUrl: - type: string - description: Callback URL - example: "" - accessAllowDomains: - type: array - items: - type: string - description: Allowed domains for the access token - example: ["ALL"] - scopes: - type: array - items: - type: string - description: Allowed scopes for the access token - example: ["am_application_scope","default"] - -#----------------------------------------------------- -# Scope Info resource -#----------------------------------------------------- - ScopeInfo: - title: API Scope info object with scope details - properties: - key: - type: string - example: admin_scope - name: - type: string - example: admin scope - roles: - type: array - items: - type: string - description: Allowed roles for the scope - example: ["manager","developer"] - -#----------------------------------------------------- -# Tier Permission Info resource -#----------------------------------------------------- - TierPermissionInfo: - title: Tier Permission info object with tier permission details - properties: - type: - type: string - enum: - - allow - - deny - roles: - type: array - items: - type: string - description: roles for this permission - example: ["manager","developer"] - - ApplicationScope : - title: Scope of the APIs - properties: - key: - type: string - description: Key of scope - example: apim:fileread - name: - type: string - description: Name of the scope - example: apim file read - roles : - type: string - description: Roles scope is bounded to - example : admin, role1 - description: - type: string - description: Description of the scope - - ScopeList : - title : Scope list - properties: - list : - type : array - items: - $ref: '#/definitions/ApplicationScope' - - -#----------------------------------------------------- -# END-OF-FILE -#----------------------------------------------------- \ No newline at end of file diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index a95c177917..6bf36e1e82 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -30,7 +30,7 @@ apimgt-extensions pom WSO2 Carbon - API Management Extensions Component - http://wso2.org + https://entgra.io io.entgra.device.mgt.core.apimgt.webapp.publisher @@ -43,23 +43,4 @@ io.entgra.device.mgt.core.apimgt.extension.rest.api - - - - - org.apache.felix - maven-scr-plugin - 1.7.2 - - - generate-scr-scrdescriptor - - scr - - - - - - - diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/pom.xml b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/pom.xml index 81c0147a52..482bc93ae9 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/pom.xml +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/pom.xml @@ -35,8 +35,12 @@ - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -49,13 +53,23 @@ ${io.entgra.device.mgt.core.version} Application Management Common Bundle - io.entgra.device.mgt.core.device.mgt.common.*;version="${io.entgra.device.mgt.core.version}", - io.entgra.device.mgt.core.device.mgt.core.dto;version="${io.entgra.device.mgt.core.version}", - com.google.gson, - io.swagger.annotations.*;resolution:=optional, - com.fasterxml.jackson.annotation, - javax.validation.constraints, - javax.xml.bind.annotation; version="${javax.xml.bind.imp.pkg.version}", + com.fasterxml.jackson.annotation;version="[2.9,3)", + com.google.gson;version="[2.9,3)", + io.entgra.device.mgt.core.application.mgt.common, + io.entgra.device.mgt.core.application.mgt.common.config, + io.entgra.device.mgt.core.application.mgt.common.dto, + io.entgra.device.mgt.core.application.mgt.common.exception, + io.entgra.device.mgt.core.application.mgt.common.response, + io.entgra.device.mgt.core.application.mgt.common.wrapper, + io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.app.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.operation.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.common.exception;version="[5.0,6)", + io.swagger.annotations;version="[1.6,2)", + javax.validation.constraints;version="[2.0,3)", + javax.xml.bind.annotation;version="[0.0,1)" + + io.entgra.device.mgt.core.application.mgt.common.* @@ -68,16 +82,14 @@ - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.equinox - org.eclipse.equinox.common + org.apache.felix + org.apache.felix.scr.ds-annotations + provided - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api + provided commons-codec.wso2 diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/ApplicationInstallResponse.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/ApplicationInstallResponse.java index c52261a943..c6fd77b7a0 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/ApplicationInstallResponse.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/ApplicationInstallResponse.java @@ -18,9 +18,9 @@ package io.entgra.device.mgt.core.application.mgt.common; -import io.swagger.annotations.ApiModelProperty; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; +import io.swagger.annotations.ApiModelProperty; import java.util.List; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/ApplicationSubscriptionInfo.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/ApplicationSubscriptionInfo.java index 93f002aad1..f2fab0456e 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/ApplicationSubscriptionInfo.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/ApplicationSubscriptionInfo.java @@ -21,7 +21,6 @@ package io.entgra.device.mgt.core.application.mgt.common; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import java.util.ArrayList; import java.util.List; public class ApplicationSubscriptionInfo { diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/DeviceList.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/DeviceList.java index 29c331c51a..4219ecf168 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/DeviceList.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/DeviceList.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.application.mgt.common; import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModelProperty; import io.entgra.device.mgt.core.device.mgt.common.Device; +import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/InstallationDetails.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/InstallationDetails.java index c948c93758..942817ec6f 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/InstallationDetails.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/InstallationDetails.java @@ -17,8 +17,8 @@ */ package io.entgra.device.mgt.core.application.mgt.common; -import io.swagger.annotations.ApiModelProperty; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.swagger.annotations.ApiModelProperty; import java.util.List; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/LifecycleState.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/LifecycleState.java index c3091f678d..53c839c6d8 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/LifecycleState.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/LifecycleState.java @@ -17,10 +17,10 @@ */ package io.entgra.device.mgt.core.application.mgt.common; -import java.sql.Timestamp; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import java.sql.Timestamp; import java.util.List; @ApiModel(value = "LifecycleState", description = "LifecycleState represents the Lifecycle state for an application release") @@ -45,8 +45,8 @@ public class LifecycleState { private String updatedBy; @ApiModelProperty(name = "updatedAt", - value = "Timestamp of the lifecycle has been updated") - private Timestamp updatedAt; + value = "The seconds from the epoch of 1970-01-01T00:00:00Z that the lifecycle has been updated") + private Long updatedAt; @ApiModelProperty(name = "reasonForChange", value = "Reason for the application release lifecycle change from previous state to current state.") @@ -76,11 +76,11 @@ public class LifecycleState { this.updatedBy = updatedBy; } - public Timestamp getUpdatedAt() { + public Long getUpdatedAt() { return updatedAt; } - public void setUpdatedAt(Timestamp updatedAt) { + public void setUpdatedAt(Long updatedAt) { this.updatedAt = updatedAt; } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/ReleaseVersionInfo.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/ReleaseVersionInfo.java new file mode 100644 index 0000000000..e1e7548d68 --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/ReleaseVersionInfo.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.application.mgt.common; + +public class ReleaseVersionInfo { + private String version; + private String releaseType; + private double rating; + private String state; + private String uuid; + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getReleaseType() { + return releaseType; + } + + public double getRating() { + return rating; + } + + public void setRating(double rating) { + this.rating = rating; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public void setReleaseType(String releaseType) { + this.releaseType = releaseType; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/ScheduledSubscriptionDTO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/ScheduledSubscriptionDTO.java index 1bd612d63a..8aaeb22770 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/ScheduledSubscriptionDTO.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/ScheduledSubscriptionDTO.java @@ -20,8 +20,8 @@ package io.entgra.device.mgt.core.application.mgt.common.dto; import com.google.gson.Gson; import io.entgra.device.mgt.core.application.mgt.common.ExecutionStatus; -import io.entgra.device.mgt.core.application.mgt.common.SubscriptionType; import io.entgra.device.mgt.core.application.mgt.common.SubAction; +import io.entgra.device.mgt.core.application.mgt.common.SubscriptionType; import io.entgra.device.mgt.core.application.mgt.common.response.ApplicationRelease; import java.util.List; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java index 7e13353980..b0356161c6 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.application.mgt.common.services; import io.entgra.device.mgt.core.application.mgt.common.ApplicationType; +import io.entgra.device.mgt.core.application.mgt.common.ReleaseVersionInfo; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; import io.entgra.device.mgt.core.application.mgt.common.exception.RequestValidatingException; import io.entgra.device.mgt.core.application.mgt.common.exception.ResourceManagementException; @@ -28,7 +29,6 @@ import io.entgra.device.mgt.core.application.mgt.common.response.Tag; import io.entgra.device.mgt.core.device.mgt.common.Base64File; import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import io.entgra.device.mgt.core.application.mgt.common.ApplicationArtifact; import io.entgra.device.mgt.core.application.mgt.common.LifecycleChanger; @@ -548,18 +548,26 @@ public interface ApplicationManager { void deleteApplicationDataOfTenant(int tenantId) throws ApplicationManagementException; /** - * Delete all application related data of a tenant by tenant Domain + * Delete all application related data of a tenant by tenant Id * - * @param tenantDomain Domain of the Tenant + * @param tenantId Id of the Tenant * @throws ApplicationManagementException thrown if an error occurs when deleting data */ - void deleteApplicationDataByTenantDomain(String tenantDomain) throws ApplicationManagementException; + void deleteApplicationDataByTenantId(int tenantId) throws ApplicationManagementException; /** - * Delete all Application artifacts related to a tenant by Tenant Domain + * Delete all Application artifacts related to a tenant by Tenant Id * - * @param tenantDomain Domain of the Tenant + * @param tenantId Id of the Tenant * @throws ApplicationManagementException thrown if an error occurs when deleting app folders */ - void deleteApplicationArtifactsByTenantDomain(String tenantDomain) throws ApplicationManagementException; + void deleteApplicationArtifactsByTenantId(int tenantId) throws ApplicationManagementException; + + /** + * Extract and retrieve application release version data for a given UUID + * @param uuid UUID of the application + * @return List of {@link ReleaseVersionInfo} + * @throws ApplicationManagementException throws when error encountered while retrieving data + */ + List getApplicationReleaseVersions(String uuid) throws ApplicationManagementException; } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ReviewManager.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ReviewManager.java index 756424275d..c354afa513 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ReviewManager.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ReviewManager.java @@ -17,12 +17,12 @@ */ package io.entgra.device.mgt.core.application.mgt.common.services; -import io.entgra.device.mgt.core.application.mgt.common.Rating; -import io.entgra.device.mgt.core.application.mgt.common.response.Review; import io.entgra.device.mgt.core.application.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.application.mgt.common.PaginationResult; +import io.entgra.device.mgt.core.application.mgt.common.Rating; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; import io.entgra.device.mgt.core.application.mgt.common.exception.ReviewManagementException; +import io.entgra.device.mgt.core.application.mgt.common.response.Review; import io.entgra.device.mgt.core.application.mgt.common.wrapper.ReviewWrapper; /** diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/SubscriptionManager.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/SubscriptionManager.java index 1e70f1b9d6..fd16e70872 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/SubscriptionManager.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/SubscriptionManager.java @@ -187,11 +187,14 @@ public interface SubscriptionManager { * @param subType subscription type of the application. * @param offsetValue offset value for get paginated request. * @param limitValue limit value for get paginated request. + * @param uninstalled a Boolean flag indicating the filter criteria for retrieve subscription data + * @param searchName an optional search term to filter the results by name. If null or empty, no filtering by name is applied. * @return {@link PaginationResult} pagination result of the category details. * @throws {@link ApplicationManagementException} Exception of the application management */ PaginationResult getAppInstalledSubscribers(int offsetValue, int limitValue, String appUUID, - String subType) throws ApplicationManagementException; + String subType, Boolean uninstalled, String searchName) + throws ApplicationManagementException; /** * This method is responsible to provide application subscription data for given application release UUID. diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml index e275391342..171fa4557d 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml @@ -35,8 +35,12 @@ - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -50,41 +54,91 @@ Application Management Core Bundle io.entgra.device.mgt.core.application.mgt.core.internal + com.dd.plist;version="[1.21,2)", + com.google.gson;version="[2.9,3)", + com.google.gson.reflect;version="[2.9,3)", + io.entgra.device.mgt.core.apimgt.application.extension;version="[5.0,6)", + io.entgra.device.mgt.core.apimgt.application.extension.dto;version="[5.0,6)", + io.entgra.device.mgt.core.apimgt.application.extension.exception;version="[5.0,6)", + io.entgra.device.mgt.core.application.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.application.mgt.common.config;version="[5.0,6)", + io.entgra.device.mgt.core.application.mgt.common.dto;version="[5.0,6)", + io.entgra.device.mgt.core.application.mgt.common.exception;version="[5.0,6)", + io.entgra.device.mgt.core.application.mgt.common.response;version="[5.0,6)", + io.entgra.device.mgt.core.application.mgt.common.services;version="[5.0,6)", + io.entgra.device.mgt.core.application.mgt.common.wrapper;version="[5.0,6)", + io.entgra.device.mgt.core.application.mgt.core.config, + io.entgra.device.mgt.core.application.mgt.core.dao, + io.entgra.device.mgt.core.application.mgt.core.dao.common, + io.entgra.device.mgt.core.application.mgt.core.dao.impl, + io.entgra.device.mgt.core.application.mgt.core.dao.impl.application, + io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.release, + io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.spapplication, + io.entgra.device.mgt.core.application.mgt.core.dao.impl.lifecyclestate, + io.entgra.device.mgt.core.application.mgt.core.dao.impl.review, + io.entgra.device.mgt.core.application.mgt.core.dao.impl.subscription, + io.entgra.device.mgt.core.application.mgt.core.dao.impl.visibility, + io.entgra.device.mgt.core.application.mgt.core.exception, + io.entgra.device.mgt.core.application.mgt.core.serviceprovider, + io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.app.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.app.mgt.android;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.exceptions;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.group.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.operation.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.permission.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.common.exception;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.common.util;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.dto;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.operation.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.permission.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.service;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.task.impl;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.util;version="[5.0,6)", + io.entgra.device.mgt.core.identity.jwt.client.extension;version="[5.0,6)", + io.entgra.device.mgt.core.identity.jwt.client.extension.dto;version="[5.0,6)", + io.entgra.device.mgt.core.identity.jwt.client.extension.exception;version="[5.0,6)", + io.entgra.device.mgt.core.identity.jwt.client.extension.service;version="[5.0,6)", + javax.annotation;version="[1.0,2)", + javax.naming, + javax.sql, + + javax.xml.bind;version="[0.0,1)", + javax.xml.bind.annotation;version="[0.0,1)", + javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}", + org.apache.commons.codec.digest;version="[1.4,2)", + org.apache.commons.httpclient;version="[3.1,4)", + org.apache.commons.httpclient.methods;version="[3.1,4)", + org.apache.commons.io;version="[2.4,3)", + org.apache.commons.lang;version="[2.6,3)", + org.apache.commons.lang3;version="[3.12,4)", + org.apache.commons.logging;version="[1.2,2)", + org.apache.commons.validator.routines;version="[1.7,2)", + + org.apache.http;version="[4.4,5)", + org.apache.http.client;version="[4.3,5)", + org.apache.http.client.methods;version="[4.3,5)", + org.apache.http.impl.client;version="[4.3,5)", + org.bouncycastle.cert, + org.bouncycastle.cert.jcajce, + org.bouncycastle.cms, + org.bouncycastle.jce.provider;version="[1.70,2)", + org.bouncycastle.util;version="[1.70,2)", + org.json;version="[3.0,4)", org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.apache.commons.logging, - javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, - org.wso2.carbon.context.*, - org.wso2.carbon.utils.*, - org.w3c.dom, - org.json, - javax.sql, - com.google.gson.*, - javax.naming, - javax.xml.bind.annotation; version="${javax.xml.bind.imp.pkg.version}", - javax.xml.bind; version="${javax.xml.bind.imp.pkg.version}", - io.entgra.device.mgt.core.application.mgt.common.*, - io.entgra.device.mgt.core.device.mgt.core.*, - io.entgra.device.mgt.core.device.mgt.common.*, - org.wso2.carbon.user.core.*, - org.wso2.carbon.user.api.*, - org.wso2.carbon.ntask.*, - org.quartz.*, - org.wso2.carbon.ndatasource.core, - org.wso2.carbon, + org.quartz;version="[2.1,3)", + org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.ndatasource.core;version="[4.8,5)", + org.wso2.carbon.ntask.common;version="[4.9,5)", + org.wso2.carbon.ntask.core;version="[4.9,5)", + org.wso2.carbon.ntask.core.service;version="[4.9,5)", + org.wso2.carbon.user.api;version="[1.0,2)", + org.wso2.carbon.user.core.service;version="[4.8,5)", + org.wso2.carbon.utils;version="[4.8,5)", + org.wso2.carbon.utils.dbcreator;version="[4.8,5)", org.xml.sax, - org.xml.sax.helpers, - org.apache.commons.io, - org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}", - org.apache.commons.codec.digest;version="${commons-codec.wso2.osgi.version.range}", - org.wso2.carbon.base, - com.dd.*, - io.entgra.device.mgt.core.identity.jwt.client.extension.*, - io.entgra.device.mgt.core.apimgt.application.extension.*, - io.entgra.device.mgt.core.tenant.mgt.common.*, - org.apache.commons.httpclient, - org.apache.commons.httpclient.methods, - org.apache.commons.validator.routines + org.xml.sax.helpers apk-parser;scope=compile|runtime;inline=false @@ -98,8 +152,11 @@ org.apache.maven.plugins maven-surefire-plugin - 2.18 + + --add-opens=java.xml/jdk.xml.internal=ALL-UNNAMED + --add-opens=java.base/jdk.internal.loader=ALL-UNNAMED + src/test/resources/testng.xml @@ -110,6 +167,9 @@ 8280 test + + org.ops4j.pax.logging + @@ -117,20 +177,13 @@ - org.apache.httpcomponents - httpclient - - - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services + org.apache.httpcomponents.client5 + httpclient5 - org.eclipse.equinox - org.eclipse.equinox.common + org.apache.felix + org.apache.felix.scr.ds-annotations + provided org.testng @@ -142,8 +195,9 @@ test - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api + provided org.wso2.carbon @@ -238,7 +292,6 @@ commons-validator commons-validator - 1.6 commons-collections @@ -254,40 +307,35 @@ cglib cglib-nodep - 3.2.7 compile - org.apache.tomcat.wso2 + org.wso2.orbit.org.apache.tomcat jdbc-pool mysql mysql-connector-java - 5.1.34 test xerces.wso2 xercesImpl - 2.8.1.wso2v2 test - com.h2database.wso2 - h2-database-engine + org.wso2.orbit.com.h2database + h2 test commons-dbcp.wso2 commons-dbcp - 1.4.0.wso2v1 test commons-pool.wso2 commons-pool - 1.5.6.wso2v1 test @@ -370,6 +418,10 @@ org.wso2.carbon.ntask.core provided + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.notification.logger + com.squareup.okhttp3 okhttp @@ -384,15 +436,12 @@ com.squareup.okio okio + ${okio.version} - org.wso2.carbon.multitenancy - org.wso2.carbon.tenant.mgt - compile - - - io.entgra.device.mgt.core - io.entgra.device.mgt.core.tenant.mgt.common + org.wso2.orbit.javax.xml.bind + jaxb-api + provided diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/config/Configuration.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/config/Configuration.java index b5efa7f99f..6d7c84476b 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/config/Configuration.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/config/Configuration.java @@ -17,14 +17,14 @@ */ package io.entgra.device.mgt.core.application.mgt.core.config; +import io.entgra.device.mgt.core.application.mgt.common.config.LifecycleState; import io.entgra.device.mgt.core.application.mgt.common.config.MDMConfig; import io.entgra.device.mgt.core.application.mgt.common.config.RatingConfiguration; -import io.entgra.device.mgt.core.application.mgt.common.config.LifecycleState; -import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; /** * Represents the Application Management Configuration. diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/config/ConfigurationManager.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/config/ConfigurationManager.java index 77b75deeab..9b7e56caba 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/config/ConfigurationManager.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/config/ConfigurationManager.java @@ -17,15 +17,15 @@ */ package io.entgra.device.mgt.core.application.mgt.core.config; +import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; +import io.entgra.device.mgt.core.application.mgt.common.exception.InvalidConfigurationException; import io.entgra.device.mgt.core.application.mgt.core.util.Constants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; -import io.entgra.device.mgt.core.application.mgt.common.exception.InvalidConfigurationException; -import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; +import java.io.File; /** * ConfigurationManager is responsible for the managing Application Management related configurations. diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/config/Extension.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/config/Extension.java index 553ee67172..3436fc04fb 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/config/Extension.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/config/Extension.java @@ -17,11 +17,11 @@ */ package io.entgra.device.mgt.core.application.mgt.core.config; -import java.util.List; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; /** * Represents a extension in the application management configuration. diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationDAO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationDAO.java index 3d460fb4db..b86747c207 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationDAO.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationDAO.java @@ -17,7 +17,8 @@ */ package io.entgra.device.mgt.core.application.mgt.core.dao; -import io.entgra.device.mgt.core.application.mgt.common.*; +import io.entgra.device.mgt.core.application.mgt.common.Filter; +import io.entgra.device.mgt.core.application.mgt.common.ReleaseVersionInfo; import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.CategoryDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.TagDTO; @@ -286,4 +287,6 @@ public interface ApplicationDAO { * @throws ApplicationManagementDAOException thrown if an error occurs while deleting data */ void deleteApplicationsByTenant(int tenantId) throws ApplicationManagementDAOException; + + List getApplicationReleaseVersions(String uuid, int tenantId) throws ApplicationManagementDAOException; } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationReleaseDAO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationReleaseDAO.java index 8314388798..558bf2821f 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationReleaseDAO.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationReleaseDAO.java @@ -17,8 +17,8 @@ */ package io.entgra.device.mgt.core.application.mgt.core.dao; -import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO; import io.entgra.device.mgt.core.application.mgt.common.Rating; +import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO; import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; import java.util.List; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ReviewDAO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ReviewDAO.java index 8fcc3abb54..9fc8994f5e 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ReviewDAO.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ReviewDAO.java @@ -17,10 +17,9 @@ */ package io.entgra.device.mgt.core.application.mgt.core.dao; -import io.entgra.device.mgt.core.application.mgt.common.response.Review; import io.entgra.device.mgt.core.application.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.application.mgt.common.dto.ReviewDTO; -import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; +import io.entgra.device.mgt.core.application.mgt.common.response.Review; import io.entgra.device.mgt.core.application.mgt.core.exception.ReviewManagementDAOException; import java.util.List; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SPApplicationDAO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SPApplicationDAO.java index aa84543e6f..d26405203e 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SPApplicationDAO.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SPApplicationDAO.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.application.mgt.core.dao; -import io.entgra.device.mgt.core.application.mgt.common.dto.IdentityServerDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.IdentityServerDTO; import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; import java.util.List; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SubscriptionDAO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SubscriptionDAO.java index c35c4a5251..cd1755fc21 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SubscriptionDAO.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SubscriptionDAO.java @@ -198,14 +198,33 @@ public interface SubscriptionDAO { * @param offsetValue offset value for get paginated result * @param limitValue limit value for get paginated result * @param appReleaseId id of the application release. + * @param uninstalled a Boolean flag indicating the filter criteria for getting users: + * - `true` to get only unsubscribed users, + * - `false` to get only subscribed users, + * - `null` to get all users regardless of their unsubscription status. + * @param searchName an optional search term to filter the results by username. * @return subscribedUsers - list of app subscribed users. * @throws {@link ApplicationManagementDAOException} if connections establishment fails. */ List getAppSubscribedUsers(int offsetValue, int limitValue, int appReleaseId, - int tenantId) + int tenantId, Boolean uninstalled, String searchName) throws ApplicationManagementDAOException; - int getSubscribedUserCount(int appReleaseId, int tenantId) throws ApplicationManagementDAOException; + /** + * This method is used to get the count of users who are subscribed or unsubscribed to a specific application release. + * + * @param appReleaseId the ID of the application release for which the user count is to be retrieved. + * @param tenantId the ID of the current tenant. + * @param uninstalled a Boolean flag indicating the filter criteria for counting users: + * - `true` to count only unsubscribed users, + * - `false` to count only subscribed users, + * - `null` to count all users regardless of their unsubscription status. + * @param searchName an optional search term to filter the results by username. + * @return the count of users based on the specified criteria. + * @throws ApplicationManagementDAOException if an error occurs while establishing a database connection or executing the query. + */ + int getSubscribedUserCount(int appReleaseId, int tenantId, Boolean uninstalled, String searchName) + throws ApplicationManagementDAOException; /** * This method is used to get the details of roles @@ -214,14 +233,34 @@ public interface SubscriptionDAO { * @param offsetValue offset value for get paginated request. * @param limitValue limit value for get paginated request. * @param appReleaseId id of the application release. + * @param uninstalled a Boolean flag indicating the filter criteria for getting roles: + * - `true` to get only unsubscribed roles, + * - `false` to get only subscribed roles, + * - `null` to get all roles regardless of their unsubscription status. + * @param searchName an optional search term to filter the results by role name. * @return subscribedRoles - list of app subscribed roles. * @throws {@link ApplicationManagementDAOException} if connections establishment fails. */ List getAppSubscribedRoles(int offsetValue, int limitValue, int appReleaseId, - int tenantId) + int tenantId, Boolean uninstalled, String searchName) throws ApplicationManagementDAOException; - int getSubscribedRoleCount(int appReleaseId, int tenantId) throws ApplicationManagementDAOException; + /** + * This method retrieves the count of roles subscribed to a given application release. + * The count can be filtered based on the unsubscription status. + * + * @param appReleaseId the ID of the application release for which the subscribed roles are counted. + * @param tenantId the ID of the current tenant. + * @param uninstalled a Boolean flag indicating the filter criteria for counting roles: + * - `true` to count only unsubscribed roles, + * - `false` to count only subscribed roles, + * - `null` to count all roles regardless of their unsubscription status. + * @param searchName an optional search term to filter the results by role name. + * @return the count of roles that match the specified criteria. + * @throws ApplicationManagementDAOException if there is an error while accessing the database or processing the request. + */ + int getSubscribedRoleCount(int appReleaseId, int tenantId, Boolean uninstalled, String searchName) + throws ApplicationManagementDAOException; /** * This method is used to get the details of subscribed groups @@ -230,13 +269,33 @@ public interface SubscriptionDAO { * @param offsetValue offset value for get paginated request. * @param limitValue limit value for get paginated request. * @param appReleaseId id of the application release. + * @param uninstalled a Boolean flag indicating the filter criteria for getting groups: + * - `true` to get only unsubscribed groups, + * - `false` to get only subscribed groups, + * - `null` to get all groups regardless of their unsubscription status. + * @param searchName an optional search term to filter the results by group name. * @return subscribedGroups - list of app subscribed groups. * @throws {@link ApplicationManagementDAOException} if connections establishment fails. */ - List getAppSubscribedGroups(int offsetValue, int limitValue, int appReleaseId, int tenantId) + List getAppSubscribedGroups(int offsetValue, int limitValue, int appReleaseId, int tenantId, + Boolean uninstalled, String searchName) throws ApplicationManagementDAOException; - int getSubscribedGroupCount(int appReleaseId, int tenantId) throws ApplicationManagementDAOException; + /** + * This method is used to get the count of subscribed groups + * + * @param tenantId id of the current tenant + * @param appReleaseId id of the application release. + * @param uninstalled a Boolean flag indicating the filter criteria for counting groups: + * - `true` to count only unsubscribed groups, + * - `false` to count only subscribed groups, + * - `null` to count all groups regardless of their unsubscription status. + * @param searchName an optional search term to filter the results by group name. + * @return subscribedGroups - list of app subscribed groups. + * @throws {@link ApplicationManagementDAOException} if connections establishment fails. + */ + int getSubscribedGroupCount(int appReleaseId, int tenantId,Boolean uninstalled, String searchName) + throws ApplicationManagementDAOException; /** * This method is used to get the details of subscribed groups diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java index 86b7407378..c99a06eeb4 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java @@ -17,8 +17,16 @@ */ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.application; +import io.entgra.device.mgt.core.application.mgt.common.AppLifecycleState; +import io.entgra.device.mgt.core.application.mgt.common.Filter; +import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.CategoryDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.TagDTO; +import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; +import io.entgra.device.mgt.core.application.mgt.common.ReleaseVersionInfo; import io.entgra.device.mgt.core.application.mgt.core.dao.ApplicationDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.AbstractDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException; import io.entgra.device.mgt.core.application.mgt.core.util.Constants; import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; @@ -26,19 +34,8 @@ import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.application.mgt.common.AppLifecycleState; -import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; -import io.entgra.device.mgt.core.application.mgt.common.dto.CategoryDTO; -import io.entgra.device.mgt.core.application.mgt.common.Filter; -import io.entgra.device.mgt.core.application.mgt.common.dto.TagDTO; -import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; -import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; +import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.StringJoiner; @@ -2053,4 +2050,50 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic } } + @Override + public List getApplicationReleaseVersions(String uuid, int tenantId) throws ApplicationManagementDAOException { + List releaseVersionInfos = new ArrayList<>(); + String sql = "SELECT VERSION, " + + "RELEASE_TYPE, " + + "RATING, " + + "CURRENT_STATE, " + + "UUID FROM " + + "AP_APP_RELEASE WHERE " + + "AP_APP_ID=" + + "(SELECT AP_APP_ID " + + "FROM AP_APP_RELEASE " + + "WHERE UUID = ? " + + "AND TENANT_ID = ?)"; + try { + Connection connection = getDBConnection(); + try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { + preparedStatement.setString(1, uuid); + preparedStatement.setInt(2, tenantId); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + ReleaseVersionInfo releaseVersionInfo; + while(resultSet.next()) { + releaseVersionInfo = new ReleaseVersionInfo(); + releaseVersionInfo.setVersion(resultSet.getString("VERSION")); + releaseVersionInfo.setReleaseType(resultSet.getString("RELEASE_TYPE")); + releaseVersionInfo.setRating(resultSet.getDouble("RATING")); + releaseVersionInfo.setState(resultSet.getString("CURRENT_STATE")); + releaseVersionInfo.setUuid(resultSet.getString("UUID")); + releaseVersionInfos.add(releaseVersionInfo); + } + } + } + } catch (DBConnectionException e) { + String msg = "Error encountered while acquiring database connection to get available release versions for " + + "UUID : " + uuid ; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "SQL error occurred while getting available release versions for : " + uuid + + "Executed query : [" + sql + "]"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + return releaseVersionInfos; + } + } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/OracleApplicationDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/OracleApplicationDAOImpl.java index 2a9796bfd3..2be1528037 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/OracleApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/OracleApplicationDAOImpl.java @@ -18,15 +18,15 @@ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.application; +import io.entgra.device.mgt.core.application.mgt.common.Filter; +import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; +import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; +import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; import io.entgra.device.mgt.core.application.mgt.core.util.Constants; import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.application.mgt.common.Filter; -import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; -import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; -import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java index ce912f5dc4..95e7f7e54f 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java @@ -18,15 +18,15 @@ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.application; +import io.entgra.device.mgt.core.application.mgt.common.Filter; +import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; +import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; +import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; import io.entgra.device.mgt.core.application.mgt.core.util.Constants; import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.application.mgt.common.Filter; -import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; -import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; -import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java index 70ad2f4e17..95b7c8584c 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java @@ -18,22 +18,19 @@ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.release; -import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO; import io.entgra.device.mgt.core.application.mgt.common.Rating; +import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; import io.entgra.device.mgt.core.application.mgt.core.dao.ApplicationReleaseDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.AbstractDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; +import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; +import java.sql.*; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.StringJoiner; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/release/OracleApplicationReleaseDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/release/OracleApplicationReleaseDAOImpl.java index c772a2baad..37a2c757db 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/release/OracleApplicationReleaseDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/release/OracleApplicationReleaseDAOImpl.java @@ -18,10 +18,10 @@ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.release; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/release/SQLServerApplicationReleaseDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/release/SQLServerApplicationReleaseDAOImpl.java index 9ef21c12e8..7a6a9b1d5b 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/release/SQLServerApplicationReleaseDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/release/SQLServerApplicationReleaseDAOImpl.java @@ -18,10 +18,10 @@ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.release; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java index 0b4d14073b..b3f0eb9f56 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.spapplication; -import io.entgra.device.mgt.core.application.mgt.common.dto.IdentityServerDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.IdentityServerDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; import io.entgra.device.mgt.core.application.mgt.core.dao.SPApplicationDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.AbstractDAOImpl; @@ -30,11 +30,7 @@ import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; +import java.sql.*; import java.util.List; public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPApplicationDAO { diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java index 993e9476f4..76269cbf89 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.spapplication; -import io.entgra.device.mgt.core.application.mgt.common.dto.IdentityServerDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.IdentityServerDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; import io.entgra.device.mgt.core.application.mgt.core.dao.SPApplicationDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.AbstractDAOImpl; @@ -28,11 +28,8 @@ import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServer import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; + +import java.sql.*; import java.util.List; public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPApplicationDAO { diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java index bc1fc660e9..d842868d31 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.spapplication; -import io.entgra.device.mgt.core.application.mgt.common.dto.IdentityServerDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.IdentityServerDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; import io.entgra.device.mgt.core.application.mgt.core.dao.SPApplicationDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.AbstractDAOImpl; @@ -28,11 +28,8 @@ import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServer import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; + +import java.sql.*; import java.util.List; public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements SPApplicationDAO { diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java index 5b6b2571ab..428f4dc393 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.spapplication; -import io.entgra.device.mgt.core.application.mgt.common.dto.IdentityServerDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.IdentityServerDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; import io.entgra.device.mgt.core.application.mgt.core.dao.SPApplicationDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.AbstractDAOImpl; @@ -28,11 +28,8 @@ import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServer import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; + +import java.sql.*; import java.util.List; public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements SPApplicationDAO { diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/lifecyclestate/GenericLifecycleStateDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/lifecyclestate/GenericLifecycleStateDAOImpl.java index c32afcd79a..f491a5a657 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/lifecyclestate/GenericLifecycleStateDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/lifecyclestate/GenericLifecycleStateDAOImpl.java @@ -17,21 +17,17 @@ */ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.lifecyclestate; -import io.entgra.device.mgt.core.application.mgt.core.dao.impl.AbstractDAOImpl; -import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.application.mgt.common.AppLifecycleState; import io.entgra.device.mgt.core.application.mgt.common.LifecycleState; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; import io.entgra.device.mgt.core.application.mgt.core.dao.LifecycleStateDAO; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.AbstractDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.exception.LifeCycleManagementDAOException; +import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; +import java.sql.*; import java.util.ArrayList; import java.util.List; @@ -278,7 +274,7 @@ public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements Lif lifecycleState = new LifecycleState(); lifecycleState.setCurrentState(rs.getString("CURRENT_STATE")); lifecycleState.setPreviousState(rs.getString("PREVIOUS_STATE")); - lifecycleState.setUpdatedAt(new Timestamp(rs.getLong("UPDATED_AT"))); + lifecycleState.setUpdatedAt(rs.getLong("UPDATED_AT")); lifecycleState.setUpdatedBy(rs.getString("UPDATED_BY")); } } catch (SQLException e) { @@ -304,7 +300,7 @@ public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements Lif LifecycleState lifecycleState = new LifecycleState(); lifecycleState.setCurrentState(rs.getString("CURRENT_STATE")); lifecycleState.setPreviousState(rs.getString("PREVIOUS_STATE")); - lifecycleState.setUpdatedAt(new Timestamp(rs.getLong("UPDATED_AT") * 1000L)); + lifecycleState.setUpdatedAt(rs.getLong("UPDATED_AT")); lifecycleState.setUpdatedBy(rs.getString("UPDATED_BY")); lifecycleStates.add(lifecycleState); } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/review/GenericReviewDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/review/GenericReviewDAOImpl.java index e31db113ef..5f1cd06dc2 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/review/GenericReviewDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/review/GenericReviewDAOImpl.java @@ -17,24 +17,19 @@ */ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.review; -import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException; -import io.entgra.device.mgt.core.application.mgt.core.util.Constants; -import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - import io.entgra.device.mgt.core.application.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.application.mgt.common.dto.ReviewDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; import io.entgra.device.mgt.core.application.mgt.core.dao.ReviewDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.AbstractDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.exception.ReviewManagementDAOException; +import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException; +import io.entgra.device.mgt.core.application.mgt.core.util.Constants; +import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; -import java.sql.SQLException; -import java.sql.ResultSet; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.Timestamp; +import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.StringJoiner; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/review/OracleReviewDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/review/OracleReviewDAOImpl.java index 162e57a101..7f8d2dbaf6 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/review/OracleReviewDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/review/OracleReviewDAOImpl.java @@ -18,14 +18,14 @@ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.review; -import io.entgra.device.mgt.core.application.mgt.core.util.Constants; -import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.application.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.application.mgt.common.dto.ReviewDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; import io.entgra.device.mgt.core.application.mgt.core.exception.ReviewManagementDAOException; +import io.entgra.device.mgt.core.application.mgt.core.util.Constants; +import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/review/SQLServerReviewDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/review/SQLServerReviewDAOImpl.java index 5a40b11b07..990eea30b3 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/review/SQLServerReviewDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/review/SQLServerReviewDAOImpl.java @@ -18,14 +18,14 @@ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.review; -import io.entgra.device.mgt.core.application.mgt.core.util.Constants; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.application.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.application.mgt.common.dto.ReviewDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; import io.entgra.device.mgt.core.application.mgt.core.exception.ReviewManagementDAOException; +import io.entgra.device.mgt.core.application.mgt.core.util.Constants; import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java index c80e10d064..a5701cfdfb 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java @@ -967,25 +967,37 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc @Override public List getAppSubscribedUsers(int offsetValue, int limitValue, int appReleaseId, - int tenantId) + int tenantId, Boolean uninstalled, String searchName) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { - log.debug("Request received in DAO Layer to get already subscribed users for " + - "given app release id."); + log.debug("Request received in DAO Layer to get subscribed/unsubscribed users for the given app release ID."); } try { Connection conn = this.getDBConnection(); List subscribedUsers = new ArrayList<>(); - String sql = "SELECT " - + "US.USER_NAME AS USER_NAME " - + "FROM AP_USER_SUBSCRIPTION US " - + "WHERE " - + "AP_APP_RELEASE_ID = ? AND TENANT_ID = ? LIMIT ? OFFSET ?"; + String sql = "SELECT US.USER_NAME AS USER_NAME " + + "FROM AP_USER_SUBSCRIPTION US " + + "WHERE AP_APP_RELEASE_ID = ? " + + "AND TENANT_ID = ? "; + if (uninstalled != null) { + sql += "AND UNSUBSCRIBED = ? "; + } + if (searchName != null && !searchName.trim().isEmpty()) { + sql += "AND US.USER_NAME LIKE ? "; + } + sql += "LIMIT ? OFFSET ?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setInt(1, appReleaseId); - stmt.setInt(2, tenantId); - stmt.setInt(3, limitValue); - stmt.setInt(4, offsetValue); + int index = 1; + stmt.setInt(index++, appReleaseId); + stmt.setInt(index++, tenantId); + if (uninstalled != null) { + stmt.setBoolean(index++, uninstalled); + } + if (searchName != null && !searchName.trim().isEmpty()) { + stmt.setString(index++, "%" + searchName + "%"); + } + stmt.setInt(index++, limitValue); + stmt.setInt(index, offsetValue); try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { subscribedUsers.add(rs.getString("USER_NAME")); @@ -994,50 +1006,62 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc return subscribedUsers; } } catch (DBConnectionException e) { - String msg = "Error occurred while obtaining the DB connection to get already " + - "subscribed users for given app release id."; + String msg = "Error occurred while obtaining the DB connection to get subscribed/unsubscribed users for the " + + "given app release ID."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } catch (SQLException e) { - String msg = "SQL Error occurred while getting subscribed users for given app release id."; + String msg = "SQL Error occurred while getting subscribed/unsubscribed users for the given app release ID."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } } @Override - public int getSubscribedUserCount(int appReleaseId, int tenantId) + public int getSubscribedUserCount(int appReleaseId, int tenantId, Boolean uninstalled, String searchName) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { - log.debug("Request received in DAO Layer to get already subscribed users for " + + log.debug("Request received in DAO Layer to get already subscribed/unsubscribed users for " + "given app release id."); } try { Connection conn = this.getDBConnection(); - String sql = "SELECT " - + "COUNT(US.USER_NAME) AS USER_NAME " - + "FROM AP_USER_SUBSCRIPTION US " - + "WHERE " - + "AP_APP_RELEASE_ID = ? AND TENANT_ID = ?"; + String sql = "SELECT COUNT(US.USER_NAME) AS USER_COUNT " + + "FROM AP_USER_SUBSCRIPTION US " + + "WHERE AP_APP_RELEASE_ID = ? " + + "AND TENANT_ID = ?"; + if (uninstalled != null) { + sql += " AND UNSUBSCRIBED = ?"; + } + if (searchName != null && !searchName.trim().isEmpty()) { + sql += " AND US.USER_NAME LIKE ?"; + } try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setInt(1, appReleaseId); - stmt.setInt(2, tenantId); + int index = 1; + stmt.setInt(index++, appReleaseId); + stmt.setInt(index++, tenantId); + if (uninstalled != null) { + stmt.setBoolean(index++, uninstalled); + } + if (searchName != null && !searchName.trim().isEmpty()) { + stmt.setString(index++, "%" + searchName + "%"); + } try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { - return rs.getInt("USER_NAME"); + return rs.getInt("USER_COUNT"); } } return 0; } } catch (DBConnectionException e) { String msg = "Error occurred while obtaining the DB connection to get already " + - "subscribed users count for given app release id."; + "subscribed/unsubscribed users count for given app release id."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } catch (SQLException e) { - String msg = "SQL Error occurred while getting subscribed users for given app release id."; + String msg = "SQL Error occurred while getting subscribed/unsubscribed users count for given app release id."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } @@ -1055,11 +1079,12 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc "AP_DEVICE_SUBSCRIPTION.AP_APP_RELEASE_ID = AP_APP_RELEASE.AP_APP_ID " + "WHERE PACKAGE_NAME = ? " + "AND DM_DEVICE_ID = ? " + - "AND UNSUBSCRIBED = 'FALSE' " + + "AND UNSUBSCRIBED = ? " + "AND STATUS = 'COMPLETED';"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, packageName); stmt.setInt(2, id); + stmt.setBoolean(3, false); try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { return rs.getString("UUID"); @@ -1150,25 +1175,40 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc @Override public List getAppSubscribedRoles(int offsetValue, int limitValue, int appReleaseId, - int tenantId) + int tenantId, Boolean uninstalled, String searchName) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { - log.debug("Request received in DAO Layer to get already subscribed roles for " + + log.debug("Request received in DAO Layer to get already subscribed/unsubscribed roles for " + "given app release id."); } try { Connection conn = this.getDBConnection(); List subscribedRoles = new ArrayList<>(); String sql = "SELECT " - + "RS.ROLE_NAME AS ROLE " - + "FROM AP_ROLE_SUBSCRIPTION RS " - + "WHERE " - + "AP_APP_RELEASE_ID = ? AND TENANT_ID = ? LIMIT ? OFFSET ?"; + + "RS.ROLE_NAME AS ROLE " + + "FROM AP_ROLE_SUBSCRIPTION RS " + + "WHERE AP_APP_RELEASE_ID = ? " + + "AND TENANT_ID = ?"; + if (uninstalled != null) { + sql += " AND UNSUBSCRIBED = ?"; + } + if (searchName != null && !searchName.trim().isEmpty()) { + sql += " AND RS.ROLE_NAME LIKE ?"; + } + sql += " LIMIT ? OFFSET ?"; try (PreparedStatement ps = conn.prepareStatement(sql)) { - ps.setInt(1, appReleaseId); - ps.setInt(2, tenantId); - ps.setInt(3, limitValue); - ps.setInt(4, offsetValue); + int paramIndex = 1; + ps.setInt(paramIndex++, appReleaseId); + ps.setInt(paramIndex++, tenantId); + + if (uninstalled != null) { + ps.setBoolean(paramIndex++, uninstalled); + } + if (searchName != null && !searchName.trim().isEmpty()) { + ps.setString(paramIndex++, "%" + searchName + "%"); + } + ps.setInt(paramIndex++, limitValue); + ps.setInt(paramIndex, offsetValue); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { subscribedRoles.add(rs.getString("ROLE")); @@ -1178,49 +1218,61 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc } } catch (DBConnectionException e) { String msg = "Error occurred while obtaining the DB connection to get already " + - "subscribed roles for given app release id."; + "subscribed/unsubscribed roles for given app release id."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } catch (SQLException e) { - String msg = "SQL Error occurred while getting subscribed roles for given app release id."; + String msg = "SQL Error occurred while getting subscribed/unsubscribed roles for given app release id."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } } @Override - public int getSubscribedRoleCount(int appReleaseId, int tenantId) + public int getSubscribedRoleCount(int appReleaseId, int tenantId, Boolean uninstalled, String searchName) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { - log.debug("Request received in DAO Layer to get already subscribed roles for " + + log.debug("Request received in DAO Layer to get already subscribed/unsubscribed roles for " + "given app release id."); } try { Connection conn = this.getDBConnection(); String sql = "SELECT " - + "COUNT(RS.ROLE_NAME) AS ROLE_NAME " - + "FROM AP_ROLE_SUBSCRIPTION RS " - + "WHERE " - + "AP_APP_RELEASE_ID = ? AND TENANT_ID = ?"; + + "COUNT(RS.ROLE_NAME) AS ROLE_COUNT " + + "FROM AP_ROLE_SUBSCRIPTION RS " + + "WHERE AP_APP_RELEASE_ID = ? " + + "AND TENANT_ID = ?"; + if (uninstalled != null) { + sql += " AND UNSUBSCRIBED = ?"; + } + if (searchName != null && !searchName.trim().isEmpty()) { + sql += " AND RS.ROLE_NAME LIKE ?"; + } try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setInt(1, appReleaseId); - stmt.setInt(2, tenantId); - + int paramIndex = 1; + stmt.setInt(paramIndex++, appReleaseId); + stmt.setInt(paramIndex++, tenantId); + if (uninstalled != null) { + stmt.setBoolean(paramIndex++, uninstalled); + } + if (searchName != null && !searchName.trim().isEmpty()) { + stmt.setString(paramIndex++, "%" + searchName + "%"); + } try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { - return rs.getInt("ROLE_NAME"); + return rs.getInt("ROLE_COUNT"); } + return 0; } - return 0; } } catch (DBConnectionException e) { String msg = "Error occurred while obtaining the DB connection to get already " + - "subscribed roles count for given app release id."; + "subscribed/unsubscribed roles count for given app release id."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } catch (SQLException e) { - String msg = "SQL Error occurred while getting subscribed roles for given app release id."; + String msg = "SQL Error occurred while getting subscribed/unsubscribed roles count for given app release id."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } @@ -1268,25 +1320,37 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc @Override public List getAppSubscribedGroups(int offsetValue, int limitValue, int appReleaseId, - int tenantId) + int tenantId, Boolean uninstalled, String searchName) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { - log.debug("Request received in DAO Layer to get already subscribed groups for " + + log.debug("Request received in DAO Layer to get already subscribed/unsubscribed groups for " + "given app release id."); } try { Connection conn = this.getDBConnection(); List subscribedGroups = new ArrayList<>(); - String sql = "SELECT " - + "GS.GROUP_NAME AS APP_GROUPS " - + "FROM AP_GROUP_SUBSCRIPTION GS " - + "WHERE " - + "AP_APP_RELEASE_ID = ? AND TENANT_ID = ? LIMIT ? OFFSET ?"; + String sql = "SELECT GS.GROUP_NAME AS APP_GROUPS " + + "FROM AP_GROUP_SUBSCRIPTION GS " + + "WHERE AP_APP_RELEASE_ID = ? AND TENANT_ID = ?"; + if (uninstalled != null) { + sql += " AND UNSUBSCRIBED = ?"; + } + if (searchName != null && !searchName.trim().isEmpty()) { + sql += " AND GS.GROUP_NAME LIKE ?"; + } + sql += " LIMIT ? OFFSET ?"; try (PreparedStatement ps = conn.prepareStatement(sql)) { - ps.setInt(1, appReleaseId); - ps.setInt(2, tenantId); - ps.setInt(3, limitValue); - ps.setInt(4, offsetValue); + int paramIndex = 1; + ps.setInt(paramIndex++, appReleaseId); + ps.setInt(paramIndex++, tenantId); + if (uninstalled != null) { + ps.setBoolean(paramIndex++, uninstalled); + } + if (searchName != null && !searchName.trim().isEmpty()) { + ps.setString(paramIndex++, "%" + searchName + "%"); + } + ps.setInt(paramIndex++, limitValue); + ps.setInt(paramIndex, offsetValue); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { subscribedGroups.add(rs.getString("APP_GROUPS")); @@ -1296,11 +1360,11 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc } } catch (DBConnectionException e) { String msg = "Error occurred while obtaining the DB connection to get already " + - "subscribed groups for given app release id."; + "subscribed/unsubscribed groups for given app release id."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } catch (SQLException e) { - String msg = "SQL Error occurred while getting subscribed groups for given " + + String msg = "SQL Error occurred while getting subscribed/unsubscribed groups for given " + "app release id."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); @@ -1308,24 +1372,34 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc } @Override - public int getSubscribedGroupCount(int appReleaseId, int tenantId) + public int getSubscribedGroupCount(int appReleaseId, int tenantId, Boolean uninstalled, String searchName) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { - log.debug("Request received in DAO Layer to get already subscribed groups for " + - "given app release id."); + log.debug("Request received in DAO Layer to get the count of subscribed/unsubscribed groups for " + + "given app release id."); } try { Connection conn = this.getDBConnection(); - String sql = "SELECT " - + "COUNT(GS.GROUP_NAME) AS APP_GROUPS_COUNT " - + "FROM AP_GROUP_SUBSCRIPTION GS " - + "WHERE " - + "AP_APP_RELEASE_ID = ? AND TENANT_ID = ?"; + String sql = "SELECT COUNT(GS.GROUP_NAME) AS APP_GROUPS_COUNT " + + "FROM AP_GROUP_SUBSCRIPTION GS " + + "WHERE AP_APP_RELEASE_ID = ? AND TENANT_ID = ?"; + if (uninstalled != null) { + sql += " AND UNSUBSCRIBED = ?"; + } + if (searchName != null && !searchName.trim().isEmpty()) { + sql += " AND GS.GROUP_NAME LIKE ?"; + } try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setInt(1, appReleaseId); - stmt.setInt(2, tenantId); - + int paramIndex = 1; + stmt.setInt(paramIndex++, appReleaseId); + stmt.setInt(paramIndex++, tenantId); + if (uninstalled != null) { + stmt.setBoolean(paramIndex++, uninstalled); + } + if (searchName != null && !searchName.trim().isEmpty()) { + stmt.setString(paramIndex++, "%" + searchName + "%"); + } try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { return rs.getInt("APP_GROUPS_COUNT"); @@ -1334,12 +1408,13 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc return 0; } } catch (DBConnectionException e) { - String msg = "Error occurred while obtaining the DB connection to get already " + - "subscribed groups count for given app release id."; + String msg = "Error occurred while obtaining the DB connection to get the count of " + + "subscribed/unsubscribed groups for given app release id."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } catch (SQLException e) { - String msg = "SQL Error occurred while getting subscribed groups for given app release id."; + String msg = "SQL Error occurred while getting the count of subscribed/unsubscribed groups for given " + + "app release id."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/OracleSubscriptionDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/OracleSubscriptionDAOImpl.java index 71bd17bbc9..a074672a55 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/OracleSubscriptionDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/OracleSubscriptionDAOImpl.java @@ -20,10 +20,10 @@ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.subscription; import io.entgra.device.mgt.core.application.mgt.common.SubscriptionEntity; import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceSubscriptionDTO; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; @@ -43,10 +43,10 @@ public class OracleSubscriptionDAOImpl extends GenericSubscriptionDAOImpl { @Override public List getAppSubscribedUsers(int offsetValue, int limitValue, int appReleaseId, - int tenantId) + int tenantId, Boolean uninstalled, String searchName) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { - log.debug("Request received in DAO Layer to get already subscribed users for " + + log.debug("Request received in DAO Layer to get already subscribed/unsubscribed users for " + "given app release id."); } try { @@ -55,13 +55,28 @@ public class OracleSubscriptionDAOImpl extends GenericSubscriptionDAOImpl { String sql = "SELECT " + "US.USER_NAME AS USER " + "FROM AP_USER_SUBSCRIPTION US " - + "WHERE " - + "AP_APP_RELEASE_ID = ? AND TENANT_ID = ? ORDER BY US.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + "WHERE AP_APP_RELEASE_ID = ? " + + "AND TENANT_ID = ? "; + if (uninstalled != null) { + sql += "AND UNSUBSCRIBED = ? "; + } + if (searchName != null && !searchName.trim().isEmpty()) { + sql += "AND US.USER_NAME LIKE ? "; + } + sql += "ORDER BY US.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setInt(1, appReleaseId); - stmt.setInt(2, tenantId); - stmt.setInt(3, offsetValue); - stmt.setInt(4, limitValue); + int index = 1; + stmt.setInt(index++, appReleaseId); + stmt.setInt(index++, tenantId); + if (uninstalled != null) { + stmt.setBoolean(index++, uninstalled); + } + if (searchName != null && !searchName.trim().isEmpty()) { + stmt.setString(index++, "%" + searchName + "%"); + } + stmt.setInt(index++, offsetValue); + stmt.setInt(index, limitValue); + try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { subscribedUsers.add(rs.getString("USER")); @@ -71,11 +86,11 @@ public class OracleSubscriptionDAOImpl extends GenericSubscriptionDAOImpl { } } catch (DBConnectionException e) { String msg = "Error occurred while obtaining the DB connection to get already " + - "subscribed users for given app release id."; + "subscribed/unsubscribed users for given app release id."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } catch (SQLException e) { - String msg = "SQL Error occurred while getting subscribed users for given app release id."; + String msg = "SQL Error occurred while getting subscribed/unsubscribed users for given app release id."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } @@ -83,10 +98,10 @@ public class OracleSubscriptionDAOImpl extends GenericSubscriptionDAOImpl { @Override public List getAppSubscribedRoles(int offsetValue, int limitValue, int appReleaseId, - int tenantId) + int tenantId, Boolean uninstalled, String searchName) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { - log.debug("Request received in DAO Layer to get already subscribed roles for " + + log.debug("Request received in DAO Layer to get already subscribed/unsubscribed roles for " + "given app release id."); } try { @@ -95,13 +110,27 @@ public class OracleSubscriptionDAOImpl extends GenericSubscriptionDAOImpl { String sql = "SELECT " + "RS.ROLE_NAME AS ROLE " + "FROM AP_ROLE_SUBSCRIPTION RS " - + "WHERE " - + "AP_APP_RELEASE_ID = ? AND TENANT_ID = ? ORDER BY RS.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + "WHERE AP_APP_RELEASE_ID = ? " + + "AND TENANT_ID = ? "; + if (uninstalled != null) { + sql += "AND UNSUBSCRIBED = ? "; + } + if (searchName != null && !searchName.trim().isEmpty()) { + sql += "AND RS.ROLE_NAME LIKE ? "; + } + sql += "ORDER BY RS.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; try (PreparedStatement ps = conn.prepareStatement(sql)) { - ps.setInt(1, appReleaseId); - ps.setInt(2, tenantId); - ps.setInt(3, offsetValue); - ps.setInt(4, limitValue); + int paramIndex = 1; + ps.setInt(paramIndex++, appReleaseId); + ps.setInt(paramIndex++, tenantId); + if (uninstalled != null) { + ps.setBoolean(paramIndex++, uninstalled); + } + if (searchName != null && !searchName.trim().isEmpty()) { + ps.setString(paramIndex++, "%" + searchName + "%"); + } + ps.setInt(paramIndex++, offsetValue); + ps.setInt(paramIndex, limitValue); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { subscribedRoles.add(rs.getString("ROLE")); @@ -111,11 +140,11 @@ public class OracleSubscriptionDAOImpl extends GenericSubscriptionDAOImpl { } } catch (DBConnectionException e) { String msg = "Error occurred while obtaining the DB connection to get already " + - "subscribed roles for given app release id."; + "subscribed/unsubscribed roles for given app release id."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } catch (SQLException e) { - String msg = "SQL Error occurred while getting subscribed roles for given app release id."; + String msg = "SQL Error occurred while getting subscribed/unsubscribed roles for given app release id."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } @@ -123,11 +152,10 @@ public class OracleSubscriptionDAOImpl extends GenericSubscriptionDAOImpl { @Override public List getAppSubscribedGroups(int offsetValue, int limitValue, int appReleaseId, - int tenantId) + int tenantId, Boolean uninstalled, String searchName) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { - log.debug("Request received in DAO Layer to get already subscribed groups for " + - "given app release id."); + log.debug("Request received in DAO Layer to get subscribed/unsubscribed groups for the given app release ID."); } try { Connection conn = this.getDBConnection(); @@ -135,13 +163,26 @@ public class OracleSubscriptionDAOImpl extends GenericSubscriptionDAOImpl { String sql = "SELECT " + "GS.GROUP_NAME AS GROUPS " + "FROM AP_GROUP_SUBSCRIPTION GS " - + "WHERE " - + "AP_APP_RELEASE_ID = ? AND TENANT_ID = ? ORDER BY GS.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + "WHERE AP_APP_RELEASE_ID = ? AND TENANT_ID = ?"; + if (uninstalled != null) { + sql += " AND UNSUBSCRIBED = ?"; + } + if (searchName != null && !searchName.trim().isEmpty()) { + sql += " AND GS.GROUP_NAME LIKE ?"; + } + sql += " ORDER BY GS.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; try (PreparedStatement ps = conn.prepareStatement(sql)) { - ps.setInt(1, appReleaseId); - ps.setInt(2, tenantId); - ps.setInt(3, offsetValue); - ps.setInt(4, limitValue); + int paramIndex = 1; + ps.setInt(paramIndex++, appReleaseId); + ps.setInt(paramIndex++, tenantId); + if (uninstalled != null) { + ps.setBoolean(paramIndex++, uninstalled); + } + if (searchName != null && !searchName.trim().isEmpty()) { + ps.setString(paramIndex++, "%" + searchName + "%"); + } + ps.setInt(paramIndex++, offsetValue); + ps.setInt(paramIndex, limitValue); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { subscribedGroups.add(rs.getString("GROUPS")); @@ -150,13 +191,12 @@ public class OracleSubscriptionDAOImpl extends GenericSubscriptionDAOImpl { return subscribedGroups; } } catch (DBConnectionException e) { - String msg = "Error occurred while obtaining the DB connection to get already " + - "subscribed groups for given app release id."; + String msg = "Error occurred while obtaining the DB connection to get subscribed/unsubscribed groups" + + " for the given app release ID."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } catch (SQLException e) { - String msg = "SQL Error occurred while getting subscribed groups for given " + - "app release id."; + String msg = "SQL Error occurred while getting subscribed/unsubscribed groups for the given app release ID."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/SQLServerSubscriptionDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/SQLServerSubscriptionDAOImpl.java index fb165ca3e0..622ce0c399 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/SQLServerSubscriptionDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/SQLServerSubscriptionDAOImpl.java @@ -18,10 +18,10 @@ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.subscription; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; @@ -39,10 +39,10 @@ public class SQLServerSubscriptionDAOImpl extends GenericSubscriptionDAOImpl { @Override public List getAppSubscribedUsers(int offsetValue, int limitValue, int appReleaseId, - int tenantId) + int tenantId, Boolean uninstalled, String searchName) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { - log.debug("Request received in DAO Layer to get already subscribed users for " + + log.debug("Request received in DAO Layer to get already subscribed/unsubscribed users for " + "given app release id."); } try { @@ -51,13 +51,28 @@ public class SQLServerSubscriptionDAOImpl extends GenericSubscriptionDAOImpl { String sql = "SELECT " + "US.USER_NAME AS USER_NAME " + "FROM AP_USER_SUBSCRIPTION US " - + "WHERE " - + "AP_APP_RELEASE_ID = ? AND TENANT_ID = ? ORDER BY US.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + "WHERE AP_APP_RELEASE_ID = ? " + + "AND TENANT_ID = ? "; + if (uninstalled != null) { + sql += "AND UNSUBSCRIBED = ? "; + } + if (searchName != null && !searchName.trim().isEmpty()) { + sql += "AND US.USER_NAME LIKE ? "; + } + sql += "ORDER BY US.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setInt(1, appReleaseId); - stmt.setInt(2, tenantId); - stmt.setInt(3, offsetValue); - stmt.setInt(4, limitValue); + int index = 1; + stmt.setInt(index++, appReleaseId); + stmt.setInt(index++, tenantId); + if (uninstalled != null) { + stmt.setBoolean(index++, uninstalled); + } + if (searchName != null && !searchName.trim().isEmpty()) { + stmt.setString(index++, "%" + searchName + "%"); + } + stmt.setInt(index++, offsetValue); + stmt.setInt(index, limitValue); + try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { subscribedUsers.add(rs.getString("USER_NAME")); @@ -67,11 +82,11 @@ public class SQLServerSubscriptionDAOImpl extends GenericSubscriptionDAOImpl { } } catch (DBConnectionException e) { String msg = "Error occurred while obtaining the DB connection to get already " + - "subscribed users for given app release id."; + "subscribed/unsubscribed users for given app release id."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } catch (SQLException e) { - String msg = "SQL Error occurred while getting subscribed users for given app release id."; + String msg = "SQL Error occurred while getting subscribed/unsubscribed users for given app release id."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } @@ -79,10 +94,10 @@ public class SQLServerSubscriptionDAOImpl extends GenericSubscriptionDAOImpl { @Override public List getAppSubscribedRoles(int offsetValue, int limitValue, int appReleaseId, - int tenantId) + int tenantId, Boolean uninstalled, String searchName) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { - log.debug("Request received in DAO Layer to get already subscribed roles for " + + log.debug("Request received in DAO Layer to get already subscribed/unsubscribed roles for " + "given app release id."); } try { @@ -91,13 +106,29 @@ public class SQLServerSubscriptionDAOImpl extends GenericSubscriptionDAOImpl { String sql = "SELECT " + "RS.ROLE_NAME AS ROLE " + "FROM AP_ROLE_SUBSCRIPTION RS " - + "WHERE " - + "AP_APP_RELEASE_ID = ? AND TENANT_ID = ? ORDER BY RS.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + "WHERE AP_APP_RELEASE_ID = ? " + + "AND TENANT_ID = ? "; + if (uninstalled != null) { + sql += "AND UNSUBSCRIBED = ? "; + } + if (searchName != null && !searchName.trim().isEmpty()) { + sql += "AND RS.ROLE_NAME LIKE ? "; + } + sql += "ORDER BY RS.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { - ps.setInt(1, appReleaseId); - ps.setInt(2, tenantId); - ps.setInt(3, offsetValue); - ps.setInt(4, limitValue); + int paramIndex = 1; + ps.setInt(paramIndex++, appReleaseId); + ps.setInt(paramIndex++, tenantId); + if (uninstalled != null) { + ps.setBoolean(paramIndex++, uninstalled); + } + if (searchName != null && !searchName.trim().isEmpty()) { + ps.setString(paramIndex++, "%" + searchName + "%"); + } + ps.setInt(paramIndex++, offsetValue); + ps.setInt(paramIndex, limitValue); + try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { subscribedRoles.add(rs.getString("ROLE")); @@ -107,11 +138,11 @@ public class SQLServerSubscriptionDAOImpl extends GenericSubscriptionDAOImpl { } } catch (DBConnectionException e) { String msg = "Error occurred while obtaining the DB connection to get already " + - "subscribed roles for given app release id."; + "subscribed/unsubscribed roles for given app release id."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } catch (SQLException e) { - String msg = "SQL Error occurred while getting subscribed roles for given app release id."; + String msg = "SQL Error occurred while getting subscribed/unsubscribed roles for given app release id."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } @@ -119,11 +150,10 @@ public class SQLServerSubscriptionDAOImpl extends GenericSubscriptionDAOImpl { @Override public List getAppSubscribedGroups(int offsetValue, int limitValue, int appReleaseId, - int tenantId) + int tenantId, Boolean uninstalled, String searchName) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { - log.debug("Request received in DAO Layer to get already subscribed groups for " + - "given app release id."); + log.debug("Request received in DAO Layer to get subscribed/unsubscribed groups for the given app release ID."); } try { Connection conn = this.getDBConnection(); @@ -131,13 +161,26 @@ public class SQLServerSubscriptionDAOImpl extends GenericSubscriptionDAOImpl { String sql = "SELECT " + "GS.GROUP_NAME AS GROUPS " + "FROM AP_GROUP_SUBSCRIPTION GS " - + "WHERE " - + "AP_APP_RELEASE_ID = ? AND TENANT_ID = ? ORDER BY GS.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + "WHERE AP_APP_RELEASE_ID = ? AND TENANT_ID = ?"; + if (uninstalled != null) { + sql += " AND UNSUBSCRIBED = ?"; + } + if (searchName != null && !searchName.trim().isEmpty()) { + sql += " AND GS.GROUP_NAME LIKE ?"; + } + sql += " ORDER BY GS.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; try (PreparedStatement ps = conn.prepareStatement(sql)) { - ps.setInt(1, appReleaseId); - ps.setInt(2, tenantId); - ps.setInt(3, offsetValue); - ps.setInt(4, limitValue); + int paramIndex = 1; + ps.setInt(paramIndex++, appReleaseId); + ps.setInt(paramIndex++, tenantId); + if (uninstalled != null) { + ps.setBoolean(paramIndex++, uninstalled); + } + if (searchName != null && !searchName.trim().isEmpty()) { + ps.setString(paramIndex++, "%" + searchName + "%"); + } + ps.setInt(paramIndex++, offsetValue); + ps.setInt(paramIndex, limitValue); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { subscribedGroups.add(rs.getString("GROUPS")); @@ -146,13 +189,11 @@ public class SQLServerSubscriptionDAOImpl extends GenericSubscriptionDAOImpl { return subscribedGroups; } } catch (DBConnectionException e) { - String msg = "Error occurred while obtaining the DB connection to get already " + - "subscribed groups for given app release id."; + String msg = "Error occurred while obtaining the DB connection to get subscribed/unsubscribed groups for the given app release ID."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } catch (SQLException e) { - String msg = "SQL Error occurred while getting subscribed groups for given " + - "app release id."; + String msg = "SQL Error occurred while getting subscribed/unsubscribed groups for the given app release ID."; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/visibility/GenericVisibilityDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/visibility/GenericVisibilityDAOImpl.java index 1033af9bef..410fcacd66 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/visibility/GenericVisibilityDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/visibility/GenericVisibilityDAOImpl.java @@ -17,12 +17,12 @@ */ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.visibility; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; import io.entgra.device.mgt.core.application.mgt.core.dao.VisibilityDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.AbstractDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.exception.VisibilityManagementDAOException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java index 2e8233f9dc..e37ec062a3 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java @@ -18,45 +18,28 @@ package io.entgra.device.mgt.core.application.mgt.core.impl; +import io.entgra.device.mgt.core.application.mgt.common.ReleaseVersionInfo; import io.entgra.device.mgt.core.application.mgt.common.exception.FileDownloaderServiceException; -import io.entgra.device.mgt.core.application.mgt.common.exception.FileTransferServiceException; import io.entgra.device.mgt.core.application.mgt.core.exception.BadRequestException; import io.entgra.device.mgt.core.application.mgt.core.dao.*; import io.entgra.device.mgt.core.application.mgt.core.exception.*; -import io.entgra.device.mgt.core.device.mgt.common.Base64File; import io.entgra.device.mgt.core.application.mgt.core.dao.SPApplicationDAO; import io.entgra.device.mgt.core.application.mgt.core.util.ApplicationManagementUtil; -import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; -import io.entgra.device.mgt.core.device.mgt.common.app.mgt.App; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; -import io.entgra.device.mgt.core.tenant.mgt.common.exception.TenantMgtException; -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringEscapeUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.validator.routines.UrlValidator; -import org.apache.cxf.jaxrs.ext.multipart.Attachment; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONObject; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.application.mgt.common.ApplicationArtifact; import io.entgra.device.mgt.core.application.mgt.common.ApplicationInstaller; +import io.entgra.device.mgt.core.application.mgt.common.ApplicationList; +import io.entgra.device.mgt.core.application.mgt.common.ApplicationSubscriptionType; +import io.entgra.device.mgt.core.application.mgt.common.ApplicationType; import io.entgra.device.mgt.core.application.mgt.common.DeviceTypes; +import io.entgra.device.mgt.core.application.mgt.common.Filter; import io.entgra.device.mgt.core.application.mgt.common.LifecycleChanger; +import io.entgra.device.mgt.core.application.mgt.common.LifecycleState; import io.entgra.device.mgt.core.application.mgt.common.Pagination; import io.entgra.device.mgt.core.application.mgt.common.config.RatingConfiguration; import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; -import io.entgra.device.mgt.core.application.mgt.common.ApplicationList; import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO; -import io.entgra.device.mgt.core.application.mgt.common.ApplicationSubscriptionType; -import io.entgra.device.mgt.core.application.mgt.common.ApplicationType; import io.entgra.device.mgt.core.application.mgt.common.dto.CategoryDTO; -import io.entgra.device.mgt.core.application.mgt.common.Filter; import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceSubscriptionDTO; -import io.entgra.device.mgt.core.application.mgt.common.LifecycleState; import io.entgra.device.mgt.core.application.mgt.common.dto.TagDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationStorageManagementException; @@ -71,18 +54,17 @@ import io.entgra.device.mgt.core.application.mgt.common.response.Category; import io.entgra.device.mgt.core.application.mgt.common.response.Tag; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationStorageManager; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.ApplicationUpdateWrapper; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.ApplicationWrapper; import io.entgra.device.mgt.core.application.mgt.common.wrapper.CustomAppReleaseWrapper; import io.entgra.device.mgt.core.application.mgt.common.wrapper.CustomAppWrapper; import io.entgra.device.mgt.core.application.mgt.common.wrapper.EntAppReleaseWrapper; -import io.entgra.device.mgt.core.application.mgt.common.wrapper.ApplicationUpdateWrapper; -import io.entgra.device.mgt.core.application.mgt.common.wrapper.ApplicationWrapper; import io.entgra.device.mgt.core.application.mgt.common.wrapper.PublicAppReleaseWrapper; import io.entgra.device.mgt.core.application.mgt.common.wrapper.PublicAppWrapper; import io.entgra.device.mgt.core.application.mgt.common.wrapper.WebAppReleaseWrapper; import io.entgra.device.mgt.core.application.mgt.common.wrapper.WebAppWrapper; import io.entgra.device.mgt.core.application.mgt.core.config.ConfigurationManager; import io.entgra.device.mgt.core.application.mgt.core.dao.common.ApplicationManagementDAOFactory; -import io.entgra.device.mgt.core.application.mgt.core.util.APIUtil; import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; import io.entgra.device.mgt.core.application.mgt.core.exception.ForbiddenException; import io.entgra.device.mgt.core.application.mgt.core.exception.LifeCycleManagementDAOException; @@ -90,24 +72,35 @@ import io.entgra.device.mgt.core.application.mgt.core.exception.NotFoundExceptio import io.entgra.device.mgt.core.application.mgt.core.exception.VisibilityManagementDAOException; import io.entgra.device.mgt.core.application.mgt.core.internal.DataHolder; import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; +import io.entgra.device.mgt.core.application.mgt.core.util.APIUtil; import io.entgra.device.mgt.core.application.mgt.core.util.ConnectionManagerUtil; import io.entgra.device.mgt.core.application.mgt.core.util.Constants; -import io.entgra.device.mgt.core.device.mgt.core.common.exception.StorageManagementException; +import io.entgra.device.mgt.core.device.mgt.common.Base64File; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; - +import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; +import io.entgra.device.mgt.core.device.mgt.core.common.exception.StorageManagementException; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.validator.routines.UrlValidator; +import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONObject; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; -import javax.ws.rs.core.Response; -import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; -import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; -import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; @@ -1488,7 +1481,7 @@ public class ApplicationManagerImpl implements ApplicationManager { this.changeLifecycleState(applicationReleaseDTO, lifecycleChanger); } } - if (applicationDTO.getType().equals("ENTERPRISE") || applicationDTO.getType().equals("PUBLIC") ) { + if (Constants.ENTERPRISE_APP_TYPE.equals(applicationDTO.getType()) || Constants.PUBLIC_APP_TYPE.equals(applicationDTO.getType())) { persistAppIconInfo(applicationReleaseDTO); } applicationReleaseEntities.add(applicationReleaseDTO); @@ -1965,14 +1958,13 @@ public class ApplicationManagerImpl implements ApplicationManager { List allMetadata; allMetadata = APIUtil.getMetadataManagementService().retrieveAllMetadata(); if (allMetadata != null && !allMetadata.isEmpty()) { - for(Metadata metadata : allMetadata){ - if(Constants.SHOW_ALL_ROLES.equals(metadata.getMetaKey())){ + for (Metadata metadata : allMetadata) { + if (Constants.SHOW_ALL_ROLES.equals(metadata.getMetaKey())) { String metaValue = metadata.getMetaValue(); if (metaValue != null) { JSONObject jsonObject; jsonObject = new JSONObject(metaValue); - boolean isUserAbleToViewAllRoles = jsonObject.getBoolean(Constants.IS_USER_ABLE_TO_VIEW_ALL_ROLES); - return isUserAbleToViewAllRoles; + return jsonObject.getBoolean(Constants.IS_USER_ABLE_TO_VIEW_ALL_ROLES); } } } @@ -4447,13 +4439,9 @@ public class ApplicationManagerImpl implements ApplicationManager { } @Override - public void deleteApplicationDataByTenantDomain(String tenantDomain) throws ApplicationManagementException { - int tenantId; + public void deleteApplicationDataByTenantId(int tenantId) throws ApplicationManagementException { try { - tenantId = DataHolder.getInstance().getTenantManagerAdminService().getTenantId(tenantDomain); - ConnectionManagerUtil.beginDBTransaction(); - vppApplicationDAO.deleteAssociationByTenant(tenantId); vppApplicationDAO.deleteVppUserByTenant(tenantId); vppApplicationDAO.deleteAssetsByTenant(tenantId); @@ -4479,50 +4467,59 @@ public class ApplicationManagerImpl implements ApplicationManager { ConnectionManagerUtil.commitDBTransaction(); } catch (DBConnectionException e) { String msg = "Error occurred while observing the database connection to delete applications for tenant with " + - "domain: " + tenantDomain; + "tenant ID: " + tenantId; log.error(msg, e); throw new ApplicationManagementException(msg, e); } catch (ApplicationManagementDAOException e) { ConnectionManagerUtil.rollbackDBTransaction(); - String msg = "Database access error is occurred when getting applications for tenant with domain: " - + tenantDomain; + String msg = "Database access error is occurred when getting applications for tenant with tenant Id: " + + tenantId; log.error(msg, e); throw new ApplicationManagementException(msg, e); } catch (LifeCycleManagementDAOException e) { ConnectionManagerUtil.rollbackDBTransaction(); String msg = "Error occurred while deleting life-cycle state data of application releases of the tenant" - + " of domain: " + tenantDomain ; + + " of id: " + tenantId ; log.error(msg, e); throw new ApplicationManagementException(msg, e); } catch (ReviewManagementDAOException e) { ConnectionManagerUtil.rollbackDBTransaction(); String msg = "Error occurred while deleting reviews of application releases of the applications" - + " of tenant of domain: " + tenantDomain ; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } catch (Exception e) { - String msg = "Error getting tenant ID from domain: " - + tenantDomain; + + " of tenant of id: " + tenantId ; log.error(msg, e); throw new ApplicationManagementException(msg, e); } } @Override - public void deleteApplicationArtifactsByTenantDomain(String tenantDomain) throws ApplicationManagementException { - int tenantId; + public void deleteApplicationArtifactsByTenantId(int tenantId) throws ApplicationManagementException { try { - tenantId = DataHolder.getInstance().getTenantManagerAdminService().getTenantId(tenantDomain); DataHolder.getInstance().getApplicationStorageManager().deleteAppFolderOfTenant(tenantId); - } catch (ApplicationStorageManagementException e) { - String msg = "Error deleting app artifacts of tenant of domain: " + tenantDomain ; + } catch (ApplicationStorageManagementException e) { + String msg = "Error deleting app artifacts of tenant of Id: " + tenantId; log.error(msg, e); throw new ApplicationManagementException(msg, e); - } catch (TenantMgtException e) { - String msg = "Error getting tenant ID from domain: " - + tenantDomain + " when trying to delete application artifacts of tenant"; + } + } + + /** + * Retrieve {@link ReleaseVersionInfo} for a given package name + * @param uuid UUID of the application release + * @return List of {@link ReleaseVersionInfo} + * @throws ApplicationManagementException throws when error encountered while retrieving data + */ + @Override + public List getApplicationReleaseVersions(String uuid) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + ConnectionManagerUtil.openDBConnection(); + return applicationDAO.getApplicationReleaseVersions(uuid, tenantId); + } catch (ApplicationManagementDAOException e) { + String msg = "Error occurred while getting available application releases for uuid : " + uuid; log.error(msg, e); throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); } } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationStorageManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationStorageManagerImpl.java index ad1906ede1..c40090a887 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationStorageManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationStorageManagerImpl.java @@ -19,24 +19,25 @@ package io.entgra.device.mgt.core.application.mgt.core.impl; import com.dd.plist.NSDictionary; -import io.entgra.device.mgt.core.application.mgt.core.exception.ParsingException; -import io.entgra.device.mgt.core.application.mgt.core.util.ArtifactsParser; -import io.entgra.device.mgt.core.application.mgt.core.util.Constants; -import net.dongliu.apk.parser.bean.ApkMeta; -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.io.IOUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.application.mgt.common.ApplicationInstaller; -import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO; import io.entgra.device.mgt.core.application.mgt.common.DeviceTypes; +import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationStorageManagementException; import io.entgra.device.mgt.core.application.mgt.common.exception.ResourceManagementException; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationStorageManager; +import io.entgra.device.mgt.core.application.mgt.core.exception.ParsingException; +import io.entgra.device.mgt.core.application.mgt.core.util.ArtifactsParser; +import io.entgra.device.mgt.core.application.mgt.core.util.Constants; import io.entgra.device.mgt.core.device.mgt.core.common.exception.StorageManagementException; import io.entgra.device.mgt.core.device.mgt.core.common.util.StorageManagementUtil; +import net.dongliu.apk.parser.bean.ApkMeta; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; -import java.io.*; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; import java.nio.file.Paths; import java.util.List; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/AppmDataHandlerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/AppmDataHandlerImpl.java index c8c613983e..73bb748c23 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/AppmDataHandlerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/AppmDataHandlerImpl.java @@ -18,22 +18,22 @@ package io.entgra.device.mgt.core.application.mgt.core.impl; -import io.entgra.device.mgt.core.application.mgt.core.exception.BadRequestException; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.application.mgt.common.config.LifecycleState; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationStorageManagementException; import io.entgra.device.mgt.core.application.mgt.common.exception.LifecycleManagementException; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationStorageManager; import io.entgra.device.mgt.core.application.mgt.common.services.AppmDataHandler; -import io.entgra.device.mgt.core.application.mgt.core.util.APIUtil; +import io.entgra.device.mgt.core.application.mgt.core.exception.BadRequestException; import io.entgra.device.mgt.core.application.mgt.core.exception.NotFoundException; import io.entgra.device.mgt.core.application.mgt.core.internal.DataHolder; import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; +import io.entgra.device.mgt.core.application.mgt.core.util.APIUtil; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.io.InputStream; import java.util.Map; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ReviewManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ReviewManagerImpl.java index 050b6743d4..5fbdabae62 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ReviewManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ReviewManagerImpl.java @@ -18,34 +18,30 @@ package io.entgra.device.mgt.core.application.mgt.core.impl; -import io.entgra.device.mgt.core.application.mgt.core.exception.BadRequestException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.application.mgt.common.Rating; -import io.entgra.device.mgt.core.application.mgt.common.ReviewNode; import io.entgra.device.mgt.core.application.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.application.mgt.common.PaginationResult; +import io.entgra.device.mgt.core.application.mgt.common.Rating; +import io.entgra.device.mgt.core.application.mgt.common.ReviewNode; import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.ReviewDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; -import io.entgra.device.mgt.core.application.mgt.common.exception.ReviewManagementException; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; +import io.entgra.device.mgt.core.application.mgt.common.exception.ReviewManagementException; import io.entgra.device.mgt.core.application.mgt.common.exception.TransactionManagementException; import io.entgra.device.mgt.core.application.mgt.common.response.Review; -import io.entgra.device.mgt.core.application.mgt.common.services.*; +import io.entgra.device.mgt.core.application.mgt.common.services.ReviewManager; import io.entgra.device.mgt.core.application.mgt.common.wrapper.ReviewWrapper; import io.entgra.device.mgt.core.application.mgt.core.dao.ApplicationDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.ApplicationReleaseDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.ReviewDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.common.ApplicationManagementDAOFactory; -import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; -import io.entgra.device.mgt.core.application.mgt.core.exception.ForbiddenException; -import io.entgra.device.mgt.core.application.mgt.core.exception.NotFoundException; -import io.entgra.device.mgt.core.application.mgt.core.exception.ReviewManagementDAOException; +import io.entgra.device.mgt.core.application.mgt.core.exception.*; import io.entgra.device.mgt.core.application.mgt.core.util.ConnectionManagerUtil; import io.entgra.device.mgt.core.application.mgt.core.util.Constants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.util.ArrayList; import java.util.Comparator; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SPApplicationManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SPApplicationManagerImpl.java index 279088baa3..b1e7451288 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SPApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SPApplicationManagerImpl.java @@ -19,10 +19,10 @@ package io.entgra.device.mgt.core.application.mgt.core.impl; import io.entgra.device.mgt.core.application.mgt.common.IdentityServerResponse; -import io.entgra.device.mgt.core.application.mgt.common.SPApplicationListResponse; -import io.entgra.device.mgt.core.application.mgt.common.dto.IdentityServerDTO; import io.entgra.device.mgt.core.application.mgt.common.SPApplication; +import io.entgra.device.mgt.core.application.mgt.common.SPApplicationListResponse; import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.IdentityServerDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.IdentityServiceProviderDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; @@ -39,18 +39,17 @@ import io.entgra.device.mgt.core.application.mgt.core.dao.common.ApplicationMana import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; import io.entgra.device.mgt.core.application.mgt.core.exception.BadRequestException; import io.entgra.device.mgt.core.application.mgt.core.exception.NotFoundException; -import io.entgra.device.mgt.core.application.mgt.core.serviceprovider.ISServiceProviderApplicationService; import io.entgra.device.mgt.core.application.mgt.core.internal.DataHolder; import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; +import io.entgra.device.mgt.core.application.mgt.core.serviceprovider.ISServiceProviderApplicationService; import io.entgra.device.mgt.core.application.mgt.core.util.APIUtil; import io.entgra.device.mgt.core.application.mgt.core.util.ApplicationManagementUtil; import io.entgra.device.mgt.core.application.mgt.core.util.ConnectionManagerUtil; +import io.entgra.device.mgt.core.device.mgt.core.common.util.HttpUtil; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.commons.validator.routines.UrlValidator; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.core.common.util.HttpUtil; import java.util.ArrayList; import java.util.List; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java index 49552ea153..92f0734c9f 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java @@ -61,10 +61,10 @@ import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.ssl.SSLContextBuilder; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; +import org.apache.http.ssl.TrustStrategy; import org.json.JSONArray; import org.json.JSONObject; import io.entgra.device.mgt.core.apimgt.application.extension.dto.ApiApplicationKey; @@ -90,7 +90,10 @@ import io.entgra.device.mgt.core.application.mgt.core.util.ConnectionManagerUtil import io.entgra.device.mgt.core.application.mgt.core.util.Constants; import io.entgra.device.mgt.core.application.mgt.core.util.HelperUtil; import io.entgra.device.mgt.core.application.mgt.core.util.OAuthUtils; -import io.entgra.device.mgt.core.device.mgt.common.*; +import io.entgra.device.mgt.core.device.mgt.common.Device; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; +import io.entgra.device.mgt.core.device.mgt.common.MDMAppConstants; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.App; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.MobileAppTypes; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.android.CustomApplication; @@ -122,6 +125,8 @@ import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -776,14 +781,34 @@ public class SubscriptionManagerImpl implements SubscriptionManager { entry.getKey(), action, properties); activityList.add(activity); for (DeviceIdentifier identifier : deviceIdentifiers) { - log.info(String.format("Web app %s triggered", action), appInstallLogContextBuilder.setAppId(String.valueOf(applicationDTO.getId())).setAppName(applicationDTO.getName()).setAppType(applicationDTO.getType()).setSubType(subType).setTenantId(tenantId).setTenantDomain(tenantDomain).setDevice(String.valueOf(identifier)).setUserName(username).setAction(action).build()); + log.info(String.format("Web app %s triggered", action), appInstallLogContextBuilder + .setAppId(String.valueOf(applicationDTO.getId())) + .setAppName(applicationDTO.getName()) + .setAppType(applicationDTO.getType()) + .setSubType(subType) + .setTenantId(tenantId) + .setTenantDomain(tenantDomain) + .setDevice(String.valueOf(identifier)) + .setUserName(username) + .setAction(action) + .build()); } } } else { Activity activity = addAppOperationOnDevices(applicationDTO, deviceIdentifiers, deviceType, action, properties); activityList.add(activity); for (DeviceIdentifier identifier : deviceIdentifiers) { - log.info(String.format("App %s triggered", action), appInstallLogContextBuilder.setAppId(String.valueOf(applicationDTO.getId())).setAppName(applicationDTO.getName()).setAppType(applicationDTO.getType()).setSubType(subType).setTenantId(tenantId).setTenantDomain(tenantDomain).setDevice(String.valueOf(identifier)).setUserName(username).setAction(action).build()); + log.info(String.format("App %s triggered", action), appInstallLogContextBuilder + .setAppId(String.valueOf(applicationDTO.getId())) + .setAppName(applicationDTO.getName()) + .setAppType(applicationDTO.getType()) + .setSubType(subType) + .setTenantId(tenantId) + .setTenantDomain(tenantDomain) + .setDevice(String.valueOf(identifier)) + .setUserName(username) + .setAction(action) + .build()); } } @@ -1369,7 +1394,12 @@ public class SubscriptionManagerImpl implements SubscriptionManager { private CloseableHttpClient getHttpClient() throws ApplicationManagementException { try { SSLContextBuilder builder = new SSLContextBuilder(); - builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); + builder.loadTrustMaterial(null, new TrustStrategy() { + @Override + public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { + return true; + } + }); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); return HttpClients.custom().setSSLSocketFactory(sslsf).useSystemProperties().build(); } catch (NoSuchAlgorithmException e) { @@ -1468,7 +1498,8 @@ public class SubscriptionManagerImpl implements SubscriptionManager { } @Override - public PaginationResult getAppInstalledSubscribers(int offsetValue, int limitValue, String appUUID, String subType) + public PaginationResult getAppInstalledSubscribers(int offsetValue, int limitValue, String appUUID, String subType, + Boolean uninstalled, String searchName) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); @@ -1483,20 +1514,16 @@ public class SubscriptionManagerImpl implements SubscriptionManager { if (SubscriptionType.USER.toString().equalsIgnoreCase(subType)) { subscriptionList = subscriptionDAO - .getAppSubscribedUsers(offsetValue, limitValue, applicationReleaseId, tenantId); - count = subscriptionDAO.getSubscribedUserCount(applicationReleaseId, tenantId); - } else { - if (SubscriptionType.ROLE.toString().equalsIgnoreCase(subType)) { - subscriptionList = subscriptionDAO - .getAppSubscribedRoles(offsetValue, limitValue, applicationReleaseId, tenantId); - count = subscriptionDAO.getSubscribedRoleCount(applicationReleaseId, tenantId); - } else { - if (SubscriptionType.GROUP.toString().equalsIgnoreCase(subType)) { - subscriptionList = subscriptionDAO - .getAppSubscribedGroups(offsetValue, limitValue, applicationReleaseId, tenantId); - count = subscriptionDAO.getSubscribedGroupCount(applicationReleaseId, tenantId); - } - } + .getAppSubscribedUsers(offsetValue, limitValue, applicationReleaseId, tenantId, uninstalled, searchName); + count = subscriptionDAO.getSubscribedUserCount(applicationReleaseId, tenantId, uninstalled, searchName); + } else if (SubscriptionType.ROLE.toString().equalsIgnoreCase(subType)) { + subscriptionList = subscriptionDAO + .getAppSubscribedRoles(offsetValue, limitValue, applicationReleaseId, tenantId, uninstalled, searchName); + count = subscriptionDAO.getSubscribedRoleCount(applicationReleaseId, tenantId, uninstalled, searchName); + } else if (SubscriptionType.GROUP.toString().equalsIgnoreCase(subType)) { + subscriptionList = subscriptionDAO + .getAppSubscribedGroups(offsetValue, limitValue, applicationReleaseId, tenantId, uninstalled, searchName); + count = subscriptionDAO.getSubscribedGroupCount(applicationReleaseId, tenantId, uninstalled, searchName); } paginationResult.setData(subscriptionList); diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/ApplicationManagementServiceComponent.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/ApplicationManagementServiceComponent.java index d1b8ff8288..f3e6b56b50 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/ApplicationManagementServiceComponent.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/ApplicationManagementServiceComponent.java @@ -33,60 +33,33 @@ import io.entgra.device.mgt.core.application.mgt.core.impl.FileTransferServiceIm import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; import io.entgra.device.mgt.core.application.mgt.core.task.ScheduledAppSubscriptionTaskManager; import io.entgra.device.mgt.core.application.mgt.core.util.ApplicationManagementUtil; -import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import io.entgra.device.mgt.core.tenant.mgt.common.spi.TenantManagerAdminService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.ntask.core.service.TaskService; import org.wso2.carbon.user.core.service.RealmService; import java.util.List; -/** - * @scr.component name="org.wso2.carbon.application.mgt.service" immediate="true" - * @scr.reference name="org.wso2.carbon.device.manager" - * interface="io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDeviceManagementService" - * unbind="unsetDeviceManagementService" - * @scr.reference name="realm.service" - * immediate="true" - * interface="org.wso2.carbon.user.core.service.RealmService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRealmService" - * unbind="unsetRealmService" - * @scr.reference name="datasource.service" - * interface="org.wso2.carbon.ndatasource.core.DataSourceService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDataSourceService" - * unbind="unsetDataSourceService" - * @scr.reference name="app.mgt.ntask.component" - * interface="org.wso2.carbon.ntask.core.service.TaskService" - * cardinality="1..1" - * policy="dynamic" - * bind="setTaskService" - * unbind="unsetTaskService" - * @scr.reference name="io.entgra.device.mgt.core.tenant.manager" - * interface="io.entgra.device.mgt.core.tenant.mgt.common.spi.TenantManagerAdminService" - * cardinality="0..1" - * policy="dynamic" - * bind="setTenantManagementAdminService" - * unbind="unsetTenantManagementAdminService" - */ + @SuppressWarnings("unused") +@Component( + name = "io.entgra.device.mgt.core.application.mgt.core.internal.ApplicationManagementServiceComponent", + immediate = true) public class ApplicationManagementServiceComponent { private static Log log = LogFactory.getLog(ApplicationManagementServiceComponent.class); @SuppressWarnings("unused") + @Activate protected void activate(ComponentContext componentContext) { BundleContext bundleContext = componentContext.getBundleContext(); try { @@ -147,11 +120,18 @@ public class ApplicationManagementServiceComponent { } @SuppressWarnings("unused") + @Deactivate protected void deactivate(ComponentContext componentContext) { //do nothing } @SuppressWarnings("unused") + @Reference( + name = "device.mgt.provider.service", + service = io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDeviceManagementService") protected void setDeviceManagementService(DeviceManagementProviderService deviceManagementProviderService) { if (log.isDebugEnabled()) { log.debug("Setting ApplicationDTO Management OSGI Manager"); @@ -168,6 +148,12 @@ public class ApplicationManagementServiceComponent { } @SuppressWarnings("unused") + @Reference( + name = "realm.service", + service = org.wso2.carbon.user.core.service.RealmService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRealmService") protected void setRealmService(RealmService realmService) { DataHolder.getInstance().setRealmService(realmService); } @@ -178,6 +164,12 @@ public class ApplicationManagementServiceComponent { } @SuppressWarnings("unused") + @Reference( + name = "datasource.service", + service = org.wso2.carbon.ndatasource.core.DataSourceService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDataSourceService") protected void setDataSourceService(DataSourceService dataSourceService) { /*Not implemented. Not needed but to make sure the datasource service are registered, as it is needed create databases. */ @@ -190,6 +182,12 @@ public class ApplicationManagementServiceComponent { } @SuppressWarnings("unused") + @Reference( + name = "task.service", + service = org.wso2.carbon.ntask.core.service.TaskService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetTaskService") public void setTaskService(TaskService taskService) { if (log.isDebugEnabled()) { log.debug("Setting the task service to Application Management SC."); @@ -204,20 +202,4 @@ public class ApplicationManagementServiceComponent { } DataHolder.getInstance().setTaskService(null); } - - @SuppressWarnings("unused") - protected void setTenantManagementAdminService(TenantManagerAdminService tenantManagerAdminService) { - if (log.isDebugEnabled()) { - log.debug("Setting Tenant management admin Service"); - } - DataHolder.getInstance().setTenantManagerAdminService(tenantManagerAdminService); - } - - @SuppressWarnings("unused") - protected void unsetTenantManagementAdminService(TenantManagerAdminService tenantManagerAdminService) { - if (log.isDebugEnabled()) { - log.debug("Un setting Tenant management admin service"); - } - DataHolder.getInstance().setTenantManagerAdminService(null); - } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/DataHolder.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/DataHolder.java index c67db70fb6..80416dcd59 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/DataHolder.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/DataHolder.java @@ -27,8 +27,6 @@ import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionMan import io.entgra.device.mgt.core.application.mgt.common.services.VPPApplicationManager; import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import io.entgra.device.mgt.core.tenant.mgt.common.spi.TenantManagerAdminService; -import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.ntask.core.service.TaskService; import org.wso2.carbon.user.core.service.RealmService; @@ -59,7 +57,6 @@ public class DataHolder { private TaskService taskService; private FileTransferService fileTransferService; - private TenantManagerAdminService tenantManagerAdminService; private static final DataHolder applicationMgtDataHolder = new DataHolder(); @@ -166,12 +163,4 @@ public class DataHolder { public void setFileTransferService(FileTransferService fileTransferService) { this.fileTransferService = fileTransferService; } - - public TenantManagerAdminService getTenantManagerAdminService() { - return tenantManagerAdminService; - } - - public void setTenantManagerAdminService(TenantManagerAdminService tenantManagerAdminService) { - this.tenantManagerAdminService = tenantManagerAdminService; - } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/lifecycle/LifecycleStateManager.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/lifecycle/LifecycleStateManager.java index 5b69013f9c..8e087eb7f5 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/lifecycle/LifecycleStateManager.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/lifecycle/LifecycleStateManager.java @@ -18,14 +18,14 @@ package io.entgra.device.mgt.core.application.mgt.core.lifecycle; -import io.entgra.device.mgt.core.application.mgt.core.internal.DataHolder; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.application.mgt.common.exception.LifecycleManagementException; import io.entgra.device.mgt.core.application.mgt.common.config.LifecycleState; +import io.entgra.device.mgt.core.application.mgt.common.exception.LifecycleManagementException; +import io.entgra.device.mgt.core.application.mgt.core.internal.DataHolder; import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException; import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionUtils; import io.entgra.device.mgt.core.device.mgt.core.search.mgt.Constants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/serviceprovider/impl/WSO2IAMSPApplicationService.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/serviceprovider/impl/WSO2IAMSPApplicationService.java index 88b8ba803d..8858ff921e 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/serviceprovider/impl/WSO2IAMSPApplicationService.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/serviceprovider/impl/WSO2IAMSPApplicationService.java @@ -26,6 +26,7 @@ import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationMan import io.entgra.device.mgt.core.application.mgt.common.exception.IdentityServerManagementException; import io.entgra.device.mgt.core.application.mgt.core.serviceprovider.ISServiceProviderApplicationService; import io.entgra.device.mgt.core.application.mgt.core.util.Constants; +import io.entgra.device.mgt.core.device.mgt.core.common.util.HttpUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpResponse; @@ -35,7 +36,7 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; -import io.entgra.device.mgt.core.device.mgt.core.common.util.HttpUtil; + import javax.ws.rs.core.HttpHeaders; import java.io.IOException; import java.util.Collections; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionCleanupTask.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionCleanupTask.java index 71dc4e87b0..799eea1203 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionCleanupTask.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionCleanupTask.java @@ -18,12 +18,12 @@ package io.entgra.device.mgt.core.application.mgt.core.task; -import io.entgra.device.mgt.core.application.mgt.core.impl.SubscriptionManagerImpl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.application.mgt.common.exception.SubscriptionManagementException; import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; +import io.entgra.device.mgt.core.application.mgt.core.impl.SubscriptionManagerImpl; import io.entgra.device.mgt.core.device.mgt.core.task.impl.RandomlyAssignedScheduleTask; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.util.Map; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionTask.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionTask.java index ffdce8e469..051c66e720 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionTask.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionTask.java @@ -20,20 +20,20 @@ package io.entgra.device.mgt.core.application.mgt.core.task; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; -import io.entgra.device.mgt.core.application.mgt.core.impl.SubscriptionManagerImpl; -import io.entgra.device.mgt.core.application.mgt.core.util.Constants; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.application.mgt.common.ExecutionStatus; import io.entgra.device.mgt.core.application.mgt.common.SubscriptionType; import io.entgra.device.mgt.core.application.mgt.common.dto.ScheduledSubscriptionDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; import io.entgra.device.mgt.core.application.mgt.common.exception.SubscriptionManagementException; import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; +import io.entgra.device.mgt.core.application.mgt.core.impl.SubscriptionManagerImpl; +import io.entgra.device.mgt.core.application.mgt.core.util.Constants; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.core.task.impl.RandomlyAssignedScheduleTask; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.util.List; import java.util.Map; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionTaskManager.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionTaskManager.java index 2064e1195d..325c2d8b9d 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionTaskManager.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionTaskManager.java @@ -19,6 +19,12 @@ package io.entgra.device.mgt.core.application.mgt.core.task; import com.google.gson.Gson; +import io.entgra.device.mgt.core.application.mgt.common.SubAction; +import io.entgra.device.mgt.core.application.mgt.common.SubscriptionType; +import io.entgra.device.mgt.core.application.mgt.common.dto.ScheduledSubscriptionDTO; +import io.entgra.device.mgt.core.application.mgt.common.exception.SubscriptionManagementException; +import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; +import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationOperationTaskException; import io.entgra.device.mgt.core.application.mgt.core.impl.SubscriptionManagerImpl; import io.entgra.device.mgt.core.application.mgt.core.internal.DataHolder; import io.entgra.device.mgt.core.application.mgt.core.util.Constants; @@ -27,24 +33,12 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.quartz.CronExpression; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.application.mgt.common.SubAction; -import io.entgra.device.mgt.core.application.mgt.common.SubscriptionType; -import io.entgra.device.mgt.core.application.mgt.common.dto.ScheduledSubscriptionDTO; -import io.entgra.device.mgt.core.application.mgt.common.exception.SubscriptionManagementException; -import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; -import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationOperationTaskException; import org.wso2.carbon.ntask.common.TaskException; import org.wso2.carbon.ntask.core.TaskInfo; import org.wso2.carbon.ntask.core.TaskManager; import org.wso2.carbon.ntask.core.service.TaskService; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Properties; +import java.util.*; import java.util.stream.Collectors; public class ScheduledAppSubscriptionTaskManager { @@ -164,7 +158,7 @@ public class ScheduledAppSubscriptionTaskManager { TaskManager taskManager = taskService.getTaskManager(SCHEDULED_APP_SUBSCRIPTION_TASK_TYPE); TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo(); - triggerInfo.setCronExpression("0 0 0/24 ? * * *"); + triggerInfo.setCronExpression("0 0 0 ? * * *"); String taskName = "SCHEDULED_APP_SUBSCRIPTION_CLEANUP_TASK"; TaskInfo taskInfo = new TaskInfo(taskName, ScheduledAppSubscriptionCleanupTask.class.getName(), null, diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/APIUtil.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/APIUtil.java index 7c2034eb11..4a0687052a 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/APIUtil.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/APIUtil.java @@ -18,41 +18,34 @@ package io.entgra.device.mgt.core.application.mgt.core.util; +import io.entgra.device.mgt.core.application.mgt.common.ApplicationType; +import io.entgra.device.mgt.core.application.mgt.common.ErrorResponse; import io.entgra.device.mgt.core.application.mgt.common.IdentityServerResponse; +import io.entgra.device.mgt.core.application.mgt.common.config.MDMConfig; +import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.IdentityServerDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.IdentityServiceProviderDTO; +import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; import io.entgra.device.mgt.core.application.mgt.common.exception.InvalidConfigurationException; +import io.entgra.device.mgt.core.application.mgt.common.response.Application; +import io.entgra.device.mgt.core.application.mgt.common.response.ApplicationRelease; +import io.entgra.device.mgt.core.application.mgt.common.services.*; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.*; +import io.entgra.device.mgt.core.application.mgt.core.config.ConfigurationManager; import io.entgra.device.mgt.core.application.mgt.core.config.IdentityServiceProvider; -import io.entgra.device.mgt.core.application.mgt.core.serviceprovider.ISServiceProviderApplicationService; import io.entgra.device.mgt.core.application.mgt.core.exception.BadRequestException; import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException; +import io.entgra.device.mgt.core.application.mgt.core.internal.DataHolder; +import io.entgra.device.mgt.core.application.mgt.core.serviceprovider.ISServiceProviderApplicationService; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; +import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.validator.routines.UrlValidator; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.application.mgt.common.ApplicationType; -import io.entgra.device.mgt.core.application.mgt.common.config.MDMConfig; -import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; -import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO; -import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; -import io.entgra.device.mgt.core.application.mgt.common.response.Application; -import io.entgra.device.mgt.core.application.mgt.common.response.ApplicationRelease; -import io.entgra.device.mgt.core.application.mgt.common.services.*; -import io.entgra.device.mgt.core.application.mgt.common.ErrorResponse; -import io.entgra.device.mgt.core.application.mgt.common.wrapper.CustomAppReleaseWrapper; -import io.entgra.device.mgt.core.application.mgt.common.wrapper.CustomAppWrapper; -import io.entgra.device.mgt.core.application.mgt.common.wrapper.EntAppReleaseWrapper; -import io.entgra.device.mgt.core.application.mgt.common.wrapper.ApplicationWrapper; -import io.entgra.device.mgt.core.application.mgt.common.wrapper.PublicAppReleaseWrapper; -import io.entgra.device.mgt.core.application.mgt.common.wrapper.PublicAppWrapper; -import io.entgra.device.mgt.core.application.mgt.common.wrapper.WebAppReleaseWrapper; -import io.entgra.device.mgt.core.application.mgt.common.wrapper.WebAppWrapper; -import io.entgra.device.mgt.core.application.mgt.core.config.ConfigurationManager; -import io.entgra.device.mgt.core.application.mgt.core.internal.DataHolder; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import javax.ws.rs.core.Response; import java.util.ArrayList; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationManagementUtil.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationManagementUtil.java index 6374aadb13..f9119832ce 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationManagementUtil.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationManagementUtil.java @@ -65,7 +65,6 @@ import io.entgra.device.mgt.core.device.mgt.core.common.util.FileUtil; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.MetadataManagementServiceImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.jetbrains.annotations.NotNull; import java.io.ByteArrayOutputStream; import java.io.File; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationMgtDatabaseCreator.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationMgtDatabaseCreator.java index 7114a1cfef..bea6f41519 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationMgtDatabaseCreator.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationMgtDatabaseCreator.java @@ -22,6 +22,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.dbcreator.DatabaseCreator; + import java.io.File; /** diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ArtifactsParser.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ArtifactsParser.java index 7062a01c1d..16d7d530ba 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ArtifactsParser.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ArtifactsParser.java @@ -22,20 +22,14 @@ import com.dd.plist.BinaryPropertyListParser; import com.dd.plist.NSDictionary; import com.dd.plist.PropertyListFormatException; import com.dd.plist.PropertyListParser; +import io.entgra.device.mgt.core.application.mgt.core.exception.ParsingException; import net.dongliu.apk.parser.ApkFile; import net.dongliu.apk.parser.bean.ApkMeta; +import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.commons.io.IOUtils; -import io.entgra.device.mgt.core.application.mgt.core.exception.ParsingException; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import java.nio.file.Files; import java.util.UUID; import java.util.zip.ZipEntry; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ConnectionManagerUtil.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ConnectionManagerUtil.java index 2d917eb42f..cddf207090 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ConnectionManagerUtil.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ConnectionManagerUtil.java @@ -17,16 +17,16 @@ */ package io.entgra.device.mgt.core.application.mgt.core.util; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; import io.entgra.device.mgt.core.application.mgt.common.exception.IllegalTransactionStateException; import io.entgra.device.mgt.core.application.mgt.common.exception.TransactionManagementException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; -import java.sql.Connection; -import java.sql.SQLException; import javax.naming.InitialContext; import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; /** * ConnectionManagerUtil is responsible for handling all the datasource connections utilities. diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/Constants.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/Constants.java index 0b22db0668..81e5bef788 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/Constants.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/Constants.java @@ -96,6 +96,9 @@ public class Constants { public static final String MSI = "MSI"; public static final String APPX = "APPX"; + public static final String ENTERPRISE_APP_TYPE = "ENTERPRISE"; + public static final String PUBLIC_APP_TYPE = "ENTERPRISE"; + private static final Map AGENT_DATA = new HashMap<>(); static { AGENT_DATA.put("android", "android-agent.apk"); diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/HelperUtil.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/HelperUtil.java index d97d8df307..38c939ab34 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/HelperUtil.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/HelperUtil.java @@ -17,11 +17,11 @@ */ package io.entgra.device.mgt.core.application.mgt.core.util; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderService; /** * Utility methods used in the Application Management. diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/OAuthUtils.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/OAuthUtils.java index 87b04db75a..96e4c40fd1 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/OAuthUtils.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/OAuthUtils.java @@ -18,17 +18,17 @@ package io.entgra.device.mgt.core.application.mgt.core.util; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService; import io.entgra.device.mgt.core.apimgt.application.extension.dto.ApiApplicationKey; import io.entgra.device.mgt.core.apimgt.application.extension.exception.APIManagerException; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.application.mgt.common.dto.ApiRegistrationProfile; import io.entgra.device.mgt.core.identity.jwt.client.extension.JWTClient; import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.AccessTokenInfo; import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; @@ -55,16 +55,18 @@ public class OAuthUtils { try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(PrivilegedCarbonContext. - getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration().getAdminUserName()); + String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() + .getRealmConfiguration().getAdminUserName(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); APIManagementProviderService apiManagementProviderService = (APIManagementProviderService) ctx. getOSGiService(APIManagementProviderService.class, null); apiApplicationKeyInfo = apiManagementProviderService. generateAndRetrieveApplicationKeys(registrationProfile.getApplicationName(), registrationProfile.getTags(), Constants.ApplicationInstall.DEFAULT_TOKEN_TYPE, - null, registrationProfile.isAllowedToAllDomains(), - Constants.ApplicationInstall.DEFAULT_VALIDITY_PERIOD); + username, registrationProfile.isAllowedToAllDomains(), + Constants.ApplicationInstall.DEFAULT_VALIDITY_PERIOD, PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() + .getRealmConfiguration().getAdminPassword(), null, null, null, false); } finally { PrivilegedCarbonContext.endTenantFlow(); } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/ArtifactParserTest.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/ArtifactParserTest.java index c067e42775..f21f26f97e 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/ArtifactParserTest.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/ArtifactParserTest.java @@ -19,11 +19,11 @@ package io.entgra.device.mgt.core.application.mgt.core; import com.dd.plist.NSDictionary; +import io.entgra.device.mgt.core.application.mgt.core.exception.ParsingException; +import io.entgra.device.mgt.core.application.mgt.core.util.ArtifactsParser; import net.dongliu.apk.parser.bean.ApkMeta; import org.testng.Assert; import org.testng.annotations.Test; -import io.entgra.device.mgt.core.application.mgt.core.exception.ParsingException; -import io.entgra.device.mgt.core.application.mgt.core.util.ArtifactsParser; import java.io.FileInputStream; import java.io.FileNotFoundException; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/BaseTestCase.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/BaseTestCase.java index 7251a0d19e..fd11a7f292 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/BaseTestCase.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/BaseTestCase.java @@ -17,13 +17,6 @@ */ package io.entgra.device.mgt.core.application.mgt.core; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.tomcat.jdbc.pool.PoolProperties; -import org.testng.annotations.BeforeSuite; -import org.w3c.dom.Document; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.application.mgt.common.config.LifecycleState; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; import io.entgra.device.mgt.core.application.mgt.core.common.DataSourceConfig; @@ -38,6 +31,13 @@ import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.tomcat.jdbc.pool.PoolProperties; +import org.testng.annotations.BeforeSuite; +import org.w3c.dom.Document; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.registry.core.config.RegistryContext; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.internal.RegistryDataHolder; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/ConfigurationTest.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/ConfigurationTest.java index 096a36382e..9afe01cb89 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/ConfigurationTest.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/ConfigurationTest.java @@ -17,11 +17,11 @@ */ package io.entgra.device.mgt.core.application.mgt.core; -import org.junit.Assert; -import org.testng.annotations.Test; +import io.entgra.device.mgt.core.application.mgt.common.config.LifecycleState; import io.entgra.device.mgt.core.application.mgt.core.config.Configuration; import io.entgra.device.mgt.core.application.mgt.core.config.ConfigurationManager; -import io.entgra.device.mgt.core.application.mgt.common.config.LifecycleState; +import org.junit.Assert; +import org.testng.annotations.Test; import java.util.List; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/InitTest.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/InitTest.java index b4ec9f3b9d..0674369256 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/InitTest.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/InitTest.java @@ -17,9 +17,9 @@ */ package io.entgra.device.mgt.core.application.mgt.core; -import org.testng.annotations.BeforeSuite; import io.entgra.device.mgt.core.application.mgt.common.exception.InvalidConfigurationException; import io.entgra.device.mgt.core.application.mgt.core.config.ConfigurationManager; +import org.testng.annotations.BeforeSuite; import java.io.File; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/LifeCycleStateManagerTest.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/LifeCycleStateManagerTest.java index 8f2a48f7bd..96dd59ecd3 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/LifeCycleStateManagerTest.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/LifeCycleStateManagerTest.java @@ -17,8 +17,8 @@ */ package io.entgra.device.mgt.core.application.mgt.core; -import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; import io.entgra.device.mgt.core.application.mgt.common.config.LifecycleState; +import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; import java.util.HashMap; import java.util.List; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/LifecycleManagementTest.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/LifecycleManagementTest.java index 605c446491..ef8bc7b3d9 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/LifecycleManagementTest.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/LifecycleManagementTest.java @@ -17,14 +17,14 @@ */ package io.entgra.device.mgt.core.application.mgt.core; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; +import io.entgra.device.mgt.core.application.mgt.common.config.LifecycleState; import io.entgra.device.mgt.core.application.mgt.common.exception.LifecycleManagementException; import io.entgra.device.mgt.core.application.mgt.core.config.Configuration; import io.entgra.device.mgt.core.application.mgt.core.config.ConfigurationManager; import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; -import io.entgra.device.mgt.core.application.mgt.common.config.LifecycleState; +import org.junit.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import java.util.List; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/StorageManagementUtilTest.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/StorageManagementUtilTest.java index eb26d08551..3448f67ed3 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/StorageManagementUtilTest.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/StorageManagementUtilTest.java @@ -18,13 +18,13 @@ package io.entgra.device.mgt.core.application.mgt.core; +import io.entgra.device.mgt.core.application.mgt.common.exception.ResourceManagementException; +import io.entgra.device.mgt.core.device.mgt.core.common.exception.StorageManagementException; +import io.entgra.device.mgt.core.device.mgt.core.common.util.StorageManagementUtil; import org.junit.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import io.entgra.device.mgt.core.application.mgt.common.exception.ResourceManagementException; -import io.entgra.device.mgt.core.device.mgt.core.common.exception.StorageManagementException; -import io.entgra.device.mgt.core.device.mgt.core.common.util.StorageManagementUtil; import java.io.File; import java.io.FileInputStream; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationManagementDAOTest.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationManagementDAOTest.java index 3712b8cd27..322d9484ee 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationManagementDAOTest.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationManagementDAOTest.java @@ -17,11 +17,6 @@ */ package io.entgra.device.mgt.core.application.mgt.core.dao; -import junit.framework.Assert; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import io.entgra.device.mgt.core.application.mgt.core.BaseTestCase; import io.entgra.device.mgt.core.application.mgt.core.config.ConfigurationManager; import io.entgra.device.mgt.core.application.mgt.core.dao.common.ApplicationManagementDAOFactory; @@ -32,6 +27,11 @@ import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagem import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceTypeDAO; +import junit.framework.Assert; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; public class ApplicationManagementDAOTest extends BaseTestCase { diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/management/ApplicationManagementTest.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/management/ApplicationManagementTest.java index 793b28d0f9..6ba0305ba0 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/management/ApplicationManagementTest.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/management/ApplicationManagementTest.java @@ -39,9 +39,9 @@ import io.entgra.device.mgt.core.application.mgt.common.response.ApplicationRele import io.entgra.device.mgt.core.application.mgt.common.response.Category; import io.entgra.device.mgt.core.application.mgt.common.response.Tag; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; -import io.entgra.device.mgt.core.application.mgt.common.wrapper.EntAppReleaseWrapper; import io.entgra.device.mgt.core.application.mgt.common.wrapper.ApplicationUpdateWrapper; import io.entgra.device.mgt.core.application.mgt.common.wrapper.ApplicationWrapper; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.EntAppReleaseWrapper; import io.entgra.device.mgt.core.application.mgt.core.BaseTestCase; import io.entgra.device.mgt.core.application.mgt.core.dao.ApplicationDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.common.ApplicationManagementDAOFactory; @@ -49,12 +49,17 @@ import io.entgra.device.mgt.core.application.mgt.core.dto.ApplicationsDTO; import io.entgra.device.mgt.core.application.mgt.core.impl.ApplicationManagerImpl; import io.entgra.device.mgt.core.application.mgt.core.internal.DataHolder; import io.entgra.device.mgt.core.application.mgt.core.util.ConnectionManagerUtil; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.Base64File; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.core.common.util.FileUtil; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceTypeVersion; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; import java.io.File; import java.io.FileInputStream; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/resources/user-test/user-mgt-registry-test.xml b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/resources/user-test/user-mgt-registry-test.xml index fc32a2698d..96fd6acfff 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/resources/user-test/user-mgt-registry-test.xml +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/resources/user-test/user-mgt-registry-test.xml @@ -27,7 +27,7 @@ everyone false 500 - jdbc:h2:target/databasetest/CARBON_TEST + jdbc:h2:./target/databasetest/CARBON_TEST org.h2.Driver 50 60000 diff --git a/components/application-mgt/pom.xml b/components/application-mgt/pom.xml index b130f15b05..c4a50c3705 100644 --- a/components/application-mgt/pom.xml +++ b/components/application-mgt/pom.xml @@ -31,7 +31,7 @@ pom WSO2 Carbon - Application Management Component WSO2 Carbon - Application Management Component - http://wso2.org + https://entgra.io io.entgra.device.mgt.core.application.mgt.common @@ -46,22 +46,5 @@ ${maven.checkstyle.vesion} - - - - org.apache.felix - maven-scr-plugin - 1.7.2 - - - generate-scr-scrdescriptor - - scr - - - - - - diff --git a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.admin.api/pom.xml b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.admin.api/pom.xml index 7f89c759df..c75eae5479 100644 --- a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.admin.api/pom.xml +++ b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.admin.api/pom.xml @@ -154,11 +154,11 @@ - - org.wso2.carbon - org.wso2.carbon.logging - provided - + + + + + io.swagger swagger-jaxrs diff --git a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.common/pom.xml b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.common/pom.xml index dc4dd90442..9e8060e0b8 100644 --- a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.common/pom.xml +++ b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.common/pom.xml @@ -36,8 +36,12 @@ - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -59,6 +63,32 @@ + + org.jacoco + jacoco-maven-plugin + + ${basedir}/target/coverage-reports/jacoco-unit.exec + + + + jacoco-initialize + + prepare-agent + + + + jacoco-site + test + + report + + + ${basedir}/target/coverage-reports/jacoco-unit.exec + ${basedir}/target/coverage-reports/site + + + + diff --git a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.core/pom.xml b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.core/pom.xml index 84853ec469..a09c92436a 100644 --- a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.core/pom.xml +++ b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.core/pom.xml @@ -35,8 +35,12 @@ - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -74,12 +78,9 @@ - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services + org.apache.felix + org.apache.felix.scr.ds-annotations + provided org.wso2.carbon diff --git a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.core/src/main/java/io/entgra/device/mgt/core/cea/mgt/core/internal/CEAManagementServiceComponent.java b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.core/src/main/java/io/entgra/device/mgt/core/cea/mgt/core/internal/CEAManagementServiceComponent.java index 624391eb7c..007134a78d 100644 --- a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.core/src/main/java/io/entgra/device/mgt/core/cea/mgt/core/internal/CEAManagementServiceComponent.java +++ b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.core/src/main/java/io/entgra/device/mgt/core/cea/mgt/core/internal/CEAManagementServiceComponent.java @@ -29,34 +29,17 @@ import io.entgra.device.mgt.core.cea.mgt.core.task.CEAPolicyMonitoringTaskManage import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.ntask.core.service.TaskService; -/** - * @scr.component name="io.entgra.device.mgt.core.cea.mgt.core.CEAManagementServiceComponent" immediate="true" - * @scr.reference name="org.wso2.carbon.ndatasource" - * interface="org.wso2.carbon.ndatasource.core.DataSourceService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDataSourceService" - * unbind="unsetDataSourceService" - * @scr.reference name="io.entgra.device.mgt.core.cea.mgt.enforcementServiceManager" - * interface="io.entgra.device.mgt.core.cea.mgt.common.service.EnforcementServiceManager" - * cardinality="1..1" - * policy="dynamic" - * bind="setEnforcementServiceManager" - * unbind="unsetEnforcementServiceManager" - * @scr.reference name="ntask.component" - * interface="org.wso2.carbon.ntask.core.service.TaskService" - * cardinality="1..1" - * policy="dynamic" - * bind="setTaskService" - * unbind="unsetTaskService" - */ - +@Component( + name = "io.entgra.device.mgt.core.cea.mgt.core.CEAManagementServiceComponent", + immediate = true) public class CEAManagementServiceComponent { private static final Log log = LogFactory.getLog(CEAManagementServiceComponent.class); + @Activate protected void activate(ComponentContext componentContext) { try { CEAConfigManager ceaConfigManager = CEAConfigManager.getInstance(); @@ -72,6 +55,13 @@ public class CEAManagementServiceComponent { } } + @Reference( + name = "org.wso2.carbon.ndatasource", + service = org.wso2.carbon.ndatasource.core.DataSourceService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + bind = "setDataSourceService", + unbind = "unsetDataSourceService") protected void setDataSourceService(DataSourceService dataSourceService) { // This is to avoid cea management component getting initialized before the underlying datasource registered } @@ -80,6 +70,13 @@ public class CEAManagementServiceComponent { // Do nothing } + @Reference( + name = "io.entgra.device.mgt.core.cea.mgt.enforcementServiceManager", + service = io.entgra.device.mgt.core.cea.mgt.common.service.EnforcementServiceManager.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + bind = "setEnforcementServiceManager", + unbind = "unsetEnforcementServiceManager") protected void setEnforcementServiceManager(EnforcementServiceManager enforcementServiceManager) { CEAManagementDataHolder.getInstance().setEnforcementServiceManager(enforcementServiceManager); if (log.isDebugEnabled()) { @@ -94,6 +91,13 @@ public class CEAManagementServiceComponent { } } + @Reference( + name = "ntask.component", + service = org.wso2.carbon.ntask.core.service.TaskService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + bind = "setTaskService", + unbind = "unsetTaskService") protected void setTaskService(TaskService taskService) { CEAManagementDataHolder.getInstance().setTaskService(taskService); if (log.isDebugEnabled()) { diff --git a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.enforce/pom.xml b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.enforce/pom.xml index 4521458fed..c22f147d82 100644 --- a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.enforce/pom.xml +++ b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.enforce/pom.xml @@ -35,8 +35,12 @@ - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -68,18 +72,49 @@ + + org.jacoco + jacoco-maven-plugin + + ${basedir}/target/coverage-reports/jacoco-unit.exec + + + + jacoco-initialize + + prepare-agent + + + + jacoco-site + test + + report + + + ${basedir}/target/coverage-reports/jacoco-unit.exec + ${basedir}/target/coverage-reports/site + + + + - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + + + + + + + + com.google.code.gson gson diff --git a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.enforce/src/main/java/io/entgra/device/mgt/core/cea/mgt/enforce/internal/EnforcementServiceComponent.java b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.enforce/src/main/java/io/entgra/device/mgt/core/cea/mgt/enforce/internal/EnforcementServiceComponent.java index d890eb62f0..29e69dcfd9 100644 --- a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.enforce/src/main/java/io/entgra/device/mgt/core/cea/mgt/enforce/internal/EnforcementServiceComponent.java +++ b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.enforce/src/main/java/io/entgra/device/mgt/core/cea/mgt/enforce/internal/EnforcementServiceComponent.java @@ -25,27 +25,16 @@ import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProvide import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.user.core.service.RealmService; -/** - * @scr.component name="io.entgra.device.mgt.core.cea.mgt.enforcementServiceManager" immediate="true" - * @scr.reference name="org.wso2.carbon.device.manager" - * interface="io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDeviceManagementServiceProviderService" - * unbind="unsetDeviceManagementServiceProviderService" - * @scr.reference name="user.realmservice.default" - * interface="org.wso2.carbon.user.core.service.RealmService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRealmService" - * unbind="unsetRealmService" - */ - +@Component( + name = "io.entgra.device.mgt.core.cea.mgt.enforcementServiceManager", + immediate = true) public class EnforcementServiceComponent { private static final Log log = LogFactory.getLog(EnforcementServiceComponent.class); + @Activate protected void activate(ComponentContext componentContext) { try { EnforcementServiceManager enforcementServiceManager = new EnforcementServiceManagerImpl(); @@ -60,6 +49,13 @@ public class EnforcementServiceComponent { } } + @Reference( + name = "org.wso2.carbon.device.manager", + service = io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + bind = "setDeviceManagementServiceProviderService", + unbind = "unsetDeviceManagementServiceProviderService") protected void setDeviceManagementServiceProviderService(DeviceManagementProviderService deviceManagementProviderService) { EnforcementServiceComponentDataHolder.getInstance().setDeviceManagementProviderService(deviceManagementProviderService); if (log.isDebugEnabled()) { @@ -74,6 +70,13 @@ public class EnforcementServiceComponent { } } + @Reference( + name = "user.realmservice.default", + service = org.wso2.carbon.user.core.service.RealmService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + bind = "setRealmService", + unbind = "unsetRealmService") protected void setRealmService(RealmService realmService) { EnforcementServiceComponentDataHolder.getInstance().setRealmService(realmService); if (log.isDebugEnabled()) { diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/pom.xml b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/pom.xml index f4a992e2af..bf1dee7058 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/pom.xml +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/pom.xml @@ -31,16 +31,13 @@ war WSO2 Carbon - Certificate Management API WSO2 Carbon - Certificate Management API - http://wso2.org + https://entgra.io maven-compiler-plugin - - 1.8 - 1.8 - + maven-war-plugin @@ -87,7 +84,6 @@ org.apache.maven.plugins maven-antrun-plugin - 1.7 compile @@ -117,7 +113,6 @@ org.codehaus.mojo exec-maven-plugin - 1.2.1 test @@ -133,6 +128,10 @@ + + org.wso2.orbit.com.fasterxml.jackson.core + jackson-annotations + org.springframework spring-web @@ -160,8 +159,8 @@ test - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api provided @@ -206,6 +205,14 @@ io.entgra.device.mgt.core.apimgt.annotations provided + + com.google.code.gson + gson + + + org.wso2.orbit.javax.xml.bind + jaxb-api + diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/api/impl/CertificateMgtServiceImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/api/impl/CertificateMgtServiceImpl.java index 35d0ade404..c0bb953453 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/api/impl/CertificateMgtServiceImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/api/impl/CertificateMgtServiceImpl.java @@ -18,15 +18,15 @@ package io.entgra.device.mgt.core.certificate.mgt.api.impl; +import io.entgra.device.mgt.core.certificate.mgt.api.CertificateMgtService; +import io.entgra.device.mgt.core.certificate.mgt.api.beans.ErrorResponse; +import io.entgra.device.mgt.core.certificate.mgt.api.exception.Message; +import io.entgra.device.mgt.core.certificate.mgt.api.exception.UnexpectedServerErrorException; +import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreException; +import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; import org.apache.commons.codec.binary.Base64; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreException; -import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; -import io.entgra.device.mgt.core.certificate.mgt.api.beans.ErrorResponse; -import io.entgra.device.mgt.core.certificate.mgt.api.exception.UnexpectedServerErrorException; -import io.entgra.device.mgt.core.certificate.mgt.api.CertificateMgtService; -import io.entgra.device.mgt.core.certificate.mgt.api.exception.Message; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/pom.xml b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/pom.xml index d2cf1432e2..3f9de89f2d 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/pom.xml +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/pom.xml @@ -31,16 +31,13 @@ war WSO2 Carbon - Admin Certificate Management API WSO2 Carbon - Admin Certificate Management API - http://wso2.org + https://entgra.io maven-compiler-plugin - - 1.8 - 1.8 - + maven-war-plugin @@ -87,7 +84,6 @@ org.apache.maven.plugins maven-antrun-plugin - 1.7 compile @@ -117,7 +113,6 @@ org.codehaus.mojo exec-maven-plugin - 1.2.1 test @@ -164,8 +159,8 @@ provided - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api provided @@ -207,6 +202,20 @@ io.entgra.device.mgt.core.apimgt.annotations provided + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.device.mgt.common + provided + + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.device.mgt.core + provided + + + org.wso2.orbit.javax.xml.bind + jaxb-api + diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/beans/CertificateList.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/beans/CertificateList.java index 68a9a219df..abafec48d7 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/beans/CertificateList.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/beans/CertificateList.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.beans; import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModelProperty; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; +import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java index 815e141f38..4b62253156 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java @@ -45,12 +45,15 @@ import io.entgra.device.mgt.core.certificate.mgt.core.scep.SCEPManager; import io.entgra.device.mgt.core.certificate.mgt.core.scep.TenantedDeviceWrapper; import io.entgra.device.mgt.core.certificate.mgt.core.service.CertificateManagementService; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import javax.ws.rs.*; import javax.ws.rs.core.Response; import java.security.cert.X509Certificate; import java.util.ArrayList; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/CertificateMgtAPIUtils.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/CertificateMgtAPIUtils.java index 737d9820a9..a8fa744869 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/CertificateMgtAPIUtils.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/CertificateMgtAPIUtils.java @@ -18,13 +18,13 @@ package io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.util; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.core.scep.SCEPManager; import io.entgra.device.mgt.core.certificate.mgt.core.service.CertificateManagementService; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.core.search.mgt.SearchManagerService; import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import javax.ws.rs.core.MediaType; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/RequestValidationUtil.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/RequestValidationUtil.java index 43f4d1ab48..8dfea3a2e9 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/RequestValidationUtil.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/RequestValidationUtil.java @@ -17,8 +17,8 @@ */ package io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.util; -import io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.beans.ErrorResponse; import io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.InputValidationException; +import io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.beans.ErrorResponse; public class RequestValidationUtil { diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml index 5259d27170..ff7cc19498 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml @@ -30,18 +30,21 @@ bundle WSO2 Carbon - Certificate Management Core WSO2 Carbon - Certificate Management Core - http://wso2.org + https://entgra.io - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix maven-bundle-plugin - 1.4.0 true @@ -54,51 +57,56 @@ io.entgra.device.mgt.core.certificate.mgt.core.util - org.osgi.framework.*;version="${imp.package.version.osgi.framework}", - org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.apache.commons.lang, - org.apache.commons.logging, - org.apache.commons.collections.map, + com.google.gson;version="[2.9,3)", + io.entgra.device.mgt.core.certificate.mgt.core.bean, + io.entgra.device.mgt.core.certificate.mgt.core.cache, + io.entgra.device.mgt.core.certificate.mgt.core.cache.impl, + io.entgra.device.mgt.core.certificate.mgt.core.config.datasource, + io.entgra.device.mgt.core.certificate.mgt.core.dao, + io.entgra.device.mgt.core.certificate.mgt.core.dto, + io.entgra.device.mgt.core.certificate.mgt.core.exception, + io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.exceptions;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.metadata.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.config;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.config.cache;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.service;version="[5.0,6)", + io.swagger.annotations;version="[1.6,2)", + javax.cache;version="[1.0,2)", + javax.naming, + javax.naming.ldap, javax.security.auth.x500, - javax.xml.*, - javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, - org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}", - org.bouncycastle.asn1, - org.bouncycastle.asn1.x500, - org.bouncycastle.asn1.x509, - org.bouncycastle.asn1.pkcs, - org.bouncycastle.cert; version="${bcprov.wso2.version.range}", - org.bouncycastle.cert.jcajce; version="${bcprov.wso2.version.range}", - org.bouncycastle.cms, - org.bouncycastle.jce.provider, - org.bouncycastle.operator, - org.bouncycastle.operator.jcajce, - org.bouncycastle.asn1.x500.style, - org.bouncycastle.pkcs, - org.wso2.carbon.user.core.tenant, - org.wso2.carbon.user.api, - org.wso2.carbon.user.core.service, - - org.bouncycastle.util, + javax.sql, + javax.xml.bind;version="[0.0,1)", + javax.xml.bind.annotation;version="[0.0,1)", + javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}", + org.apache.commons.codec.binary;version="[1.4,2)", + org.apache.commons.collections.map;version="[3.2,4)", + org.apache.commons.lang;version="[2.4,3)", + org.apache.commons.logging;version="[1.2,2)", + org.bouncycastle.asn1;version="[1.70,2)", + org.bouncycastle.asn1.pkcs;version="[1.70,2)", + org.bouncycastle.asn1.x500;version="[1.70,2)", + org.bouncycastle.asn1.x500.style;version="[1.70,2)", + org.bouncycastle.asn1.x509;version="[1.70,2)", + org.bouncycastle.cert;version="[1.70,2)", + org.bouncycastle.cert.jcajce;version="[1.70,2)", + org.bouncycastle.cms;version="[1.70,2)", + org.bouncycastle.jce.provider;version="[1.70,2)", + org.bouncycastle.operator;version="[1.70,2)", + org.bouncycastle.operator.jcajce;version="[1.70,2)", + org.bouncycastle.pkcs;version="[1.70,2)", + org.bouncycastle.util;version="[1.70,2)", org.jscep.message, - org.wso2.carbon.context, org.jscep.transaction, - org.w3c.dom, - org.xml.sax, - javax.sql, - - javax.naming, - javax.xml.bind.annotation, - javax.xml.bind, - org.wso2.carbon.utils.*, - io.entgra.device.mgt.core.device.mgt.common.*, - io.swagger.annotations.*;resolution:=optional, - io.entgra.device.mgt.core.device.mgt.core.*, - org.wso2.carbon.registry.indexing.*, - javax.cache.*, - javax.naming.ldap, - com.google.gson.* - + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", + org.w3c.dom,org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.user.api;version="[1.0,2)", + org.wso2.carbon.user.core.service;version="[4.8,5)", + org.wso2.carbon.user.core.tenant;version="[4.8,5)", + org.wso2.carbon.utils;version="[4.8,5)", + org.wso2.carbon.utils.dbcreator;version="[4.8,5)" !io.entgra.device.mgt.core.certificate.mgt.core.internal.*, @@ -111,8 +119,11 @@ org.apache.maven.plugins maven-surefire-plugin - 2.18 + + --add-opens=java.xml/jdk.xml.internal=ALL-UNNAMED + --add-opens=java.base/jdk.internal.loader=ALL-UNNAMED + src/test/resources/testng.xml @@ -120,6 +131,9 @@ ${basedir}/target/coverage-reports/jacoco-unit.exec file:src/test/resources/log4j.properties + + org.ops4j.pax.logging + @@ -128,15 +142,9 @@ ${jacoco.maven.plugin.version} - default-instrument + jacoco-initialize - instrument - - - - default-restore-instrumented-classes - - restore-instrumented-classes + prepare-agent @@ -150,50 +158,40 @@ ${basedir}/target/coverage-reports/site - - default-report-integration - - report-integration - - + + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + org.jacoco org.jacoco.agent ${jacoco.maven.plugin.version} runtime - - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.equinox - org.eclipse.equinox.common - org.testng testng - com.h2database.wso2 - h2-database-engine + org.wso2.orbit.com.h2database + h2 test org.wso2.carbon org.wso2.carbon.securevault - test org.powermock - powermock-api-mockito + powermock-api-mockito2 test @@ -202,19 +200,22 @@ test - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api + provided org.wso2.orbit.org.bouncycastle bcprov-jdk15on + provided org.wso2.orbit.org.bouncycastle bcpkix-jdk15on + provided - org.wso2.orbit.com.google.code.jscep + io.entgra.com.google.code.jscep jscep @@ -232,10 +233,12 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.device.mgt.core + provided io.entgra.device.mgt.core io.entgra.device.mgt.core.device.mgt.common + provided io.swagger @@ -255,6 +258,11 @@ slf4j-simple test + + org.wso2.orbit.javax.xml.bind + jaxb-api + provided + com.googlecode.json-simple.wso2 json-simple diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/cache/impl/CertificateCacheManagerImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/cache/impl/CertificateCacheManagerImpl.java index ac02de57a3..0a3129b977 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/cache/impl/CertificateCacheManagerImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/cache/impl/CertificateCacheManagerImpl.java @@ -19,8 +19,8 @@ package io.entgra.device.mgt.core.certificate.mgt.core.cache.impl; -import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.certificate.mgt.core.cache.CertificateCacheManager; +import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateManagementDAOFactory.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateManagementDAOFactory.java index 89f4d8145b..4a2fc9a47f 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateManagementDAOFactory.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateManagementDAOFactory.java @@ -18,6 +18,8 @@ package io.entgra.device.mgt.core.certificate.mgt.core.dao; +import io.entgra.device.mgt.core.certificate.mgt.core.config.datasource.DataSourceConfig; +import io.entgra.device.mgt.core.certificate.mgt.core.config.datasource.JNDILookupDefinition; import io.entgra.device.mgt.core.certificate.mgt.core.dao.impl.GenericCertificateDAOImpl; import io.entgra.device.mgt.core.certificate.mgt.core.dao.impl.OracleCertificateDAOImpl; import io.entgra.device.mgt.core.certificate.mgt.core.dao.impl.PostgreSQLCertificateDAOImpl; @@ -28,8 +30,6 @@ import io.entgra.device.mgt.core.certificate.mgt.core.exception.UnsupportedDatab import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagementConstants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.certificate.mgt.core.config.datasource.DataSourceConfig; -import io.entgra.device.mgt.core.certificate.mgt.core.config.datasource.JNDILookupDefinition; import javax.sql.DataSource; import java.sql.Connection; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java index 888b3619ca..9116acb94c 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java @@ -19,15 +19,15 @@ package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl; import io.entgra.device.mgt.core.certificate.mgt.core.bean.Certificate; -import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; -import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateDAO; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOException; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOUtil; +import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; +import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; import io.entgra.device.mgt.core.certificate.mgt.core.util.Serializer; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import java.io.IOException; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java index 26cb256e29..92891754ed 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java @@ -26,6 +26,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOException; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; +import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOUtil; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; import org.wso2.carbon.context.PrivilegedCarbonContext; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java index e60ee4a6c0..9fd87d6ed0 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java @@ -26,6 +26,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOException; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; +import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOUtil; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; import org.wso2.carbon.context.PrivilegedCarbonContext; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java index 48effed43b..ef06ec0000 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java @@ -26,6 +26,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOException; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; +import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOUtil; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; import org.wso2.carbon.context.PrivilegedCarbonContext; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java index 5cd02c63d0..22874dd7b7 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java @@ -26,6 +26,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOException; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; +import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOUtil; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; import org.wso2.carbon.context.PrivilegedCarbonContext; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGenerator.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGenerator.java index a692a45ab2..e8a29ebc29 100755 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGenerator.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGenerator.java @@ -17,8 +17,17 @@ */ package io.entgra.device.mgt.core.certificate.mgt.core.impl; +import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateDAO; +import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOException; +import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; +import io.entgra.device.mgt.core.certificate.mgt.core.dto.CAStatus; +import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; +import io.entgra.device.mgt.core.certificate.mgt.core.dto.SCEPResponse; +import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreException; +import io.entgra.device.mgt.core.certificate.mgt.core.exception.TransactionManagementException; import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagementConstants; import io.entgra.device.mgt.core.certificate.mgt.core.util.CommonUtil; +import io.entgra.device.mgt.core.certificate.mgt.core.util.Serializer; import org.apache.commons.codec.binary.Base64; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -46,26 +55,10 @@ import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.bouncycastle.util.Store; -import org.jscep.message.CertRep; -import org.jscep.message.MessageDecodingException; -import org.jscep.message.MessageEncodingException; -import org.jscep.message.PkcsPkiEnvelopeDecoder; -import org.jscep.message.PkcsPkiEnvelopeEncoder; -import org.jscep.message.PkiMessage; -import org.jscep.message.PkiMessageDecoder; -import org.jscep.message.PkiMessageEncoder; +import org.jscep.message.*; import org.jscep.transaction.FailInfo; import org.jscep.transaction.Nonce; import org.jscep.transaction.TransactionId; -import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateDAO; -import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOException; -import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; -import io.entgra.device.mgt.core.certificate.mgt.core.dto.CAStatus; -import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; -import io.entgra.device.mgt.core.certificate.mgt.core.dto.SCEPResponse; -import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreException; -import io.entgra.device.mgt.core.certificate.mgt.core.exception.TransactionManagementException; -import io.entgra.device.mgt.core.certificate.mgt.core.util.Serializer; import org.wso2.carbon.context.PrivilegedCarbonContext; import javax.naming.InvalidNameException; @@ -77,24 +70,9 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.KeyFactory; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.Security; -import java.security.SignatureException; +import java.security.*; import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateFactory; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.X509Certificate; +import java.security.cert.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import java.util.*; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/KeyStoreReader.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/KeyStoreReader.java index 2103cc6021..94cab378bf 100755 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/KeyStoreReader.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/KeyStoreReader.java @@ -17,8 +17,6 @@ */ package io.entgra.device.mgt.core.certificate.mgt.core.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.core.cache.CertificateCacheManager; import io.entgra.device.mgt.core.certificate.mgt.core.cache.impl.CertificateCacheManagerImpl; import io.entgra.device.mgt.core.certificate.mgt.core.config.CertificateConfigurationManager; @@ -30,12 +28,10 @@ import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.certificate.mgt.core.exception.CertificateManagementException; import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreException; import io.entgra.device.mgt.core.certificate.mgt.core.util.Serializer; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import java.security.*; import java.security.cert.Certificate; import java.security.cert.CertificateException; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/internal/CertificateManagementServiceComponent.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/internal/CertificateManagementServiceComponent.java index 956bb4683c..e51febfe88 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/internal/CertificateManagementServiceComponent.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/internal/CertificateManagementServiceComponent.java @@ -18,37 +18,33 @@ package io.entgra.device.mgt.core.certificate.mgt.core.internal; +import io.entgra.device.mgt.core.certificate.mgt.core.config.CertificateConfigurationManager; +import io.entgra.device.mgt.core.certificate.mgt.core.config.CertificateManagementConfig; +import io.entgra.device.mgt.core.certificate.mgt.core.config.datasource.DataSourceConfig; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; import io.entgra.device.mgt.core.certificate.mgt.core.exception.CertificateManagementException; import io.entgra.device.mgt.core.certificate.mgt.core.scep.SCEPManager; import io.entgra.device.mgt.core.certificate.mgt.core.scep.SCEPManagerImpl; +import io.entgra.device.mgt.core.certificate.mgt.core.service.CertificateManagementService; +import io.entgra.device.mgt.core.certificate.mgt.core.service.CertificateManagementServiceImpl; import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagementConstants; import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateMgtSchemaInitializer; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; -import io.entgra.device.mgt.core.certificate.mgt.core.config.CertificateConfigurationManager; -import io.entgra.device.mgt.core.certificate.mgt.core.config.CertificateManagementConfig; -import io.entgra.device.mgt.core.certificate.mgt.core.config.datasource.DataSourceConfig; -import io.entgra.device.mgt.core.certificate.mgt.core.service.CertificateManagementService; -import io.entgra.device.mgt.core.certificate.mgt.core.service.CertificateManagementServiceImpl; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import org.osgi.service.component.annotations.*; -/** - * @scr.component name="org.wso2.carbon.certificate.mgt" immediate="true" - * @scr.reference name="org.wso2.carbon.device.manager" - * interface="io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDeviceManagementService" - * unbind="unsetDeviceManagementService" - */ +@Component( + name = "io.entgra.device.mgt.core.certificate.mgt.core.internal.CertificateManagementServiceComponent", + immediate = true) public class CertificateManagementServiceComponent { private static Log log = LogFactory.getLog(CertificateManagementServiceComponent.class); @SuppressWarnings("unused") + @Activate protected void activate(ComponentContext componentContext) { try { if (log.isDebugEnabled()) { @@ -86,10 +82,17 @@ public class CertificateManagementServiceComponent { } @SuppressWarnings("unused") + @Deactivate protected void deactivate(ComponentContext componentContext) { //do nothing } + @Reference( + name = "device.mgt.provider.service", + service = io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDeviceManagementService") protected void setDeviceManagementService(DeviceManagementProviderService deviceManagerService) { if (log.isDebugEnabled()) { log.debug("Setting Device Management Service"); diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/scep/SCEPManagerImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/scep/SCEPManagerImpl.java index 4d18a19afb..783a234ff7 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/scep/SCEPManagerImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/scep/SCEPManagerImpl.java @@ -18,15 +18,15 @@ package io.entgra.device.mgt.core.certificate.mgt.core.scep; -import org.apache.commons.collections.map.SingletonMap; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.core.internal.CertificateManagementDataHolder; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import org.apache.commons.collections.map.SingletonMap; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateMgtSchemaInitializer.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateMgtSchemaInitializer.java index 9253ac9500..d0e080cc52 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateMgtSchemaInitializer.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateMgtSchemaInitializer.java @@ -18,9 +18,9 @@ package io.entgra.device.mgt.core.certificate.mgt.core.util; +import io.entgra.device.mgt.core.certificate.mgt.core.config.datasource.DataSourceConfig; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.certificate.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.dbcreator.DatabaseCreator; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/Serializer.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/Serializer.java index e5505449fd..4e5bee0518 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/Serializer.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/Serializer.java @@ -18,11 +18,7 @@ package io.entgra.device.mgt.core.certificate.mgt.core.util; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; +import java.io.*; /** * Serialize/deserialize a given object to and from a byte array. diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/common/BaseDeviceManagementCertificateTest.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/common/BaseDeviceManagementCertificateTest.java index 74118cb1ba..7ef81c794d 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/common/BaseDeviceManagementCertificateTest.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/common/BaseDeviceManagementCertificateTest.java @@ -19,6 +19,10 @@ package io.entgra.device.mgt.core.certificate.mgt.core.common; import io.entgra.device.mgt.core.certificate.mgt.core.util.TestUtils; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; +import io.entgra.device.mgt.core.device.mgt.core.dao.GroupManagementDAOFactory; +import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tomcat.jdbc.pool.PoolProperties; @@ -27,10 +31,6 @@ import org.testng.annotations.BeforeSuite; import org.w3c.dom.Document; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; -import io.entgra.device.mgt.core.device.mgt.core.dao.GroupManagementDAOFactory; -import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; import javax.sql.DataSource; import javax.xml.bind.JAXBContext; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateCacheManagerImplTests.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateCacheManagerImplTests.java index 04f5c73713..911c84d763 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateCacheManagerImplTests.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateCacheManagerImplTests.java @@ -18,11 +18,11 @@ package io.entgra.device.mgt.core.certificate.mgt.core.impl; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; import io.entgra.device.mgt.core.certificate.mgt.core.cache.CertificateCacheManager; import io.entgra.device.mgt.core.certificate.mgt.core.common.BaseDeviceManagementCertificateTest; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; /** * This class tests CertificateCache manager methods diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGeneratorNegativeTests.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGeneratorNegativeTests.java index e83917000b..fe87657544 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGeneratorNegativeTests.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGeneratorNegativeTests.java @@ -17,7 +17,11 @@ */ package io.entgra.device.mgt.core.certificate.mgt.core.impl; + +import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; +import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreException; import io.entgra.device.mgt.core.certificate.mgt.core.util.CSRGenerator; +import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagementConstants; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.cert.CertIOException; @@ -36,18 +40,11 @@ import org.powermock.modules.testng.PowerMockTestCase; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.base.MultitenantConstants; -import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; -import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreException; -import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagementConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; + import javax.sql.DataSource; import java.io.File; -import java.security.KeyPair; -import java.security.PrivateKey; -import java.security.NoSuchProviderException; -import java.security.NoSuchAlgorithmException; -import java.security.SignatureException; -import java.security.InvalidKeyException; +import java.security.*; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.sql.SQLException; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGeneratorTestSuite.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGeneratorTestSuite.java index b0a752714f..ddad9213b9 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGeneratorTestSuite.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGeneratorTestSuite.java @@ -18,13 +18,13 @@ package io.entgra.device.mgt.core.certificate.mgt.core.impl; +import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreException; +import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagementConstants; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.Assert; import org.testng.annotations.Test; -import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreException; -import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagementConstants; import java.io.File; import java.io.IOException; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGeneratorTests.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGeneratorTests.java index e192a41864..20a625eee1 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGeneratorTests.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGeneratorTests.java @@ -17,11 +17,11 @@ */ package io.entgra.device.mgt.core.certificate.mgt.core.impl; +import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreException; import junit.framework.Assert; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.annotations.Test; -import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreException; public class CertificateGeneratorTests { diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java index a57bfbb4d0..a3cca775a9 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java @@ -18,8 +18,20 @@ package io.entgra.device.mgt.core.certificate.mgt.core.impl; +import io.entgra.device.mgt.core.certificate.mgt.core.common.BaseDeviceManagementCertificateTest; +import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; +import io.entgra.device.mgt.core.certificate.mgt.core.dto.CAStatus; +import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; +import io.entgra.device.mgt.core.certificate.mgt.core.dto.SCEPResponse; +import io.entgra.device.mgt.core.certificate.mgt.core.exception.CertificateManagementException; +import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreException; +import io.entgra.device.mgt.core.certificate.mgt.core.service.CertificateManagementServiceImpl; +import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; import io.entgra.device.mgt.core.certificate.mgt.core.util.CSRGenerator; +import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagementConstants; import io.entgra.device.mgt.core.certificate.mgt.core.util.DummyCertificate; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; @@ -33,20 +45,8 @@ import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import io.entgra.device.mgt.core.certificate.mgt.core.common.BaseDeviceManagementCertificateTest; -import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; -import io.entgra.device.mgt.core.certificate.mgt.core.dto.CAStatus; -import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; -import io.entgra.device.mgt.core.certificate.mgt.core.dto.SCEPResponse; -import io.entgra.device.mgt.core.certificate.mgt.core.exception.CertificateManagementException; -import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreException; -import io.entgra.device.mgt.core.certificate.mgt.core.service.CertificateManagementServiceImpl; -import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; -import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagementConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; -import sun.misc.BASE64Encoder; + import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; @@ -55,6 +55,7 @@ import java.security.PrivateKey; import java.security.Security; import java.security.cert.*; import java.util.ArrayList; +import java.util.Base64; import java.util.List; /** @@ -181,7 +182,6 @@ public class CertificateManagementServiceImplTests extends BaseDeviceManagementC @Test(description = "This test case tests Signature verification of a Certificate against the keystore") public void testVerifySignature() throws KeystoreException, CertificateEncodingException, CMSException, IOException { - BASE64Encoder encoder = new BASE64Encoder(); //generate and save a certificate in the keystore X509Certificate x509Certificate = managementService.generateX509Certificate(); //Generate CMSdata @@ -192,7 +192,7 @@ public class CertificateManagementServiceImplTests extends BaseDeviceManagementC generator.addCertificates(store); CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent()); byte[] signature = degenerateSd.getEncoded(); - boolean verifySignature = managementService.verifySignature(encoder.encode(signature)); + boolean verifySignature = managementService.verifySignature(Base64.getEncoder().encodeToString(signature)); Assert.assertNotNull(verifySignature); Assert.assertTrue(verifySignature); log.info("VerifySignature Test Successful"); @@ -264,11 +264,11 @@ public class CertificateManagementServiceImplTests extends BaseDeviceManagementC @Test(description = "This test case tests generation of signed Certificate from a CSR") public void testGetSignedCertificateFromCSR() throws KeystoreException { CSRGenerator csrGeneration = new CSRGenerator(); - BASE64Encoder encoder = new BASE64Encoder(); // Generate key pair KeyPair keyPair = csrGeneration.generateKeyPair("RSA", 1024); byte[] csrData = csrGeneration.generateCSR("SHA256WithRSA", keyPair); - X509Certificate signedCertificateFromCSR = managementService.getSignedCertificateFromCSR(encoder.encode(csrData)); + X509Certificate signedCertificateFromCSR = managementService.getSignedCertificateFromCSR( + Base64.getEncoder().encodeToString(csrData)); Assert.assertNotNull(signedCertificateFromCSR); Assert.assertEquals(signedCertificateFromCSR.getType(), CertificateManagementConstants.X_509); log.info("GetSignedCertificateFromCSR Test Successful"); @@ -305,9 +305,8 @@ public class CertificateManagementServiceImplTests extends BaseDeviceManagementC @Test(description = "This test case tests converting a pem file to X509 Certificate") public void testPemToX509Certificate() throws IOException, KeystoreException { File caCert = new File(CA_CERT_PEM); - BASE64Encoder encoder = new BASE64Encoder(); byte[] caBytes = FileUtils.readFileToByteArray(caCert); - X509Certificate certificate = managementService.pemToX509Certificate(encoder.encode(caBytes)); + X509Certificate certificate = managementService.pemToX509Certificate(Base64.getEncoder().encodeToString(caBytes)); Assert.assertNotNull(certificate); Assert.assertEquals(certificate.getType(), CertificateManagementConstants.X_509); log.info("PemToX509Certificate Test Successful"); @@ -315,7 +314,6 @@ public class CertificateManagementServiceImplTests extends BaseDeviceManagementC @Test(description = "This test case tests extracting Certificate from the header Signature") public void testExtractCertificateFromSignature() throws KeystoreException, CertificateEncodingException, CMSException, IOException, DeviceManagementException { - BASE64Encoder encoder = new BASE64Encoder(); DeviceConfigurationManager.getInstance().initConfig(); //generate and save a certificate in the keystore X509Certificate x509Certificate = managementService.generateX509Certificate(); @@ -327,7 +325,7 @@ public class CertificateManagementServiceImplTests extends BaseDeviceManagementC generator.addCertificates(store); CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent()); byte[] signature = degenerateSd.getEncoded(); - X509Certificate certificate = managementService.extractCertificateFromSignature(encoder.encode(signature)); + X509Certificate certificate = managementService.extractCertificateFromSignature(Base64.getEncoder().encodeToString(signature)); Assert.assertNotNull(certificate); Assert.assertEquals(certificate.getType(), CertificateManagementConstants.X_509); log.info("ExtractCertificateFromSignature Test Successful"); diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateTests.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateTests.java index 9ece83b78a..e3ef5d8337 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateTests.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateTests.java @@ -18,10 +18,10 @@ package io.entgra.device.mgt.core.certificate.mgt.core.impl; +import io.entgra.device.mgt.core.certificate.mgt.core.bean.Certificate; import io.entgra.device.mgt.core.certificate.mgt.core.util.DummyCertificate; import org.testng.Assert; import org.testng.annotations.Test; -import io.entgra.device.mgt.core.certificate.mgt.core.bean.Certificate; /** * This class tests the DTO for certificates diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/util/DummyCertificate.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/util/DummyCertificate.java index ba4491643a..0a22e7b52b 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/util/DummyCertificate.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/util/DummyCertificate.java @@ -21,17 +21,8 @@ package io.entgra.device.mgt.core.certificate.mgt.core.util; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import java.math.BigInteger; -import java.security.Principal; -import java.security.PublicKey; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.CertificateException; -import java.security.NoSuchAlgorithmException; -import java.security.SignatureException; -import java.security.NoSuchProviderException; -import java.security.cert.X509Certificate; -import java.security.InvalidKeyException; +import java.security.*; +import java.security.cert.*; import java.util.Date; import java.util.Set; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/datasources/master-datasources.xml b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/datasources/master-datasources.xml index a901e7a707..010c7a2cc8 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/datasources/master-datasources.xml +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/datasources/master-datasources.xml @@ -15,7 +15,7 @@ ~ specific language governing permissions and limitations ~ under the License. --> - + org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/data-source-config.xml b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/data-source-config.xml index 27b6dfeaeb..533fd82959 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/data-source-config.xml +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/data-source-config.xml @@ -18,7 +18,7 @@ --> - jdbc:h2:mem:cdm-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true + jdbc:h2:mem:cdm-test-db;DB_CLOSE_ON_EXIT=FALSE org.h2.Driver wso2carbon wso2carbon diff --git a/components/certificate-mgt/pom.xml b/components/certificate-mgt/pom.xml index 6716687cc1..c733f7e373 100644 --- a/components/certificate-mgt/pom.xml +++ b/components/certificate-mgt/pom.xml @@ -30,7 +30,7 @@ certificate-mgt pom WSO2 Carbon - Certificate Management Component - http://wso2.org + https://entgra.io io.entgra.device.mgt.core.certificate.mgt.core @@ -38,23 +38,4 @@ io.entgra.device.mgt.core.certificate.mgt.cert.admin.api - - - - - org.apache.felix - maven-scr-plugin - 1.7.2 - - - generate-scr-scrdescriptor - - scr - - - - - - - diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/pom.xml index 0c52cb5756..888af70f81 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/pom.xml @@ -36,21 +36,16 @@ - org.apache.felix - maven-scr-plugin - - + org.apache.maven.plugins maven-compiler-plugin 1.8 1.8 - 2.3.2 org.apache.felix maven-bundle-plugin - 1.4.0 true @@ -60,22 +55,19 @@ IoT - User Roles Management Bundle io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.internal + io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.bean;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.exception;version="[5.0,6)", + javax.xml.bind;version="[0.0,1)", + javax.xml.bind.annotation;version="[0.0,1)", + javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}", + org.apache.commons.logging;version="[1.2,2)", org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.apache.commons.logging, - org.apache.axis2.*;version="${axis2.osgi.version.range}", - org.wso2.carbon.core, - org.wso2.carbon.utils.*, - javax.xml.bind;resolution:=optional, - javax.xml.bind.annotation, - javax.xml.parsers, - org.w3c.dom, - org.wso2.carbon, - org.wso2.carbon.context, - org.wso2.carbon.user.api, - org.wso2.carbon.user.core.common, - org.wso2.carbon.user.core.service, - org.wso2.carbon.user.mgt.common + org.w3c.dom,org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.core;version="[4.8,5)", + org.wso2.carbon.user.api;version="[1.0,2)", + org.wso2.carbon.user.core.service;version="[4.8,5)", + org.wso2.carbon.utils;version="[4.8,5)" !io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.internal, @@ -114,13 +106,19 @@ org.apache.maven.plugins maven-surefire-plugin + + --add-opens=java.xml/jdk.xml.internal=ALL-UNNAMED + --add-opens=java.base/jdk.internal.loader=ALL-UNNAMED + - file:src/test/resources/carbon-home/repository/conf/log4j.properties - + file:src/test/resources/log4j.properties src/test/resources/testng.xml + + org.ops4j.pax.logging + @@ -128,20 +126,18 @@ - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services + org.apache.felix + org.apache.felix.scr.ds-annotations + provided org.wso2.carbon org.wso2.carbon.core - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api + provided org.wso2.carbon @@ -191,7 +187,6 @@ org.wso2.carbon org.wso2.carbon.securevault - test @@ -215,8 +210,18 @@ test - javax.xml.bind + org.wso2.orbit.javax.xml.bind jaxb-api + provided + + + com.sun.xml.bind + jaxb-core + test + + + com.sun.xml.bind + jaxb-impl test diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/defaultrole/manager/internal/RoleManagerServiceComponent.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/defaultrole/manager/internal/RoleManagerServiceComponent.java index 095fca95e4..6b802591ce 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/defaultrole/manager/internal/RoleManagerServiceComponent.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/defaultrole/manager/internal/RoleManagerServiceComponent.java @@ -19,35 +19,24 @@ package io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.internal; import io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.DefaultRolesConfigManager; +import io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.IoTSStartupHandler; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.core.ServerStartupObserver; -import io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.IoTSStartupHandler; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.utils.ConfigurationContextService; -/** - * @scr.component name="io.entgra.device.mgt.role.manager.RoleManagerServiceComponent" - * immediate="true" - * @scr.reference name="user.realmservice.default" - * interface="org.wso2.carbon.user.core.service.RealmService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRealmService" - * unbind="unsetRealmService" - * @scr.reference name="config.context.service" - * interface="org.wso2.carbon.utils.ConfigurationContextService" - * cardinality="0..1" - * policy="dynamic" - * bind="setConfigurationContextService" - * unbind="unsetConfigurationContextService" - */ +@Component( + name = "io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.internal.RoleManagerServiceComponent", + immediate = true) public class RoleManagerServiceComponent { private static final Log log = LogFactory.getLog(RoleManagerServiceComponent.class); + @Activate protected void activate(ComponentContext ctx) { if (log.isDebugEnabled()) { log.debug("Activating Role Management Service Component"); @@ -63,13 +52,19 @@ public class RoleManagerServiceComponent { log.error("Error occurred while activating Role Management Service Component", e); } } - + @Deactivate protected void deactivate(ComponentContext ctx) { if (log.isDebugEnabled()) { log.debug("De-activating Role Manager Service Component"); } } + @Reference( + name = "configuration.context.service", + service = org.wso2.carbon.utils.ConfigurationContextService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetConfigurationContextService") protected void setConfigurationContextService(ConfigurationContextService configurationContextService) { if (log.isDebugEnabled()) { log.debug("Setting ConfigurationContextService"); @@ -90,6 +85,12 @@ public class RoleManagerServiceComponent { * * @param realmService An instance of RealmService */ + @Reference( + name = "realm.service", + service = org.wso2.carbon.user.core.service.RealmService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRealmService") protected void setRealmService(RealmService realmService) { if (log.isDebugEnabled()) { log.debug("Setting Realm Service"); diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/src/test/resources/carbon-home/dbscripts/h2.sql b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/src/test/resources/carbon-home/dbscripts/h2.sql index 2f96eeba79..7f20466a6f 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/src/test/resources/carbon-home/dbscripts/h2.sql +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/src/test/resources/carbon-home/dbscripts/h2.sql @@ -16,24 +16,6 @@ * under the License. */ -/* - * Copyright (c) 2021, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you 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. - */ - CREATE TABLE IF NOT EXISTS REG_CLUSTER_LOCK ( REG_LOCK_NAME VARCHAR (20), REG_LOCK_STATUS VARCHAR (20), @@ -104,7 +86,6 @@ CREATE INDEX IF NOT EXISTS REG_RESOURCE_IND_BY_PATH_ID_NAME ON REG_RESOURCE(REG_ CREATE INDEX IF NOT EXISTS REG_RESOURCE_IND_BY_UUID ON REG_RESOURCE(REG_UUID); CREATE INDEX IF NOT EXISTS REG_RESOURCE_IND_BY_TENANT ON REG_RESOURCE(REG_TENANT_ID, REG_UUID); CREATE INDEX IF NOT EXISTS REG_RESOURCE_IND_BY_TYPE ON REG_RESOURCE(REG_TENANT_ID, REG_MEDIA_TYPE); - CREATE TABLE IF NOT EXISTS REG_RESOURCE_HISTORY ( REG_PATH_ID INTEGER NOT NULL, REG_NAME VARCHAR(256), diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/src/test/resources/carbon-home/repository/conf/datasources/data-source-config.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/src/test/resources/carbon-home/repository/conf/datasources/data-source-config.xml index ad8165fc67..2e591b07c9 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/src/test/resources/carbon-home/repository/conf/datasources/data-source-config.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/src/test/resources/carbon-home/repository/conf/datasources/data-source-config.xml @@ -18,7 +18,7 @@ --> - jdbc:h2:mem:smart-meter-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true + jdbc:h2:mem:smart-meter-test-db;DB_CLOSE_ON_EXIT=FALSE org.h2.Driver wso2carbon wso2carbon diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api/pom.xml index be028cf924..3cc512d792 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api/pom.xml @@ -144,9 +144,8 @@ provided - org.apache.cxf + org.apache.cxf.wso2 cxf-bundle - 3.0.0-milestone2 test @@ -180,8 +179,8 @@ - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api provided @@ -234,6 +233,10 @@ org.wso2.orbit.com.fasterxml.jackson.core jackson-core + + com.fasterxml.jackson.core + jackson-databind + @@ -267,6 +270,7 @@ org.wso2.orbit.com.fasterxml.jackson.core jackson-annotations + provided org.hibernate @@ -315,7 +319,7 @@ org.powermock - powermock-api-mockito + powermock-api-mockito2 test diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/pom.xml index b5101280a2..61480722b1 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/pom.xml @@ -95,6 +95,11 @@ + + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + org.wso2.carbon org.wso2.carbon.ndatasource.core @@ -125,16 +130,16 @@ - - org.eclipse.osgi - org.eclipse.osgi - provided - - - org.eclipse.osgi - org.eclipse.osgi.services - provided - + + + + + + + + + + @@ -166,7 +171,7 @@ provided - org.apache.tomcat.wso2 + org.wso2.orbit.org.apache.tomcat jdbc-pool provided @@ -238,7 +243,6 @@ com.google.guava guava - ${guava.version} provided @@ -260,7 +264,7 @@ org.powermock - powermock-api-mockito + powermock-api-mockito2 test @@ -304,7 +308,7 @@ test - javax.xml.bind + org.wso2.orbit.javax.xml.bind jaxb-api test @@ -315,10 +319,10 @@ org.apache.maven.plugins maven-compiler-plugin - - - org.apache.felix - maven-scr-plugin + + 1.8 + 1.8 + org.apache.felix @@ -366,7 +370,7 @@ com.fasterxml.jackson.core.*, com.fasterxml.jackson.databind.*, com.fasterxml.jackson.annotation.*, - com.google.common.cache.*, + com.google.common.cache.* diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/internal/DeviceOrganizationMgtServiceComponent.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/internal/DeviceOrganizationMgtServiceComponent.java index f33cbdcd01..b6fd06d8ff 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/internal/DeviceOrganizationMgtServiceComponent.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/internal/DeviceOrganizationMgtServiceComponent.java @@ -31,28 +31,11 @@ import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.registry.core.service.RegistryService; +import org.osgi.service.component.annotations.*; -/** - * @scr.component name="io.entgra.device.mgt.core.device.mgt.extensions.device.organization.internal.DeviceOrganizationMgtServiceComponent" immediate="true" - * @scr.reference name="org.wso2.carbon.device.manager" - * interface="io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDeviceManagementService" - * unbind="unsetDeviceManagementService" - * @scr.reference name="org.wso2.carbon.ndatasource" - * interface="org.wso2.carbon.ndatasource.core.DataSourceService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDataSourceService" - * unbind="unsetDataSourceService" - * @scr.reference name="registry.service" - * interface="org.wso2.carbon.registry.core.service.RegistryService" - * cardinality="0..1" - * policy="dynamic" - * bind="setRegistryService" - * unbind="unsetRegistryService" - */ +@Component( + name = "io.entgra.device.mgt.core.device.mgt.extensions.device.organization.internal.DeviceOrganizationMgtServiceComponent", + immediate = true) public class DeviceOrganizationMgtServiceComponent { private static final Log log = LogFactory.getLog(DeviceOrganizationMgtServiceComponent.class); @@ -60,6 +43,7 @@ public class DeviceOrganizationMgtServiceComponent { /** * @param componentContext */ + @Activate protected void activate(ComponentContext componentContext) { if (log.isDebugEnabled()) { @@ -87,6 +71,7 @@ public class DeviceOrganizationMgtServiceComponent { /** * @param componentContext */ + @Deactivate protected void deactivate(ComponentContext componentContext) { if (log.isDebugEnabled()) { log.debug("De-activating Device Organization Management Service Component"); @@ -94,6 +79,13 @@ public class DeviceOrganizationMgtServiceComponent { } @SuppressWarnings("unused") + @Reference( + name = "org.wso2.carbon.device.manager", + service = io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + bind = "setDeviceManagementService", + unbind = "unsetDeviceManagementService") protected void setDeviceManagementService(DeviceManagementProviderService deviceManagementProviderService) { if (log.isDebugEnabled()) { log.debug("Setting Device Management Service to Device Organization Mgt SC"); @@ -112,6 +104,14 @@ public class DeviceOrganizationMgtServiceComponent { /** * @param dataSourceService */ + + @Reference( + name = "org.wso2.carbon.ndatasource", + service = org.wso2.carbon.ndatasource.core.DataSourceService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + bind = "setDataSourceService", + unbind = "unsetDataSourceService") protected void setDataSourceService(DataSourceService dataSourceService) { if (log.isDebugEnabled()) { log.debug("Data source service set to Device Organization Mgt component"); @@ -128,7 +128,13 @@ public class DeviceOrganizationMgtServiceComponent { } } - + @Reference( + name = "registry.service", + service = org.wso2.carbon.registry.core.service.RegistryService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + bind = "setRegistryService", + unbind = "unsetRegistryService") protected void setRegistryService(RegistryService registryService) { if (log.isDebugEnabled()) { log.debug("RegistryService set to Device Organization Mgt component"); @@ -143,5 +149,4 @@ public class DeviceOrganizationMgtServiceComponent { DeviceOrganizationMgtDataHolder.getInstance().setRegistryService(null); } - } diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql index 29d1a225b2..c581442e42 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql @@ -65,7 +65,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE ID INTEGER auto_increment NOT NULL, DESCRIPTION TEXT DEFAULT NULL, NAME VARCHAR(100) DEFAULT NULL, - DEVICE_TYPE_ID INT(11) DEFAULT NULL, + DEVICE_TYPE_ID INT DEFAULT NULL, DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, TENANT_ID INTEGER DEFAULT 0, @@ -212,17 +212,17 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE CREATE TABLE IF NOT EXISTS DM_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT, + ID INT NOT NULL AUTO_INCREMENT, NAME VARCHAR(45) DEFAULT NULL, DESCRIPTION VARCHAR(1000) NULL, PAYLOAD_VERSION VARCHAR(45) NULL, - TENANT_ID INT(11) NOT NULL, - PROFILE_ID INT(11) NOT NULL, + TENANT_ID INT NOT NULL, + PROFILE_ID INT NOT NULL, OWNERSHIP_TYPE VARCHAR(45) NULL, COMPLIANCE VARCHAR(100) NULL, PRIORITY INT NOT NULL, - ACTIVE INT(2) NOT NULL, - UPDATED INT(1) NULL, + ACTIVE INT NOT NULL, + UPDATED INT NULL, POLICY_TYPE VARCHAR(45) NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_PROFILE_DM_POLICY @@ -234,11 +234,11 @@ CREATE TABLE IF NOT EXISTS DM_POLICY CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT, - DEVICE_ID INT(11) NOT NULL, - ENROLMENT_ID INT(11) NOT NULL, + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_ID INT NOT NULL, + ENROLMENT_ID INT NOT NULL, DEVICE BLOB NOT NULL, - POLICY_ID INT(11) NOT NULL, + POLICY_ID INT NOT NULL, PRIMARY KEY (ID), CONSTRAINT FK_POLICY_DEVICE_POLICY FOREIGN KEY (POLICY_ID) @@ -254,9 +254,9 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( - ID INT(11) NOT NULL, + ID INT NOT NULL, DEVICE_TYPE VARCHAR(300) NOT NULL, - POLICY_ID INT(11) NOT NULL, + POLICY_ID INT NOT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DEVICE_TYPE_POLICY FOREIGN KEY (POLICY_ID) @@ -267,11 +267,11 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( - ID INT(11) NOT NULL AUTO_INCREMENT, - PROFILE_ID INT(11) NOT NULL, + ID INT NOT NULL AUTO_INCREMENT, + PROFILE_ID INT NOT NULL, FEATURE_CODE VARCHAR(100) NOT NULL, DEVICE_TYPE VARCHAR(300) NOT NULL, - TENANT_ID INT(11) NOT NULL, + TENANT_ID INT NOT NULL, CONTENT BLOB NULL DEFAULT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES @@ -283,11 +283,11 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES CREATE TABLE IF NOT EXISTS DM_POLICY_CORRECTIVE_ACTION ( - ID INT(11) NOT NULL AUTO_INCREMENT, + ID INT NOT NULL AUTO_INCREMENT, ACTION_TYPE VARCHAR(45) NOT NULL, - CORRECTIVE_POLICY_ID INT(11) DEFAULT NULL, - POLICY_ID INT(11) NOT NULL, - FEATURE_ID INT(11) DEFAULT NULL, + CORRECTIVE_POLICY_ID INT DEFAULT NULL, + POLICY_ID INT NOT NULL, + FEATURE_ID INT DEFAULT NULL, IS_REACTIVE BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (ID), CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION @@ -299,9 +299,9 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CORRECTIVE_ACTION CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT, + ID INT NOT NULL AUTO_INCREMENT, ROLE_NAME VARCHAR(45) NOT NULL, - POLICY_ID INT(11) NOT NULL, + POLICY_ID INT NOT NULL, PRIMARY KEY (ID), CONSTRAINT FK_ROLE_POLICY_POLICY FOREIGN KEY (POLICY_ID) @@ -327,11 +327,11 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( ID INT NOT NULL AUTO_INCREMENT, DEVICE_ID INT NOT NULL, - ENROLMENT_ID INT(11) NOT NULL, + ENROLMENT_ID INT NOT NULL, POLICY_ID INT NOT NULL, POLICY_CONTENT TEXT NULL, TENANT_ID INT NOT NULL, - APPLIED TINYINT(1) NULL, + APPLIED TINYINT NULL, CREATED_TIME TIMESTAMP NULL, UPDATED_TIME TIMESTAMP NULL, APPLIED_TIME TIMESTAMP NULL, @@ -388,7 +388,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( ID INT NOT NULL AUTO_INCREMENT, DEVICE_ID INT NOT NULL, - ENROLMENT_ID INT(11) NOT NULL, + ENROLMENT_ID INT NOT NULL, POLICY_ID INT NOT NULL, TENANT_ID INT NOT NULL, STATUS INT NULL, @@ -404,7 +404,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ID INT NOT NULL AUTO_INCREMENT, POLICY_ID INT NOT NULL, DEVICE_TYPE VARCHAR(300) NOT NULL, - TENANT_ID INT(11) NOT NULL, + TENANT_ID INT NOT NULL, PRIMARY KEY (ID) ); @@ -435,7 +435,7 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION LOCATION_URL VARCHAR(100) DEFAULT NULL, IMAGE_URL VARCHAR(100) DEFAULT NULL, APP_PROPERTIES BLOB NULL, - MEMORY_USAGE INTEGER(10) NULL, + MEMORY_USAGE INTEGER NULL, IS_ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, DEVICE_ID INTEGER NOT NULL, ENROLMENT_ID INTEGER NOT NULL, @@ -507,7 +507,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION STATE VARCHAR(45) NULL, COUNTRY VARCHAR(45) NULL, GEO_HASH VARCHAR(45) NULL, - UPDATE_TIMESTAMP BIGINT(15) NOT NULL, + UPDATE_TIMESTAMP BIGINT NOT NULL, ALTITUDE DOUBLE NULL, SPEED FLOAT NULL, BEARING FLOAT NULL, @@ -545,8 +545,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL CPU_USAGE DECIMAL(5) NULL, TOTAL_RAM_MEMORY DECIMAL(30, 3) NULL, AVAILABLE_RAM_MEMORY DECIMAL(30, 3) NULL, - PLUGGED_IN INT(1) NULL, - UPDATE_TIMESTAMP BIGINT(15) NOT NULL, + PLUGGED_IN INT NULL, + UPDATE_TIMESTAMP BIGINT NOT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE FOREIGN KEY (DEVICE_ID) @@ -573,7 +573,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_HISTORY_LAST_SEVEN_DAYS LONGITUDE DOUBLE NULL, SPEED FLOAT NULL, HEADING FLOAT NULL, - TIMESTAMP BIGINT(15) NOT NULL, + TIMESTAMP BIGINT NOT NULL, GEO_HASH VARCHAR(45) NULL, DEVICE_OWNER VARCHAR(45) NULL, DEVICE_ALTITUDE DOUBLE NULL, @@ -879,8 +879,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_ORGANIZATION ( ORGANIZATION_ID INT NOT NULL AUTO_INCREMENT, TENANT_ID INT DEFAULT 0, - DEVICE_ID INT(11) NOT NULL, - PARENT_DEVICE_ID INT(11) DEFAULT NULL, + DEVICE_ID INT NOT NULL, + PARENT_DEVICE_ID INT DEFAULT NULL, DEVICE_ORGANIZATION_META TEXT DEFAULT NULL, LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, PRIMARY KEY (ORGANIZATION_ID), diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/carbon-home/dbscripts/h2.sql b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/carbon-home/dbscripts/h2.sql index d89dfd584b..e738decf52 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/carbon-home/dbscripts/h2.sql +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/carbon-home/dbscripts/h2.sql @@ -22,8 +22,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_ORGANIZATION ( ORGANIZATION_ID INT NOT NULL AUTO_INCREMENT, TENANT_ID INT DEFAULT 0, - DEVICE_ID INT(11) NOT NULL, - PARENT_DEVICE_ID INT(11) DEFAULT NULL, + DEVICE_ID INT NOT NULL, + PARENT_DEVICE_ID INT DEFAULT NULL, DEVICE_ORGANIZATION_META TEXT DEFAULT NULL, LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, PRIMARY KEY (ORGANIZATION_ID), diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/carbon-home/repository/conf/datasources/data-source-config.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/carbon-home/repository/conf/datasources/data-source-config.xml index a9c81a4710..a237b9af1d 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/carbon-home/repository/conf/datasources/data-source-config.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/carbon-home/repository/conf/datasources/data-source-config.xml @@ -17,7 +17,7 @@ --> - jdbc:h2:mem:smart-meter-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true + jdbc:h2:mem:smart-meter-test-db;DB_CLOSE_ON_EXIT=FALSE org.h2.Driver wso2carbon wso2carbon diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/config/datasource/data-source-config-mock.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/config/datasource/data-source-config-mock.xml index 383fc72b75..04445b6397 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/config/datasource/data-source-config-mock.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/config/datasource/data-source-config-mock.xml @@ -18,7 +18,7 @@ --> - jdbc:h2:mem:cdm-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true + jdbc:h2:mem:cdm-test-db;DB_CLOSE_ON_EXIT=FALSE io.entgra.device.mgt.core.device.mgt.extensions.device.organization.mock.MockJDBCDriver wso2carbon wso2carbon diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/config/datasource/data-source-config-no-table.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/config/datasource/data-source-config-no-table.xml index b28626efe7..71e35416f3 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/config/datasource/data-source-config-no-table.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/config/datasource/data-source-config-no-table.xml @@ -18,7 +18,7 @@ --> - jdbc:h2:mem:nodb-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true + jdbc:h2:mem:nodb-test-db;DB_CLOSE_ON_EXIT=FALSE org.h2.Driver wso2carbon wso2carbon diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/config/datasource/data-source-config.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/config/datasource/data-source-config.xml index 27b6dfeaeb..533fd82959 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/config/datasource/data-source-config.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/config/datasource/data-source-config.xml @@ -18,7 +18,7 @@ --> - jdbc:h2:mem:cdm-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true + jdbc:h2:mem:cdm-test-db;DB_CLOSE_ON_EXIT=FALSE org.h2.Driver wso2carbon wso2carbon diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/pom.xml index 888c00a4d4..2a04b62e41 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/pom.xml @@ -31,9 +31,14 @@ bundle WSO2 Carbon - Device Type Deployer WSO2 Carbon - Device Type Deployer Implementation - http://wso2.org + https://entgra.io + + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + commons-lang.wso2 commons-lang @@ -46,14 +51,6 @@ org.wso2.carbon org.wso2.carbon.utils - - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services - commons-logging commons-logging @@ -107,13 +104,37 @@ io.entgra.device.mgt.core.device.mgt.core test + + org.mockito + mockito-core + test + + + com.sun.xml.bind + jaxb-core + test + + + com.sun.xml.bind + jaxb-impl + test + + + org.wso2.orbit.javax.xml.bind + jaxb-api + provided + - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -130,37 +151,51 @@ io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.* - javax.naming, - javax.sql, - javax.xml, - javax.xml.bind, - javax.xml.bind.annotation, - javax.xml.parsers; version="${javax.xml.parsers.import.pkg.version}", - org.apache.axis2.context, - org.apache.axis2.deployment.*, - org.apache.commons.lang;version="${commons-lang.wso2.osgi.version.range}", - org.apache.commons.logging, + io.entgra.device.mgt.core.device.mgt.common.spi;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.util, + io.entgra.device.mgt.core.device.mgt.extensions.device.type.template;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.exception;version="[5.0,6)", + javax.xml.bind;version="[0.0,1)", + javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}", + org.apache.axis2.context;version="[1.6,2)", + org.apache.axis2.deployment;version="[1.6,2)", + org.apache.axis2.deployment.repository.util;version="[1.6,2)", + org.apache.axis2.engine;version="[1.6,2)", + org.apache.commons.logging;version="[1.2,2)", org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.w3c.dom, - org.wso2.carbon.context, - io.entgra.device.mgt.core.device.mgt.common.*, - io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.*, - org.wso2.carbon.registry.api, - org.wso2.carbon.registry.core, - org.wso2.carbon.registry.core.*, - org.wso2.carbon.utils.*, - javax.xml.namespace, - org.apache.commons.io, - org.wso2.carbon.application.deployer.*, - org.apache.axis2.engine, - org.wso2.carbon.ndatasource.core, + org.w3c.dom,org.wso2.carbon.application.deployer;version="[4.8,5)", + org.wso2.carbon.application.deployer.config;version="[4.8,5)", + org.wso2.carbon.application.deployer.handler;version="[4.8,5)", + org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.ndatasource.core;version="[4.8,5)", + org.wso2.carbon.registry.core.service;version="[1.0,2)", + org.wso2.carbon.utils;version="[4.8,5)" DeviceTypeDeployer - + + org.apache.maven.plugins + maven-surefire-plugin + + + --add-opens=java.xml/jdk.xml.internal=ALL-UNNAMED + --add-opens=java.base/jdk.internal.loader=ALL-UNNAMED + + + file:src/test/resources/log4j.properties + + + src/test/resources/testng.xml + + + org.ops4j.pax.logging + + + org.jacoco jacoco-maven-plugin diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/DeviceTypeCAppDeployer.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/DeviceTypeCAppDeployer.java index b4dd226289..ee2c7a7367 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/DeviceTypeCAppDeployer.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/DeviceTypeCAppDeployer.java @@ -17,6 +17,7 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer; +import io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.util.DeviceTypePluginConstants; import org.apache.axis2.deployment.Deployer; import org.apache.axis2.deployment.DeploymentException; import org.apache.axis2.deployment.repository.util.DeploymentFileData; @@ -29,7 +30,6 @@ import org.wso2.carbon.application.deployer.CarbonApplication; import org.wso2.carbon.application.deployer.config.Artifact; import org.wso2.carbon.application.deployer.config.CappFile; import org.wso2.carbon.application.deployer.handler.AppDeploymentHandler; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.util.DeviceTypePluginConstants; import java.io.File; import java.util.ArrayList; diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/DeviceTypePluginDeployer.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/DeviceTypePluginDeployer.java index 51da5d8687..fe5a4488e1 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/DeviceTypePluginDeployer.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/DeviceTypePluginDeployer.java @@ -17,6 +17,13 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer; +import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService; +import io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.internal.DeviceTypeManagementDataHolder; +import io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.util.DeviceTypeConfigUtil; +import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.DeviceTypeConfigIdentifier; +import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.DeviceTypeManagerService; +import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration; +import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.exception.DeviceTypeConfigurationException; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.deployment.AbstractDeployer; import org.apache.axis2.deployment.DeploymentException; @@ -27,13 +34,6 @@ import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import org.w3c.dom.Document; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.internal.DeviceTypeManagementDataHolder; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.util.DeviceTypeConfigUtil; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.DeviceTypeConfigIdentifier; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.DeviceTypeManagerService; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.exception.DeviceTypeConfigurationException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/internal/DeviceTypeManagementServiceComponent.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/internal/DeviceTypeManagementServiceComponent.java index e1a8e560c1..6d5b0a7002 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/internal/DeviceTypeManagementServiceComponent.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/internal/DeviceTypeManagementServiceComponent.java @@ -21,34 +21,19 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.int import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; -import org.wso2.carbon.application.deployer.handler.AppDeploymentHandler; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.utils.ConfigurationContextService; -/** - * @scr.component name="io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.internal.DeviceTypeManagementServiceComponent" - * immediate="true" - * @scr.reference name="config.context.service" - * interface="org.wso2.carbon.utils.ConfigurationContextService" - * cardinality="0..1" - * policy="dynamic" - * bind="setConfigurationContextService" - * unbind="unsetConfigurationContextService" - * @scr.reference name="registry.service" - * interface="org.wso2.carbon.registry.core.service.RegistryService" cardinality="0..1" - * policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService" - * @scr.reference name="org.wso2.carbon.ndatasource" - * interface="org.wso2.carbon.ndatasource.core.DataSourceService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDataSourceService" - * unbind="unsetDataSourceService" - */ +@Component( + name = "io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.internal.DeviceTypeManagementServiceComponent", + immediate = true) public class DeviceTypeManagementServiceComponent { private static final Log log = LogFactory.getLog(DeviceTypeManagementServiceComponent.class); + @Activate protected void activate(ComponentContext ctx) { if (log.isDebugEnabled()) { log.debug("Activating DeviceType Deployer Service Component"); @@ -56,13 +41,19 @@ public class DeviceTypeManagementServiceComponent { // ctx.getBundleContext().registerService(AppDeploymentHandler.class.getName(), new DeviceTypeCAppDeployer(), null); DeviceTypeManagementDataHolder.getInstance().setBundleContext(ctx.getBundleContext()); } - + @Deactivate protected void deactivate(ComponentContext ctx) { if (log.isDebugEnabled()) { log.debug("De-activating DeviceType Deployer Service Component"); } } + @Reference( + name = "configuration.context.service", + service = org.wso2.carbon.utils.ConfigurationContextService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetConfigurationContextService") protected void setConfigurationContextService(ConfigurationContextService configurationContextService) { if (log.isDebugEnabled()) { log.debug("Setting ConfigurationContextService"); @@ -79,6 +70,12 @@ public class DeviceTypeManagementServiceComponent { DeviceTypeManagementDataHolder.getInstance().setConfigurationContextService(null); } + @Reference( + name = "registry.service", + service = org.wso2.carbon.registry.core.service.RegistryService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRegistryService") protected void setRegistryService(RegistryService registryService) { if (log.isDebugEnabled()) { log.debug("RegistryService acquired"); @@ -90,6 +87,12 @@ public class DeviceTypeManagementServiceComponent { DeviceTypeManagementDataHolder.getInstance().setRegistryService(null); } + @Reference( + name = "datasource.service", + service = org.wso2.carbon.ndatasource.core.DataSourceService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDataSourceService") protected void setDataSourceService(DataSourceService dataSourceService) { /* This is to avoid mobile device management component getting initialized before the underlying datasources are registered */ diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/util/DeviceTypeConfigUtil.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/util/DeviceTypeConfigUtil.java index 4a80afc085..e54ba0265e 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/util/DeviceTypeConfigUtil.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/util/DeviceTypeConfigUtil.java @@ -17,8 +17,8 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.util; -import org.w3c.dom.Document; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.exception.DeviceTypeConfigurationException; +import org.w3c.dom.Document; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/DeviceTypeCAppDeployerTest.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/DeviceTypeCAppDeployerTest.java index ecdc8de691..f188c7af06 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/DeviceTypeCAppDeployerTest.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/DeviceTypeCAppDeployerTest.java @@ -18,7 +18,7 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.DeviceTypeCAppDeployer; +import io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.util.DeviceTypePluginConstants; import org.apache.axis2.deployment.DeploymentException; import org.apache.axis2.engine.AxisConfiguration; import org.mockito.Mockito; @@ -29,8 +29,8 @@ import org.wso2.carbon.application.deployer.config.ApplicationConfiguration; import org.wso2.carbon.application.deployer.config.Artifact; import org.wso2.carbon.application.deployer.config.CappFile; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.util.DeviceTypePluginConstants; import org.wso2.carbon.registry.core.exceptions.RegistryException; + import java.io.File; import java.io.IOException; import java.lang.reflect.Field; diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/DeviceTypePluginDeployerTest.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/DeviceTypePluginDeployerTest.java index f452e55b58..2766977aeb 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/DeviceTypePluginDeployerTest.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/deployer/DeviceTypePluginDeployerTest.java @@ -18,7 +18,7 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.DeviceTypePluginDeployer; +import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.DeviceTypeConfigIdentifier; import org.apache.axis2.deployment.DeploymentException; import org.apache.axis2.deployment.repository.util.DeploymentFileData; import org.junit.Assert; @@ -27,8 +27,8 @@ import org.osgi.framework.ServiceRegistration; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.DeviceTypeConfigIdentifier; import org.wso2.carbon.registry.core.exceptions.RegistryException; + import java.io.File; import java.io.IOException; import java.lang.reflect.Field; diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger/pom.xml index 700cca153c..aa4b2c1cf1 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger/pom.xml @@ -37,6 +37,10 @@ org.apache.maven.plugins maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -50,7 +54,7 @@ Entgra Logger Bundle io.entgra.device.mgt.core.device.mgt.extensions.logger, - org.apache.commons.logging + org.apache.commons.logging;version="[1.2,2)" io.entgra.device.mgt.core.device.mgt.extensions.logger.* @@ -63,8 +67,8 @@ - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api provided diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/pom.xml index 338198eab8..d1ea2bc255 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/pom.xml @@ -31,9 +31,14 @@ bundle WSO2 Carbon - Pull Notification Provider Implementation WSO2 Carbon - Pull Notification Provider Implementation - http://wso2.org + https://entgra.io + + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + io.entgra.device.mgt.core io.entgra.device.mgt.core.device.mgt.common @@ -42,14 +47,6 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.device.mgt.core - - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services - io.entgra.device.mgt.core io.entgra.device.mgt.core.policy.mgt.core @@ -64,8 +61,12 @@ - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -82,17 +83,17 @@ io.entgra.device.mgt.core.device.mgt.extensions.pull.notification.* - org.osgi.framework.*;version="${imp.package.version.osgi.framework}", - org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.apache.commons.logging, - io.entgra.device.mgt.core.device.mgt.common.*, - io.entgra.device.mgt.core.device.mgt.core.service - io.entgra.device.mgt.core.policy.mgt.core.*, - io.entgra.device.mgt.core.policy.mgt.core, - com.google.gson, - io.entgra.device.mgt.core.device.mgt.core.service.*, - io.entgra.device.mgt.core.application.mgt.common.*, - io.entgra.device.mgt.core.application.mgt.common.services.* + com.google.gson;version="[2.9,3)", + io.entgra.device.mgt.core.application.mgt.common.exception;version="[5.0,6)", + io.entgra.device.mgt.core.application.mgt.common.services;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.operation.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.pull.notification;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.service;version="[5.0,6)", + io.entgra.device.mgt.core.policy.mgt.core;version="[5.0,6)", + org.apache.commons.logging;version="[1.2,2)", + org.osgi.service.*;version="${imp.package.version.osgi.service}" diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/pull/notification/PullNotificationSubscriberImpl.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/pull/notification/PullNotificationSubscriberImpl.java index 3967b5eed3..8826e8019d 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/pull/notification/PullNotificationSubscriberImpl.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/pull/notification/PullNotificationSubscriberImpl.java @@ -21,11 +21,9 @@ import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonParser; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; -import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; +import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManagementException; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.ComplianceFeature; @@ -33,6 +31,8 @@ import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.PolicyComp import io.entgra.device.mgt.core.device.mgt.common.pull.notification.PullNotificationExecutionFailedException; import io.entgra.device.mgt.core.device.mgt.common.pull.notification.PullNotificationSubscriber; import io.entgra.device.mgt.core.device.mgt.extensions.pull.notification.internal.PullNotificationDataHolder; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.util.ArrayList; import java.util.List; diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/pull/notification/internal/PullNotificationServiceComponent.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/pull/notification/internal/PullNotificationServiceComponent.java index 5a44909555..924c4c6633 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/pull/notification/internal/PullNotificationServiceComponent.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/pull/notification/internal/PullNotificationServiceComponent.java @@ -17,39 +17,23 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.pull.notification.internal; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; -/** - * @scr.component name="io.entgra.device.mgt.core.device.mgt.extensions.pull.notification.internal.PullNotificationServiceComponent" immediate="true" - * @scr.reference name="carbon.device.mgt.provider" - * interface="io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDeviceManagementProviderService" - * unbind="unsetDeviceManagementProviderService" - * @scr.reference name="io.entgra.device.mgt.core.policy.mgt.core" - * interface="io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService" - * cardinality="1..1" - * policy="dynamic" - * bind="setPolicyManagerService" - * unbind="unsetPolicyManagerService" - * @scr.reference name="org.wso2.carbon.application.mgt.service" - * interface="io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager" - * cardinality="1..1" - * policy="dynamic" - * bind="setApplicationManagerService" - * unbind="unsetApplicationManagerService" - */ +@Component( + name = "io.entgra.device.mgt.core.device.mgt.extensions.pull.notification.internal.PullNotificationServiceComponent", + immediate = true) public class PullNotificationServiceComponent { private static final Log log = LogFactory.getLog(PullNotificationServiceComponent.class); @SuppressWarnings("unused") + @Activate protected void activate(ComponentContext componentContext) { try { //Do nothing @@ -62,11 +46,17 @@ public class PullNotificationServiceComponent { "implementation bundle", e); } } - + @Deactivate protected void deactivate(ComponentContext componentContext) { //Do nothing } + @Reference( + name = "device.mgt.provider.service", + service = io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDeviceManagementProviderService") protected void setDeviceManagementProviderService(DeviceManagementProviderService deviceManagementProviderService) { PullNotificationDataHolder.getInstance().setDeviceManagementProviderService(deviceManagementProviderService); } @@ -75,6 +65,12 @@ public class PullNotificationServiceComponent { PullNotificationDataHolder.getInstance().setDeviceManagementProviderService(null); } + @Reference( + name = "policy.mgr.service", + service = io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetPolicyManagerService") protected void setPolicyManagerService(PolicyManagerService policyManagerService) { PullNotificationDataHolder.getInstance().setPolicyManagerService(policyManagerService); } @@ -83,6 +79,12 @@ public class PullNotificationServiceComponent { PullNotificationDataHolder.getInstance().setPolicyManagerService(null); } + @Reference( + name = "applcation.mgr", + service = io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetApplicationManagerService") protected void setApplicationManagerService(ApplicationManager applicationManagerService){ PullNotificationDataHolder.getInstance().setApplicationManager(applicationManagerService); } diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml index 8453f05e9f..01e0074adf 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml @@ -31,9 +31,14 @@ bundle WSO2 Carbon - FCM Based Push Notification Provider Implementation WSO2 Carbon - FCM Based Push Notification Provider Implementation - http://wso2.org + https://entgra.io + + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + org.wso2.carbon.governance org.wso2.carbon.governance.api @@ -63,23 +68,15 @@ org.wso2.carbon.utils - org.wso2.orbit.org.scannotation + io.entgra.org.scannotation scannotation - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services - - - org.wso2.tomcat + org.wso2.orbit.org.apache.tomcat tomcat - org.wso2.tomcat + org.wso2.orbit.org.apache.tomcat tomcat-servlet-api @@ -151,13 +148,21 @@ org.wso2.carbon org.wso2.carbon.utils + + com.squareup.okhttp3 + okhttp + - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java index 39bd1ba7e5..e166f500c7 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java @@ -18,9 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm; import com.google.gson.JsonObject; -import io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.util.FCMUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.push.notification.NotificationContext; @@ -28,11 +25,14 @@ import io.entgra.device.mgt.core.device.mgt.common.push.notification.Notificatio import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationConfig; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationExecutionFailedException; import io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.internal.FCMDataHolder; +import io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.util.FCMUtil; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.io.IOException; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; import java.util.List; public class FCMNotificationStrategy implements NotificationStrategy { @@ -89,8 +89,6 @@ public class FCMNotificationStrategy implements NotificationStrategy { */ private void sendWakeUpCall(String accessToken, String registrationId) throws IOException, PushNotificationExecutionFailedException { - HttpURLConnection conn = null; - String fcmServerEndpoint = FCMUtil.getInstance().getContextMetadataProperties() .getProperty(FCM_ENDPOINT_KEY); if(fcmServerEndpoint == null) { @@ -99,26 +97,21 @@ public class FCMNotificationStrategy implements NotificationStrategy { throw new PushNotificationExecutionFailedException(msg); } - try { - byte[] bytes = getFCMRequest(registrationId).getBytes(); - URL url = new URL(fcmServerEndpoint); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestProperty("Content-Type", "application/json"); - conn.setRequestProperty("Authorization", "Bearer " + accessToken); - conn.setRequestMethod("POST"); - conn.setDoOutput(true); - - try (OutputStream os = conn.getOutputStream()) { - os.write(bytes); - } - - int status = conn.getResponseCode(); - if (status != 200) { - log.error("Response Status: " + status + ", Response Message: " + conn.getResponseMessage()); + RequestBody fcmRequest = getFCMRequest(registrationId); + Request request = new Request.Builder() + .url(fcmServerEndpoint) + .post(fcmRequest) + .addHeader("Authorization", "Bearer " + accessToken) + .build(); + try (Response response = FCMUtil.getInstance().getHttpClient().newCall(request).execute()) { + if (log.isDebugEnabled()) { + log.debug("FCM message sent to the FCM server. Response code: " + response.code() + + " Response message : " + response.message()); } - } finally { - if (conn != null) { - conn.disconnect(); + if(!response.isSuccessful()) { + String msg = "Response Status: " + response.code() + ", Response Message: " + response.message(); + log.error(msg); + throw new IOException(msg); } } } @@ -128,14 +121,14 @@ public class FCMNotificationStrategy implements NotificationStrategy { * @param registrationId Registration ID of the device * @return FCM request as a JSON string */ - private static String getFCMRequest(String registrationId) { + private static RequestBody getFCMRequest(String registrationId) { JsonObject messageObject = new JsonObject(); messageObject.addProperty("token", registrationId); JsonObject fcmRequest = new JsonObject(); fcmRequest.add("message", messageObject); - return fcmRequest.toString(); + return RequestBody.create(fcmRequest.toString(), okhttp3.MediaType.parse("application/json")); } @Override diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/internal/FCMPushNotificationServiceComponent.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/internal/FCMPushNotificationServiceComponent.java index c6ae0128a9..203b1f0cd4 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/internal/FCMPushNotificationServiceComponent.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/internal/FCMPushNotificationServiceComponent.java @@ -17,25 +17,21 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.internal; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import org.osgi.service.component.annotations.*; -/** - * @scr.component name="io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.internal.FCMPushNotificationServiceComponent" immediate="true" - * @scr.reference name="carbon.device.mgt.provider" - * interface="io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDeviceManagementProviderService" - * unbind="unsetDeviceManagementProviderService" - */ +@Component( + name = "io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.internal.FCMPushNotificationServiceComponent", + immediate = true) public class FCMPushNotificationServiceComponent { private static final Log log = LogFactory.getLog(FCMPushNotificationServiceComponent.class); @SuppressWarnings("unused") + @Activate protected void activate(ComponentContext componentContext) { try { //Do nothing @@ -48,11 +44,16 @@ public class FCMPushNotificationServiceComponent { "implementation bundle", e); } } - + @Deactivate protected void deactivate(ComponentContext componentContext) { //Do nothing } - + @Reference( + name = "device.mgt.provider.service", + service = io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDeviceManagementProviderService") protected void setDeviceManagementProviderService( DeviceManagementProviderService deviceManagementProviderService) { FCMDataHolder.getInstance().setDeviceManagementProviderService(deviceManagementProviderService); diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java index 0c6c433cc7..e3d15d8974 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java @@ -22,6 +22,8 @@ import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManag import io.entgra.device.mgt.core.device.mgt.core.config.push.notification.ContextMetadata; import io.entgra.device.mgt.core.device.mgt.core.config.push.notification.PushNotificationConfiguration; import io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.FCMNotificationStrategy; +import okhttp3.ConnectionPool; +import okhttp3.OkHttpClient; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.utils.CarbonUtils; @@ -33,6 +35,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Properties; +import java.util.concurrent.TimeUnit; public class FCMUtil { @@ -43,10 +46,29 @@ public class FCMUtil { "repository" + File.separator + "resources" + File.separator + "service-account.json"; private static final String[] FCM_SCOPES = { "https://www.googleapis.com/auth/firebase.messaging" }; private Properties contextMetadataProperties; + private static ConnectionPool connectionPool; + private static OkHttpClient client; private FCMUtil() { initContextConfigs(); initDefaultOAuthApplication(); + initPooledConnection(); + } + + /** + * Initialize the connection pool for the OkHttpClient instance. + */ + private void initPooledConnection() { + connectionPool = new ConnectionPool(25, 1, TimeUnit.MINUTES); + client = new OkHttpClient.Builder().connectionPool(connectionPool).build(); + } + + /** + * Get the Pooled OkHttpClient instance + * @return OkHttpClient instance + */ + public OkHttpClient getHttpClient() { + return client; } private void initDefaultOAuthApplication() { diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/pom.xml index 53d4fbab79..1ae1b328cf 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/pom.xml @@ -31,9 +31,14 @@ bundle WSO2 Carbon - HTTP Based Push Notification Provider Implementation WSO2 Carbon - HTTP Based Push Notification Provider Implementation - http://wso2.org + https://entgra.io + + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + org.wso2.carbon.governance org.wso2.carbon.governance.api @@ -63,23 +68,15 @@ org.wso2.carbon.utils - org.wso2.orbit.org.scannotation + io.entgra.org.scannotation scannotation - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services - - - org.wso2.tomcat + org.wso2.orbit.org.apache.tomcat tomcat - org.wso2.tomcat + org.wso2.orbit.org.apache.tomcat tomcat-servlet-api @@ -107,8 +104,12 @@ - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -125,18 +126,13 @@ io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.* - org.apache.commons.logging, - org.osgi.framework.*;version="${imp.package.version.osgi.framework}", - org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.wso2.carbon.context, - io.entgra.device.mgt.core.device.mgt.common.operation.mgt, - io.entgra.device.mgt.core.device.mgt.common.push.notification, - io.entgra.device.mgt.core.device.mgt.common, - io.entgra.device.mgt.core.device.mgt.core.service, - io.entgra.device.mgt.core.device.mgt.core.operation.mgt, - org.wso2.carbon.core, - com.google.gson, - org.apache.commons.httpclient.* + com.google.gson;version="[2.9,3)", + io.entgra.device.mgt.core.device.mgt.common.exceptions;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.push.notification;version="[5.0,6)", + org.apache.commons.httpclient;version="[3.1,4)", + org.apache.commons.httpclient.methods;version="[3.1,4)", + org.apache.commons.logging;version="[1.2,2)", + org.osgi.service.*;version="${imp.package.version.osgi.service}" diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/http/HTTPMessageExecutor.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/http/HTTPMessageExecutor.java index 3122e727a7..7acf8c42f1 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/http/HTTPMessageExecutor.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/http/HTTPMessageExecutor.java @@ -19,6 +19,8 @@ package io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http; import com.google.gson.Gson; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidConfigurationException; +import io.entgra.device.mgt.core.device.mgt.common.push.notification.NotificationContext; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.EntityEnclosingMethod; @@ -26,8 +28,6 @@ import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidConfigurationException; -import io.entgra.device.mgt.core.device.mgt.common.push.notification.NotificationContext; import java.net.UnknownHostException; diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/http/HTTPNotificationStrategy.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/http/HTTPNotificationStrategy.java index 5d9ec3bb98..79c7eea49a 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/http/HTTPNotificationStrategy.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/http/HTTPNotificationStrategy.java @@ -17,15 +17,15 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http; -import org.apache.commons.httpclient.HostConfiguration; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidConfigurationException; import io.entgra.device.mgt.core.device.mgt.common.push.notification.NotificationContext; import io.entgra.device.mgt.core.device.mgt.common.push.notification.NotificationStrategy; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationConfig; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationExecutionFailedException; +import org.apache.commons.httpclient.HostConfiguration; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.net.MalformedURLException; import java.net.URL; diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/http/internal/HTTPPushNotificationServiceComponent.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/http/internal/HTTPPushNotificationServiceComponent.java index 4a6dde580c..54e24395b1 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/http/internal/HTTPPushNotificationServiceComponent.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/http/internal/HTTPPushNotificationServiceComponent.java @@ -20,15 +20,17 @@ package io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provid import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; - -/** - * @scr.component name="io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.internal.HTTPPushNotificationServiceComponent" immediate="true" - */ +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +@Component( + name = "io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.internal.HTTPPushNotificationServiceComponent", + immediate = true) public class HTTPPushNotificationServiceComponent { private static final Log log = LogFactory.getLog(HTTPPushNotificationServiceComponent.class); @SuppressWarnings("unused") + @Activate protected void activate(ComponentContext componentContext) { try { if (log.isDebugEnabled()) { diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/pom.xml index 2b9a09a282..0477011b9f 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/pom.xml @@ -31,9 +31,14 @@ bundle WSO2 Carbon - MQTT Based Push Notification Provider Implementation WSO2 Carbon - MQTT Based Push Notification Provider Implementation - http://wso2.org + https://entgra.io + + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + org.wso2.carbon.governance org.wso2.carbon.governance.api @@ -63,23 +68,15 @@ org.wso2.carbon.utils - org.wso2.orbit.org.scannotation + io.entgra.org.scannotation scannotation - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services - - - org.wso2.tomcat + org.wso2.orbit.org.apache.tomcat tomcat - org.wso2.tomcat + org.wso2.orbit.org.apache.tomcat tomcat-servlet-api @@ -125,12 +122,26 @@ powermock-module-testng test + + org.wso2.carbon + org.wso2.carbon.securevault + test + + + org.mockito + mockito-core + test + - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -147,21 +158,17 @@ io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.* - org.apache.commons.logging, - org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.exceptions;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.operation.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.push.notification;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.operation.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.service;version="[5.0,6)", + org.apache.commons.logging;version="[1.2,2)", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.wso2.carbon.context, - io.entgra.device.mgt.core.device.mgt.common.operation.mgt, - io.entgra.device.mgt.core.device.mgt.common.push.notification, - io.entgra.device.mgt.core.device.mgt.common, - io.entgra.device.mgt.core.device.mgt.common.exceptions, - io.entgra.device.mgt.core.device.mgt.core.service, - org.wso2.carbon.event.output.adapter.core, - org.wso2.carbon.event.output.adapter.core.exception, - io.entgra.device.mgt.core.device.mgt.core.operation.mgt, - org.wso2.carbon.core, - io.entgra.device.mgt.core.application.mgt.common.*, - io.entgra.device.mgt.core.application.mgt.common.services.* + org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.event.output.adapter.core;version="[5.3,6)", + org.wso2.carbon.event.output.adapter.core.exception;version="[5.3,6)" @@ -192,6 +199,25 @@ + + org.apache.maven.plugins + maven-surefire-plugin + + + --add-opens=java.xml/jdk.xml.internal=ALL-UNNAMED + --add-opens=java.base/jdk.internal.loader=ALL-UNNAMED + + + file:src/test/resources/log4j.properties + + + src/test/resources/testng.xml + + + org.ops4j.pax.logging + + + diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/MQTTNotificationStrategy.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/MQTTNotificationStrategy.java index e1128f6d8c..8d97facb6b 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/MQTTNotificationStrategy.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/MQTTNotificationStrategy.java @@ -17,22 +17,22 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidConfigurationException; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.common.push.notification.NotificationContext; import io.entgra.device.mgt.core.device.mgt.common.push.notification.NotificationStrategy; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationConfig; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationExecutionFailedException; +import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.PolicyOperation; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.ProfileOperation; import io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.internal.MQTTDataHolder; import io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.internal.util.MQTTAdapterConstants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.event.output.adapter.core.MessageType; import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration; import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException; -import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.PolicyOperation; import java.util.HashMap; import java.util.List; diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/internal/MQTTDataHolder.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/internal/MQTTDataHolder.java index df2de21783..27124a0949 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/internal/MQTTDataHolder.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/internal/MQTTDataHolder.java @@ -18,7 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.internal; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration; import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService; public class MQTTDataHolder { diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/internal/MQTTPushNotificationServiceComponent.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/internal/MQTTPushNotificationServiceComponent.java index cc8215ceaf..1f4413fba8 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/internal/MQTTPushNotificationServiceComponent.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/internal/MQTTPushNotificationServiceComponent.java @@ -17,32 +17,22 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.internal; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService; -/** - * @scr.component name="io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.internal.MQTTPushNotificationServiceComponent" immediate="true" - * @scr.reference name="carbon.device.mgt.provider" - * interface="io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDeviceManagementProviderService" - * unbind="unsetDeviceManagementProviderService" - * @scr.reference name="event.output.adapter.service" - * interface="org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService" - * cardinality="1..1" - * policy="dynamic" - * bind="setOutputEventAdapterService" - * unbind="unsetOutputEventAdapterService" - */ +@Component( + name = "io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.internal.MQTTPushNotificationServiceComponent", + immediate = true) public class MQTTPushNotificationServiceComponent { private static final Log log = LogFactory.getLog(MQTTPushNotificationServiceComponent.class); @SuppressWarnings("unused") + @Activate protected void activate(ComponentContext componentContext) { try { if (log.isDebugEnabled()) { @@ -58,11 +48,17 @@ public class MQTTPushNotificationServiceComponent { "implementation bundle", e); } } - + @Deactivate protected void deactivate(ComponentContext componentContext) { //Do nothing } + @Reference( + name = "device.mgt.provider.service", + service = io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDeviceManagementProviderService") protected void setDeviceManagementProviderService( DeviceManagementProviderService deviceManagementProviderService) { MQTTDataHolder.getInstance().setDeviceManagementProviderService(deviceManagementProviderService); @@ -73,6 +69,12 @@ public class MQTTPushNotificationServiceComponent { MQTTDataHolder.getInstance().setDeviceManagementProviderService(deviceManagementProviderService); } + @Reference( + name = "output.event.adaptor.service", + service = org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetOutputEventAdapterService") protected void setOutputEventAdapterService(OutputEventAdapterService outputEventAdapterService){ MQTTDataHolder.getInstance().setOutputEventAdapterService(outputEventAdapterService); } diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/MQTTBasedPushNotificationProviderTest.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/MQTTBasedPushNotificationProviderTest.java index 6f85027688..c819f7dd6f 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/MQTTBasedPushNotificationProviderTest.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/MQTTBasedPushNotificationProviderTest.java @@ -18,15 +18,14 @@ package io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.push.notification.NotificationStrategy; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationConfig; import io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.internal.MQTTDataHolder; import io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.internal.util.MQTTAdapterConstants; +import org.mockito.Mockito; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException; import org.wso2.carbon.event.output.adapter.core.internal.CarbonOutputEventAdapterService; import org.wso2.carbon.registry.core.exceptions.RegistryException; diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/MQTTNotificationStrategyTest.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/MQTTNotificationStrategyTest.java index 164f453157..e32c6af108 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/MQTTNotificationStrategyTest.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/mqtt/MQTTNotificationStrategyTest.java @@ -18,12 +18,8 @@ package io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.common.push.notification.NotificationContext; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationConfig; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationExecutionFailedException; @@ -31,19 +27,19 @@ import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.PolicyOperation; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.ProfileOperation; import io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.internal.MQTTDataHolder; import io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.internal.util.MQTTAdapterConstants; +import org.mockito.Mockito; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException; import org.wso2.carbon.event.output.adapter.core.internal.CarbonOutputEventAdapterService; import org.wso2.carbon.registry.core.exceptions.RegistryException; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; -import static io.entgra.device.mgt.core.device.mgt.core.operation.mgt.PolicyOperation.POLICY_OPERATION_CODE; import java.io.IOException; import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; +import java.util.*; + +import static io.entgra.device.mgt.core.device.mgt.core.operation.mgt.PolicyOperation.POLICY_OPERATION_CODE; /* Unit tests for MQTTNotificationStrategy class diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/test/resources/conf/carbon.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/test/resources/conf/carbon.xml deleted file mode 100644 index a5518cb720..0000000000 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/test/resources/conf/carbon.xml +++ /dev/null @@ -1,658 +0,0 @@ - - - - - - - - - ${product.name} - - - ${product.key} - - - ${product.version} - - - - - - - - - local:/${carbon.context}/services/ - - - - - - - ${default.server.role} - - - - - - - org.wso2.carbon - - - / - - - - - - - - - 15 - - - - - - - - - 0 - - - - - 9999 - - 11111 - - - - - - 10389 - - 8000 - - - - - - 10500 - - - - - - - org.wso2.carbon.tomcat.jndi.CarbonJavaURLContextFactory - - - - - - - - - java - - - - - - - - - - false - - - false - - - 600 - - - - false - - - - - - - - 30 - - - - - - - - - 15 - - - - - - ${carbon.home}/repository/deployment/server/ - - - 15 - - - ${carbon.home}/repository/conf/axis2/axis2.xml - - - 30000 - - - ${carbon.home}/repository/deployment/client/ - - ${carbon.home}/repository/conf/axis2/axis2_client.xml - - true - - - - - - - - - - admin - Default Administrator Role - - - user - Default User Role - - - - - - - - - - - - ${carbon.home}/repository/resources/security/wso2carbon.jks - - JKS - - wso2carbon - - wso2carbon - - wso2carbon - - - - - - ${carbon.home}/repository/resources/security/client-truststore.jks - - JKS - - wso2carbon - - - - - - - - - - - - - - - - - - - UserManager - - - false - - - - - - - ${carbon.home}/tmp/work - - - - - - true - - - 10 - - - 30 - - - - - - 100 - - - - keystore - certificate - * - - org.wso2.carbon.ui.transports.fileupload.AnyFileUploadExecutor - - - - - jarZip - - org.wso2.carbon.ui.transports.fileupload.JarZipUploadExecutor - - - - dbs - - org.wso2.carbon.ui.transports.fileupload.DBSFileUploadExecutor - - - - tools - - org.wso2.carbon.ui.transports.fileupload.ToolsFileUploadExecutor - - - - toolsAny - - org.wso2.carbon.ui.transports.fileupload.ToolsAnyFileUploadExecutor - - - - - - - info - org.wso2.carbon.core.transports.util.InfoProcessor - - - wsdl - org.wso2.carbon.core.transports.util.Wsdl11Processor - - - wsdl2 - org.wso2.carbon.core.transports.util.Wsdl20Processor - - - xsd - org.wso2.carbon.core.transports.util.XsdProcessor - - - - - - false - false - true - svn - http://svnrepo.example.com/repos/ - username - password - true - - - - - - - - - - - - - - - ${require.carbon.servlet} - - - - - true - - - - - - - default repository - ${p2.repo.url} - - - - - - - - true - - - - - - true - - diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/test/resources/repository/conf/carbon.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/src/test/resources/repository/conf/carbon.xml new file mode 100644 index 0000000000..e69de29bb2 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/pom.xml index c0de48044f..d22a7befe7 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/pom.xml @@ -31,9 +31,14 @@ bundle WSO2 Carbon - XMPP Based Push Notification Provider Implementation WSO2 Carbon - XMPP Based Push Notification Provider Implementation - http://wso2.org + https://entgra.io + + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + org.wso2.carbon.governance org.wso2.carbon.governance.api @@ -63,23 +68,15 @@ org.wso2.carbon.utils - org.wso2.orbit.org.scannotation + io.entgra.org.scannotation scannotation - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services - - - org.wso2.tomcat + org.wso2.orbit.org.apache.tomcat tomcat - org.wso2.tomcat + org.wso2.orbit.org.apache.tomcat tomcat-servlet-api @@ -116,8 +113,12 @@ - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -134,17 +135,15 @@ io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.* - org.apache.commons.logging, - org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.exceptions;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.operation.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.push.notification;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.service;version="[5.0,6)", + org.apache.commons.logging;version="[1.2,2)", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.wso2.carbon.context, - io.entgra.device.mgt.core.device.mgt.common.operation.mgt, - io.entgra.device.mgt.core.device.mgt.common.push.notification, - io.entgra.device.mgt.core.device.mgt.core.*, - org.wso2.carbon.event.output.adapter.core, - org.wso2.carbon.event.output.adapter.core.exception, - org.wso2.carbon.core, - io.entgra.device.mgt.core.device.mgt.common.* + org.wso2.carbon.event.output.adapter.core;version="[5.3,6)", + org.wso2.carbon.event.output.adapter.core.exception;version="[5.3,6)" diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/xmpp/XMPPNotificationStrategy.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/xmpp/XMPPNotificationStrategy.java index 597789dd36..4e5dcde5bf 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/xmpp/XMPPNotificationStrategy.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/xmpp/XMPPNotificationStrategy.java @@ -17,8 +17,6 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidConfigurationException; import io.entgra.device.mgt.core.device.mgt.common.push.notification.NotificationContext; import io.entgra.device.mgt.core.device.mgt.common.push.notification.NotificationStrategy; @@ -26,6 +24,8 @@ import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotific import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationExecutionFailedException; import io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.internal.XMPPDataHolder; import io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.internal.util.XMPPAdapterConstants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.event.output.adapter.core.MessageType; import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration; import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException; diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/xmpp/internal/XMPPPushNotificationServiceComponent.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/xmpp/internal/XMPPPushNotificationServiceComponent.java index 3a509d03ae..035fa40369 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/xmpp/internal/XMPPPushNotificationServiceComponent.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/xmpp/internal/XMPPPushNotificationServiceComponent.java @@ -17,32 +17,22 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.internal; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService; -/** - * @scr.component name="io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.internal.XMPPPushNotificationServiceComponent" immediate="true" - * @scr.reference name="carbon.device.mgt.provider" - * interface="io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDeviceManagementProviderService" - * unbind="unsetDeviceManagementProviderService" - * @scr.reference name="event.output.adapter.service" - * interface="org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService" - * cardinality="1..1" - * policy="dynamic" - * bind="setOutputEventAdapterService" - * unbind="unsetOutputEventAdapterService" - */ +@Component( + name = "io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.internal.XMPPPushNotificationServiceComponent", + immediate = true) public class XMPPPushNotificationServiceComponent { private static final Log log = LogFactory.getLog(XMPPPushNotificationServiceComponent.class); @SuppressWarnings("unused") + @Activate protected void activate(ComponentContext componentContext) { try { if (log.isDebugEnabled()) { @@ -58,11 +48,17 @@ public class XMPPPushNotificationServiceComponent { "implementation bundle", e); } } - + @Deactivate protected void deactivate(ComponentContext componentContext) { //Do nothing } + @Reference( + name = "device.mgt.provider.service", + service = io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDeviceManagementProviderService") protected void setDeviceManagementProviderService( DeviceManagementProviderService deviceManagementProviderService) { XMPPDataHolder.getInstance().setDeviceManagementProviderService(deviceManagementProviderService); @@ -73,6 +69,12 @@ public class XMPPPushNotificationServiceComponent { XMPPDataHolder.getInstance().setDeviceManagementProviderService(deviceManagementProviderService); } + @Reference( + name = "output.event.adaptor.service", + service = org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetOutputEventAdapterService") protected void setOutputEventAdapterService(OutputEventAdapterService outputEventAdapterService){ XMPPDataHolder.getInstance().setOutputEventAdapterService(outputEventAdapterService); } diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/pom.xml index 27a70b464e..3cc4114dc9 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/pom.xml @@ -38,10 +38,10 @@ org.apache.maven.plugins maven-compiler-plugin - - - org.apache.felix - maven-scr-plugin + + 1.8 + 1.8 + org.apache.felix @@ -54,13 +54,13 @@ ${io.entgra.device.mgt.core.version} IoT Device Management State Engine Bundle - org.wso2.carbon.context, - org.wso2.carbon.logging, - org.apache.commons.lang, - org.wso2.carbon.user.api, - org.apache.commons.logging, - org.wso2.carbon.user.core.service, - io.entgra.device.mgt.core.device.mgt.common.* + io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.extensions.stateengine.dto, + io.entgra.device.mgt.core.device.mgt.extensions.stateengine.exception, + org.apache.commons.logging;version="[1.2,2)", + org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.user.api;version="[1.0,2)", + org.wso2.carbon.user.core.service;version="[4.8,5)" io.entgra.device.mgt.core.device.mgt.extensions.stateengine.*, @@ -100,8 +100,14 @@ - org.wso2.carbon - org.wso2.carbon.logging + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + + + org.ops4j.pax.logging + pax-logging-api + provided com.google.code.gson diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/stateengine/spi/DeviceStateMachine.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/stateengine/spi/DeviceStateMachine.java index caca232a9b..a9dbd4edd9 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/stateengine/spi/DeviceStateMachine.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/stateengine/spi/DeviceStateMachine.java @@ -18,10 +18,10 @@ package io.entgra.device.mgt.core.device.mgt.extensions.stateengine.spi; -import io.entgra.device.mgt.core.device.mgt.extensions.stateengine.dto.StateUpdateResult; -import io.entgra.device.mgt.core.device.mgt.extensions.stateengine.exception.StateValidationException; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; +import io.entgra.device.mgt.core.device.mgt.extensions.stateengine.dto.StateUpdateResult; +import io.entgra.device.mgt.core.device.mgt.extensions.stateengine.exception.StateValidationException; public interface DeviceStateMachine { diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/pom.xml index 8cd558dda0..a6b55859df 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/pom.xml @@ -36,16 +36,12 @@ - org.apache.felix - maven-scr-plugin - - + org.apache.maven.plugins maven-compiler-plugin 1.8 1.8 - 2.3.2 org.apache.felix @@ -130,21 +126,14 @@ - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services + org.apache.felix + org.apache.felix.scr.ds-annotations + provided org.wso2.carbon org.wso2.carbon.core - - org.wso2.carbon - org.wso2.carbon.logging - org.wso2.carbon org.wso2.carbon.utils @@ -193,7 +182,6 @@ org.wso2.carbon org.wso2.carbon.securevault - test @@ -216,11 +204,6 @@ org.wso2.carbon.queuing test - - javax.xml.bind - jaxb-api - test - io.entgra.device.mgt.core io.entgra.device.mgt.core.server.bootup.heartbeat.beacon diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/internal/UserStoreRoleMappingServiceComponent.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/internal/UserStoreRoleMappingServiceComponent.java index 2471c18403..9e2c3ae1e0 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/internal/UserStoreRoleMappingServiceComponent.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/internal/UserStoreRoleMappingServiceComponent.java @@ -25,36 +25,19 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.core.ServerStartupObserver; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.utils.ConfigurationContextService; -/** - * @scr.component name="io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper.internal.UserStoreRoleMappingServiceComponent" - * immediate="true" - * @scr.reference name="user.realmservice.default" - * interface="org.wso2.carbon.user.core.service.RealmService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRealmService" - * unbind="unsetRealmService" - * @scr.reference name="config.context.service" - * interface="org.wso2.carbon.utils.ConfigurationContextService" - * cardinality="0..1" - * policy="dynamic" - * bind="setConfigurationContextService" - * unbind="unsetConfigurationContextService" - * @scr.reference name="entgra.heart.beat.service" - * interface="io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService" - * cardinality="0..1" - * policy="dynamic" - * bind="setHeartBeatService" - * unbind="unsetHeartBeatService" - */ +@Component( + name = "io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper.internal.UserStoreRoleMappingServiceComponent", + immediate = true) public class UserStoreRoleMappingServiceComponent { private static final Log log = LogFactory.getLog(UserStoreRoleMappingServiceComponent.class); + @Activate protected void activate(ComponentContext ctx) { if (log.isDebugEnabled()) { log.debug("Activating Role Management Service Component"); @@ -72,12 +55,19 @@ public class UserStoreRoleMappingServiceComponent { } } + @Deactivate protected void deactivate(ComponentContext ctx) { if (log.isDebugEnabled()) { log.debug("De-activating Role Manager Service Component"); } } + @Reference( + name = "user.realmservice.default", + service = org.wso2.carbon.user.core.service.RealmService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRealmService") protected void setConfigurationContextService(ConfigurationContextService configurationContextService) { if (log.isDebugEnabled()) { log.debug("Setting ConfigurationContextService"); @@ -86,6 +76,12 @@ public class UserStoreRoleMappingServiceComponent { UserStoreRoleMappingDataHolder.getInstance().setConfigurationContextService(configurationContextService); } + @Reference( + name = "config.context.service", + service = org.wso2.carbon.utils.ConfigurationContextService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetConfigurationContextService") protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) { if (log.isDebugEnabled()) { log.debug("Un-setting ConfigurationContextService"); @@ -118,6 +114,12 @@ public class UserStoreRoleMappingServiceComponent { } @SuppressWarnings("unused") + @Reference( + name = "entgra.heart.beat.service", + service = io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetHeartBeatService") protected void setHeartBeatService(HeartBeatManagementService heartBeatService) { if (log.isDebugEnabled()) { log.debug("Setting heart beat service"); diff --git a/components/device-mgt-extensions/pom.xml b/components/device-mgt-extensions/pom.xml index 5e906f2c8e..455aa0679c 100644 --- a/components/device-mgt-extensions/pom.xml +++ b/components/device-mgt-extensions/pom.xml @@ -31,7 +31,7 @@ pom WSO2 Carbon - Device Management Extensions WSO2 Carbon - Device Management Extensions - http://wso2.org + https://entgra.io io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml index a84a45a8d2..6ce3f3e666 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml @@ -31,11 +31,12 @@ war WSO2 Carbon - Mobile Device Management API WSO2 Carbon - Mobile Device Management API - http://wso2.org + https://entgra.io + org.apache.maven.plugins maven-compiler-plugin 1.8 @@ -43,6 +44,7 @@ + org.apache.maven.plugins maven-war-plugin WEB-INF/lib/*cxf*.jar @@ -99,7 +101,6 @@ org.apache.maven.plugins maven-antrun-plugin - 1.7 compile @@ -129,7 +130,6 @@ org.codehaus.mojo exec-maven-plugin - 1.2.1 test @@ -155,22 +155,29 @@ spring-web provided - - org.apache.cxf - cxf-bundle - 3.0.0-milestone2 - test - - - org.apache.cxf - cxf-bundle-jaxrs - provided - commons-httpclient.wso2 commons-httpclient provided + + org.apache.cxf + cxf-rt-frontend-jaxrs + + + javax.ws.rs + jsr311-api + + + org.apache.cxf + cxf-rt-core + + + jakarta.xml.bind + jakarta.xml.bind-api + + + org.wso2.carbon org.wso2.carbon.utils @@ -189,11 +196,15 @@ org.slf4j jcl-over-slf4j + + org.ops4j.pax.logging + pax-logging-log4j2 + - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api provided @@ -223,6 +234,14 @@ javassist javassist + + javax.ws.rs + jsr311-api + + + javax.ws.rs + javax.ws.rs-api + @@ -291,10 +310,6 @@ org.slf4j slf4j-api - - org.wso2.orbit.com.fasterxml.jackson.core - jackson-core - @@ -310,8 +325,8 @@ slf4j-api - org.wso2.orbit.com.fasterxml.jackson.core - jackson-core + javax.ws.rs + jsr311-api @@ -325,29 +340,10 @@ io.entgra.device.mgt.core.apimgt.annotations provided - - org.wso2.orbit.com.fasterxml.jackson.core - jackson-annotations - org.hibernate hibernate-validator - - javax.ws.rs - javax.ws.rs-api - provided - - - javax.ws.rs - jsr311-api - provided - - - org.wso2.carbon.commons - org.wso2.carbon.application.mgt.stub - provided - org.wso2.carbon.analytics org.wso2.carbon.analytics.api @@ -366,6 +362,12 @@ org.wso2.carbon.registry org.wso2.carbon.registry.resource + + + javax.ws.rs + javax.ws.rs-api + + provided @@ -374,11 +376,6 @@ ${carbon.identity.framework.version} provided - - - - - org.wso2.carbon.analytics-common org.wso2.carbon.event.receiver.stub @@ -406,7 +403,7 @@ org.powermock - powermock-api-mockito + powermock-api-mockito2 test @@ -419,6 +416,12 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.application.mgt.common provided + + + org.wso2.orbit.javax.xml.bind + jaxb-api + + io.entgra.device.mgt.core @@ -460,5 +463,15 @@ io.entgra.device.mgt.core.apimgt.webapp.publisher provided + + org.wso2.orbit.javax.xml.bind + jaxb-api + provided + + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.tenant.mgt.common + provided + \ No newline at end of file diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/NotificationContext.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/NotificationContext.java index 18e2d43a7e..80c9aba849 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/NotificationContext.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/NotificationContext.java @@ -18,10 +18,10 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs; import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.Notification; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; @ApiModel(value = "NotificationContext") public class NotificationContext { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/NotificationList.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/NotificationList.java index 4753d0ed6f..853b08a27c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/NotificationList.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/NotificationList.java @@ -18,9 +18,9 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs; import com.fasterxml.jackson.annotation.JsonProperty; +import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.Notification; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.Notification; import java.util.ArrayList; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ActivityList.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ActivityList.java index e4a9fce702..ede2a22bbf 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ActivityList.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ActivityList.java @@ -19,9 +19,9 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.gson.Gson; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ApplicationList.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ApplicationList.java index b57f0ba437..38338f0a8c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ApplicationList.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ApplicationList.java @@ -19,8 +19,8 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModelProperty; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.Application; +import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ApplicationWrapper.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ApplicationWrapper.java index 58177319fc..6aca491d71 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ApplicationWrapper.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ApplicationWrapper.java @@ -18,10 +18,10 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.App; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/AuthorizationRequest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/AuthorizationRequest.java index c4e4d0cfa3..bb5c00a12f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/AuthorizationRequest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/AuthorizationRequest.java @@ -17,9 +17,9 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ComplianceDeviceList.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ComplianceDeviceList.java index 65b823ea61..4712cbedbf 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ComplianceDeviceList.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ComplianceDeviceList.java @@ -19,8 +19,8 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModelProperty; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.ComplianceData; +import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/Credential.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/Credential.java index ef827e26a1..c919d194a0 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/Credential.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/Credential.java @@ -17,11 +17,11 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.exception.BadRequestException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpStatus; import org.apache.http.util.TextUtils; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.exception.BadRequestException; public class Credential { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceCompliance.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceCompliance.java index 5b6cd49472..26ed612cc2 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceCompliance.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceCompliance.java @@ -17,8 +17,8 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; -import io.swagger.annotations.ApiModel; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.NonComplianceData; +import io.swagger.annotations.ApiModel; @ApiModel(value = "DeviceCompliance", description = "Device's policy compliance status") public class DeviceCompliance { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceConfig.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceConfig.java index 60b657a1f1..b373dc749d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceConfig.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceConfig.java @@ -17,10 +17,8 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; -import io.swagger.annotations.ApiModel; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; - -import java.util.List; +import io.swagger.annotations.ApiModel; @ApiModel(value = "DeviceConfig", description = "Device config") public class DeviceConfig { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceList.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceList.java index 7b3e084276..165605ae90 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceList.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceList.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModelProperty; import io.entgra.device.mgt.core.device.mgt.common.Device; +import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceToGroupsAssignment.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceToGroupsAssignment.java index ef70a0e371..4af0630d8e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceToGroupsAssignment.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceToGroupsAssignment.java @@ -18,9 +18,8 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModelProperty; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.BasePaginatedResult; +import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceTypeList.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceTypeList.java index 39a604fda1..a453dea045 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceTypeList.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/DeviceTypeList.java @@ -19,7 +19,6 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModelProperty; -import io.entgra.device.mgt.core.device.mgt.common.Device; import java.util.ArrayList; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/MetadataList.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/MetadataList.java index f69fcc259e..44e707212e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/MetadataList.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/MetadataList.java @@ -18,9 +18,9 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; import com.fasterxml.jackson.annotation.JsonProperty; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/NotificationList.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/NotificationList.java index 366733b8b0..05aed976f0 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/NotificationList.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/NotificationList.java @@ -18,9 +18,9 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; import com.fasterxml.jackson.annotation.JsonProperty; +import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.Notification; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.Notification; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/OperationList.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/OperationList.java index 54f41972e8..707cee812a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/OperationList.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/OperationList.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModelProperty; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; +import io.swagger.annotations.ApiModelProperty; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/OperationRequest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/OperationRequest.java index 8c9be6f0ed..606dfda252 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/OperationRequest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/OperationRequest.java @@ -17,9 +17,9 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/PermissionList.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/PermissionList.java index 06a938cd3f..86f849f8e4 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/PermissionList.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/PermissionList.java @@ -21,6 +21,7 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; + import java.io.Serializable; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/PolicyList.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/PolicyList.java index 0d98688257..ecf93f3b51 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/PolicyList.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/PolicyList.java @@ -18,9 +18,9 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; import com.fasterxml.jackson.annotation.JsonProperty; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/PolicyWrapper.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/PolicyWrapper.java index 206590fb0a..8db782b8c0 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/PolicyWrapper.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/PolicyWrapper.java @@ -18,11 +18,11 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.CorrectiveAction; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.DeviceGroupWrapper; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ProfileFeature.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ProfileFeature.java index 571619d591..99da050099 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ProfileFeature.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/ProfileFeature.java @@ -19,9 +19,9 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; import com.google.gson.Gson; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.CorrectiveAction; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.CorrectiveAction; import java.io.Serializable; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/RemoteSessionInfo.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/RemoteSessionInfo.java index 4c5400989a..ef6f71b989 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/RemoteSessionInfo.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/RemoteSessionInfo.java @@ -17,12 +17,8 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; -import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; - -import java.util.List; @ApiModel(value = "RemoteSessionInfo", description = "Template of the remote session") public class RemoteSessionInfo { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/RoleInfo.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/RoleInfo.java index 374efeb6e0..6269bcbcba 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/RoleInfo.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/RoleInfo.java @@ -22,8 +22,6 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.wso2.carbon.user.mgt.common.UIPermissionNode; -import java.util.List; - @ApiModel(value = "RoleInfo", description = "Role details including permission and the users in the roles are " + "wrapped here.") public class RoleInfo { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/TagInfo.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/TagInfo.java new file mode 100644 index 0000000000..33075f39d2 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/TagInfo.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel(value = "TagInfo", description = "Tag details including parameters associated with tags " + + "wrapped here.") +public class TagInfo { + + @ApiModelProperty(name = "name", value = "The name of the tag.", required = true) + private String name; + + @ApiModelProperty(name = "description", value = "Describes the behavior of the tag.", + required = false) + private String description; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/TagInfoList.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/TagInfoList.java new file mode 100644 index 0000000000..96015c7c6c --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/TagInfoList.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.List; + +@ApiModel(value = "TagInfoList") +public class TagInfoList extends BasePaginatedResult { + + private List tags; + + @ApiModelProperty(value = "Returns the list of tags that match the offset and limit parameter values " + + "that were specified.") + @JsonProperty("tags") + public List getList() { + return tags; + } + + public void setList(List tags) { + this.tags = tags; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("{\n"); + sb.append(" count: ").append(getCount()).append(",\n"); + sb.append(" tags: [").append(tags).append("\n"); + sb.append("]}\n"); + return sb.toString(); + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/TagMappingInfo.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/TagMappingInfo.java new file mode 100644 index 0000000000..ae5debb2e4 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/TagMappingInfo.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.List; + +@ApiModel(value = "TagMappingInfo", description = "Tag mapping details including parameters associated with " + + "device mapping wrapped here.") +public class TagMappingInfo { + + @ApiModelProperty(name = "deviceIdentifiers", value = "Defines the device identifiers.", required = true) + private List deviceIdentifiers; + + @ApiModelProperty(name = "deviceType", value = "Defines the device type.", required = true) + private String deviceType; + + @ApiModelProperty(name = "tags", value = "Defines the tags.", required = true) + private List tags; + + public List getDeviceIdentifiers() { + return deviceIdentifiers; + } + + public void setDeviceIdentifiers(List deviceIdentifiers) { + this.deviceIdentifiers = deviceIdentifiers; + } + + public String getDeviceType() { + return deviceType; + } + + public void setDeviceType(String deviceType) { + this.deviceType = deviceType; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/TagMappingInfoList.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/TagMappingInfoList.java new file mode 100644 index 0000000000..8ae856748e --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/TagMappingInfoList.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.List; + +@ApiModel(value = "TagMappingInfoList") +public class TagMappingInfoList extends BasePaginatedResult { + + private List tagMappings; + + @ApiModelProperty(value = "Returns the list of tag mappings that match the offset and " + + "limit parameter values that were specified.") + @JsonProperty("tagMappings") + public List getList() { + return tagMappings; + } + + public void setList(List tagMappings) { + this.tagMappings = tagMappings; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("{\n"); + sb.append(" count: ").append(getCount()).append(",\n"); + sb.append(" tagMappings: [").append(tagMappings).append("\n"); + sb.append("]}\n"); + return sb.toString(); + } + + +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/AdapterConfiguration.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/AdapterConfiguration.java index 0e2c2a564a..9df6824c8e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/AdapterConfiguration.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/AdapterConfiguration.java @@ -18,7 +18,7 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics; import io.swagger.annotations.ApiModelProperty; -import java.util.ArrayList; + import java.util.List; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/DeviceTypeEvent.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/DeviceTypeEvent.java index d527631e92..f5f9b72732 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/DeviceTypeEvent.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/DeviceTypeEvent.java @@ -20,8 +20,6 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModelProperty; -import java.util.List; - /** * This hold stats data record */ diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/EventAttributeList.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/EventAttributeList.java index 4fb2e3921d..26847a2153 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/EventAttributeList.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/EventAttributeList.java @@ -19,8 +19,6 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModelProperty; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.BasePaginatedResult; import java.util.ArrayList; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/EventRecords.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/EventRecords.java index 792e8de652..baa458392d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/EventRecords.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/EventRecords.java @@ -18,13 +18,12 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics; import com.fasterxml.jackson.annotation.JsonProperty; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.BasePaginatedResult; import io.swagger.annotations.ApiModelProperty; -import io.entgra.device.mgt.core.device.mgt.common.Device; +import org.wso2.carbon.analytics.datasource.commons.Record; import java.util.ArrayList; import java.util.List; -import org.wso2.carbon.analytics.datasource.commons.Record; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.BasePaginatedResult; /** * This hold stats data record diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/EventStream.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/EventStream.java index 2956fefaa8..b0012cb058 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/EventStream.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/analytics/EventStream.java @@ -19,7 +19,6 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics; import io.swagger.annotations.ApiModelProperty; -import java.util.ArrayList; import java.util.List; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/exception/GlobalThrowableMapper.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/exception/GlobalThrowableMapper.java index 3384123fac..33411f3748 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/exception/GlobalThrowableMapper.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/exception/GlobalThrowableMapper.java @@ -19,9 +19,9 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.exception; import com.google.gson.JsonParseException; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtUtil; import javax.naming.AuthenticationException; import javax.ws.rs.ClientErrorException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ActivityInfoProviderService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ActivityInfoProviderService.java index 27d855b3b1..9c9756241b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ActivityInfoProviderService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ActivityInfoProviderService.java @@ -17,35 +17,17 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ActivityList; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.common.ActivityIdList; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; +import io.swagger.annotations.*; -import javax.validation.Valid; import javax.validation.constraints.Size; -import javax.ws.rs.Consumes; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/AnalyticsArtifactsManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/AnalyticsArtifactsManagementService.java index 0b627554bb..f509284431 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/AnalyticsArtifactsManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/AnalyticsArtifactsManagementService.java @@ -17,7 +17,6 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api; -import io.swagger.annotations.ApiParam; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; @@ -25,25 +24,10 @@ import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.Adapter; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.EventStream; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.SiddhiExecutionPlan; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; +import io.swagger.annotations.*; import javax.validation.Valid; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ConfigurationManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ConfigurationManagementService.java index 164d85371e..5957783c3a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ConfigurationManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ConfigurationManagementService.java @@ -17,24 +17,12 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Info; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Extension; -import io.swagger.annotations.Tag; -import io.swagger.annotations.Api; -import io.swagger.annotations.AuthorizationScope; -import io.swagger.annotations.Authorization; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.ResponseHeader; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; -import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; +import io.swagger.annotations.*; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceAgentService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceAgentService.java index 5e43b5e274..1aee1b1b29 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceAgentService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceAgentService.java @@ -17,35 +17,17 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.OperationList; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.common.Device; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; +import io.swagger.annotations.*; import javax.validation.Valid; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceEventManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceEventManagementService.java index ab9bf2aa53..fd7258e3c0 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceEventManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceEventManagementService.java @@ -18,33 +18,15 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.DeviceTypeEvent; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.EventRecords; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.swagger.annotations.*; import javax.validation.Valid; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceManagementService.java index 5c41168bcb..8d9d05a570 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceManagementService.java @@ -18,20 +18,11 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.DisenrollRequest; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.*; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.DisenrollRequest; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.common.Feature; @@ -43,12 +34,17 @@ import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.NonComplianceData; import io.entgra.device.mgt.core.device.mgt.common.search.PropertyMap; import io.entgra.device.mgt.core.device.mgt.common.search.SearchContext; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ApplicationList; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceList; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.OperationRequest; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.OperationStatusBean; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Extension; +import io.swagger.annotations.ExtensionProperty; +import io.swagger.annotations.Info; +import io.swagger.annotations.ResponseHeader; +import io.swagger.annotations.SwaggerDefinition; +import io.swagger.annotations.Tag; import javax.validation.Valid; import javax.validation.constraints.Size; @@ -64,9 +60,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.sql.Timestamp; import java.util.List; -import java.util.Map; /** * Device related REST-API. This can be used to manipulated device related details. @@ -339,6 +333,12 @@ public interface DeviceManagementService { required = false) @QueryParam("requireDeviceInfo") boolean requireDeviceInfo, + @ApiParam( + name = "tag", + value = "Describes the tags associated with the enrolment", + required = false) + @QueryParam("tag") + List tags, @ApiParam( name = "offset", value = "The starting pagination index for the complete list of qualified items.", diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceTypeManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceTypeManagementService.java index 9236bb9790..7ad07f5c0c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceTypeManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceTypeManagementService.java @@ -18,33 +18,17 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; -import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; -import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceTypeList; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; +import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; +import io.swagger.annotations.*; import javax.validation.constraints.Size; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/GeoLocationBasedService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/GeoLocationBasedService.java index a0ff8dda0d..c5faaf1f1c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/GeoLocationBasedService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/GeoLocationBasedService.java @@ -18,36 +18,18 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; -import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.Alert; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.GeofenceWrapper; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; +import io.entgra.device.mgt.core.device.mgt.common.geo.service.Alert; +import io.swagger.annotations.*; import javax.validation.Valid; import javax.validation.constraints.Size; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/GroupManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/GroupManagementService.java index 36c85323c6..c302d15edf 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/GroupManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/GroupManagementService.java @@ -18,6 +18,17 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api; +import io.entgra.device.mgt.core.apimgt.annotations.Scope; +import io.entgra.device.mgt.core.apimgt.annotations.Scopes; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceGroupList; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceList; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceToGroupsAssignment; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.RoleList; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroupRoleWrapper; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @@ -30,17 +41,6 @@ import io.swagger.annotations.ResponseHeader; import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.Tag; import org.apache.axis2.transport.http.HTTPConstants; -import io.entgra.device.mgt.core.apimgt.annotations.Scope; -import io.entgra.device.mgt.core.apimgt.annotations.Scopes; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceGroupList; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceList; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceToGroupsAssignment; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.RoleList; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroupRoleWrapper; import javax.validation.Valid; import javax.ws.rs.Consumes; @@ -1349,11 +1349,11 @@ public interface GroupManagementService { "Server error occurred while creating the group or adding devices or sharing the group.", response = ErrorResponse.class) }) - Response createGroupWithRoles(@ApiParam( - name = "group", - value = "Define the group object with data.", - required = true) - @Valid DeviceGroupRoleWrapper group - ); - + Response createGroupWithRoles( + @ApiParam( + name = "group", + value = "Define the group object with data.", + required = true) + @Valid DeviceGroupRoleWrapper group + ); } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/MetadataService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/MetadataService.java index b8aca4c550..1fcdb4d0e8 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/MetadataService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/MetadataService.java @@ -18,35 +18,16 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; -import org.apache.axis2.transport.http.HTTPConstants; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.WhiteLabelThemeCreateRequest; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.MetadataList; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; +import io.swagger.annotations.*; +import org.apache.axis2.transport.http.HTTPConstants; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/NotificationManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/NotificationManagementService.java index 749791619f..c86153ecc3 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/NotificationManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/NotificationManagementService.java @@ -17,33 +17,16 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; -import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.Notification; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.NotificationList; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.Notification; +import io.swagger.annotations.*; import javax.validation.constraints.Size; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/PolicyManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/PolicyManagementService.java index 4abcf68617..3fe2f11770 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/PolicyManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/PolicyManagementService.java @@ -17,37 +17,19 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.PolicyWrapper; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.PriorityUpdatedPolicyWrapper; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ProfileFeature; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; +import io.swagger.annotations.*; import javax.validation.Valid; import javax.validation.constraints.Size; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/RemoteSessionService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/RemoteSessionService.java index 508c29100c..4df5b8c7e6 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/RemoteSessionService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/RemoteSessionService.java @@ -19,20 +19,10 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.swagger.annotations.*; import javax.validation.constraints.Size; import javax.ws.rs.GET; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ReportManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ReportManagementService.java index e22f938684..af7c103764 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ReportManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ReportManagementService.java @@ -17,37 +17,17 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api; -import com.google.gson.JsonObject; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.ReportManagementException; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceList; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.ReportManagementException; +import io.swagger.annotations.*; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; import java.util.List; @SwaggerDefinition( diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/RoleManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/RoleManagementService.java index 9be614674f..eedede200a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/RoleManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/RoleManagementService.java @@ -17,13 +17,13 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api; -import io.swagger.annotations.*; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.RoleInfo; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.RoleList; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.swagger.annotations.*; import org.wso2.carbon.user.mgt.common.UIPermissionNode; import javax.ws.rs.*; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/TagManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/TagManagementService.java new file mode 100644 index 0000000000..23fa92b9f8 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/TagManagementService.java @@ -0,0 +1,404 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api; + +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.TagInfo; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.TagInfoList; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.TagMappingInfo; +import io.swagger.annotations.*; +import io.entgra.device.mgt.core.apimgt.annotations.Scope; +import io.entgra.device.mgt.core.apimgt.annotations.Scopes; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.List; + +@SwaggerDefinition( + info = @Info( + version = "1.0.0", + title = "", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = "name", value = "TagManagement"), + @ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/tags"), + }) + } + ), + tags = { + @Tag(name = "device_management") + } +) +@Scopes( + scopes = { + @Scope( + name = "Getting the List of Tags", + description = "Getting the List of Tags", + key = "tm:tags:view", + roles = {"Internal/devicemgt-user"}, + permissions = {"/device-mgt/tags/view"} + ), + @Scope( + name = "Adding a new tag", + description = "Adding a new tag", + key = "tm:tags:create", + roles = {"Internal/devicemgt-user"}, + permissions = {"/device-mgt/tags/create"} + ), + @Scope( + name = "Updating a tag", + description = "Updating a tag", + key = "tm:tags:update", + roles = {"Internal/devicemgt-user"}, + permissions = {"/device-mgt/tags/update"} + ), + @Scope( + name = "Delete a tag", + description = "Delete a tag", + key = "tm:tags:delete", + roles = {"Internal/devicemgt-user"}, + permissions = {"/device-mgt/tags/delete"} + ), + @Scope( + name = "Adding a device tag mapping", + description = "Adding a device-tag mapping", + key = "tm:tags:mapping:create", + roles = {"Internal/devicemgt-user"}, + permissions = {"/device-mgt/tags/mapping/create"} + ), + @Scope( + name = "Deleting a device tag mapping", + description = "Deleting a device-tag mapping", + key = "tm:tags:mapping:delete", + roles = {"Internal/devicemgt-user"}, + permissions = {"/device-mgt/tags/mapping/delete"} + ), + @Scope( + name = "Getting the list of device tag mappings", + description = "Getting the list of device-tag mappings", + key = "tm:tags:mapping:view", + roles = {"Internal/devicemgt-user"}, + permissions = {"/device-mgt/tags/mapping/view"} + ) + } +) +@Path("/tags") +@Api(value = "Tag Management", description = "Tag management related operations can be found here.") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public interface TagManagementService { + + @GET + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting the List of Tags", + notes = "This endpoint is used to retrieve all tags", + tags = "Tag Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "tm:tags:view") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully fetched the list of tags.", + response = TagInfoList.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. \n Empty body because the client already has the latest version of the requested resource."), + @ApiResponse( + code = 406, + message = "Not Acceptable.\n The requested media type is not supported"), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while fetching list of roles.", + response = ErrorResponse.class) + }) + Response getTags(); + + @POST + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Adding a Tag", + notes = "This endpoint is used to add new tags", + tags = "Tag Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "tm:tags:create") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 201, + message = "Created. \n Successfully created the tag.", + responseHeaders = { + @ResponseHeader( + name = "Content-Location", + description = "The URL to the newly added tag."), + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests.")}), + @ApiResponse( + code = 303, + message = "See Other. \n The source can be retrieved from the URL specified in the location header.", + responseHeaders = { + @ResponseHeader( + name = "Content-Location", + description = "The Source URL of the document.")}), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 415, + message = "Unsupported media type. \n The format of the requested entity was not supported.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while adding a new tag.", + response = ErrorResponse.class) + }) + Response addTag( + @ApiParam( + name = "tag", + value = "The properties required to add a new tag.", + required = true) List tags); + + @PUT + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "PUT", + value = "Updating a Tag", + notes = "This endpoint is used to update a specific tag", + tags = "Tag Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "tm:tags:update") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully updated the tag.", + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body")}), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "Not Found. \n The specified tag does not exist.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while updating the tag.", + response = ErrorResponse.class) + }) + Response updateTag( + @ApiParam( + name = "tagId", + value = "The ID of the tag to be updated.", + required = false) @QueryParam("tagId") Integer tagId, + @ApiParam( + name = "tagName", + value = "The name of the tag to be updated.", + required = false) @QueryParam("tagName") String tagName, + @ApiParam( + name = "tagInfo", + value = "The properties required to update the tag.", + required = true) TagInfo tagInfo); + + @DELETE + @Path("/{tagId}") + @ApiOperation( + httpMethod = "DELETE", + value = "Deleting a Tag", + notes = "This endpoint is used to delete a specific tag", + tags = "Tag Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "tm:tags:delete") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 204, + message = "No Content. \n Successfully deleted the tag."), + @ApiResponse( + code = 404, + message = "Not Found. \n The specified tag does not exist.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while deleting the tag.", + response = ErrorResponse.class) + }) + Response deleteTag( + @ApiParam( + name = "tagId", + value = "The ID of the tag to be deleted.", + required = true) @PathParam("tagId") int tagId); + + @GET + @Path("/{tagId}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting a Tag by ID", + notes = "This endpoint is used to retrieve tag by id", + tags = "Tag Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "tm:tags:view") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully fetched the tag.", + response = Tag.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body")}), + @ApiResponse( + code = 404, + message = "Not Found. \n The specified tag does not exist.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while fetching the tag.", + response = ErrorResponse.class) + }) + Response getTagById( + @ApiParam( + name = "tagId", + value = "The ID of the tag to be fetched.", + required = true) @PathParam("tagId") int tagId); + + @POST + @Path("/mapping") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Adding a Device-Tag Mapping", + notes = "This endpoint is used to map devices with tags", + tags = "Device-Tag Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "tm:tags:mapping:create") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 201, + message = "Created. \n Successfully created the device-tag mapping.", + responseHeaders = { + @ResponseHeader( + name = "Content-Location", + description = "The URL to the newly added device-tag mapping."), + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body")}), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while adding the device-tag mapping.", + response = ErrorResponse.class) + }) + Response addDeviceTagMapping( + @ApiParam( + name = "deviceTagInfo", + value = "The properties required to add a new device-tag mapping.", + required = true) TagMappingInfo tagMappingInfo); + + @DELETE + @Path("/mapping") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "DELETE", + value = "Deleting a Device-Tag Mapping", + notes = "This endpoint is used to remove tag mappings from devices", + tags = "Device-Tag Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "tm:tags:mapping:delete") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 204, + message = "No Content. \n Successfully deleted the device-tag mapping."), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while deleting the device-tag mapping.", + response = ErrorResponse.class) + }) + Response deleteDeviceTagMapping( + @ApiParam( + name = "deviceTagInfo", + value = "The properties required to add a new device-tag mapping.", + required = true) TagMappingInfo tagMappingInfo); +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/UserManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/UserManagementService.java index 345198403a..6538913292 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/UserManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/UserManagementService.java @@ -32,8 +32,10 @@ import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.PermissionList; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.RoleList; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.UserInfo; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.UserStoreList; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.*; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; import io.entgra.device.mgt.core.device.mgt.common.invitation.mgt.DeviceEnrollmentInvitation; +import org.apache.axis2.transport.http.HTTPConstants; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/WhiteLabelService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/WhiteLabelService.java index 22544b9ff0..e6fd3e2c7a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/WhiteLabelService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/WhiteLabelService.java @@ -17,30 +17,17 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; -import io.swagger.annotations.ApiParam; -import org.apache.axis2.transport.http.HTTPConstants; + import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.WhiteLabelThemeCreateRequest; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.PathParam; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.WhiteLabelThemeCreateRequest; +import io.swagger.annotations.*; +import org.apache.axis2.transport.http.HTTPConstants; + +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/ApplicationManagementAdminService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/ApplicationManagementAdminService.java index 211390180f..9e7fa5a247 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/ApplicationManagementAdminService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/ApplicationManagementAdminService.java @@ -17,22 +17,13 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Info; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Extension; -import io.swagger.annotations.Tag; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ApplicationWrapper; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; +import io.swagger.annotations.*; import javax.ws.rs.Consumes; import javax.ws.rs.POST; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceAccessAuthorizationAdminService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceAccessAuthorizationAdminService.java index e26e5bb29f..a29604db1b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceAccessAuthorizationAdminService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceAccessAuthorizationAdminService.java @@ -17,21 +17,13 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; -import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAuthorizationResult; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.AuthorizationRequest; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAuthorizationResult; +import io.swagger.annotations.*; import javax.ws.rs.Consumes; import javax.ws.rs.POST; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceAnalyticsArtifactUploaderAdminService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceAnalyticsArtifactUploaderAdminService.java deleted file mode 100644 index 889714066e..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceAnalyticsArtifactUploaderAdminService.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin; - - -import io.swagger.annotations.*; -import io.entgra.device.mgt.core.apimgt.annotations.Scope; -import io.entgra.device.mgt.core.apimgt.annotations.Scopes; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; - -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Response; - -@SwaggerDefinition( - info = @Info( - version = "1.0.0", - title = "", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = "name", value = "DeviceAnalyticsArtifactUploaderAdminService"), - @ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/admin/publish-artifact"), - }) - } - ), - tags = { - @Tag(name = "device_management", description = "") - } -) -@Path("/admin/publish-artifact") -@Api(value = "Devicetype deployment Administrative Service", description = "This an API intended to be used to " + - "deploy device type components" + - "Further, this is strictly restricted to admin users only ") -@Scopes( - scopes = { - @Scope( - name = "Devicetype deployment", - description = "Deploy devicetype", - key = "dm:device-type:deploy", - roles = {"Internal/devicemgt-admin"}, - permissions = {"/device-mgt/devicetype/deploy"} - ) - } -) - -public interface DeviceAnalyticsArtifactUploaderAdminService { - - @POST - @Path("/deploy/{type}") - @ApiOperation( - httpMethod = "POST", - value = "Deploy device type\n", - notes = "This is an API that can be used to deploy existing device type artifact for tenant", - response = Response.class, - tags = "Devicetype Deployment Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "dm:device-type:deploy") - }) - }) - - @ApiResponses(value = { - @ApiResponse( - code = 201, - message = "OK. \n Successfully deployed the artifacts.", - response = Response.class), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error.", - response = ErrorResponse.class), - @ApiResponse( - code = 404, - message = "Not Found. \n The specified resource does not exist."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The entity of the request was in a not supported format."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n Server error occurred while checking the authorization" + - " for a specified set of devices.", - response = ErrorResponse.class) - }) - - Response doPublish( - @ApiParam(name = "type", - value = "The type of deployment." + - "INFO: Deploy artifact with given type.", - required = true) - @PathParam("type") String type); - -} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceManagementAdminService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceManagementAdminService.java index 21eae81189..13a63087a7 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceManagementAdminService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceManagementAdminService.java @@ -17,35 +17,17 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; -import org.apache.axis2.transport.http.HTTPConstants; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; -import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceList; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.common.Device; +import io.swagger.annotations.*; +import org.apache.axis2.transport.http.HTTPConstants; import javax.validation.constraints.Size; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.sql.Timestamp; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceTypeManagementAdminService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceTypeManagementAdminService.java index 55122c2bd0..f0e67a5755 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceTypeManagementAdminService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/DeviceTypeManagementAdminService.java @@ -17,35 +17,18 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; -import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; -import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceTypeList; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceTypeVersionWrapper; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; +import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; +import io.swagger.annotations.*; import javax.validation.constraints.Size; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/GroupManagementAdminService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/GroupManagementAdminService.java index 7801afb3e3..6d69127405 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/GroupManagementAdminService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/GroupManagementAdminService.java @@ -18,6 +18,13 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin; +import io.entgra.device.mgt.core.apimgt.annotations.Scope; +import io.entgra.device.mgt.core.apimgt.annotations.Scopes; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceGroupList; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroupRoleWrapper; import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.Info; import io.swagger.annotations.ExtensionProperty; @@ -30,15 +37,8 @@ import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ResponseHeader; import org.apache.axis2.transport.http.HTTPConstants; -import io.entgra.device.mgt.core.apimgt.annotations.Scope; -import io.entgra.device.mgt.core.apimgt.annotations.Scopes; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceGroupList; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroupRoleWrapper; -import javax.validation.Valid; +import javax.validation.Valid; import javax.ws.rs.Consumes; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/UserManagementAdminService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/UserManagementAdminService.java index 08b51ac9c4..9721fe67bc 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/UserManagementAdminService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/UserManagementAdminService.java @@ -17,14 +17,14 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin; -import io.swagger.annotations.*; -import org.apache.axis2.transport.http.HTTPConstants; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; -import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.PasswordResetWrapper; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.common.Device; +import io.swagger.annotations.*; +import org.apache.axis2.transport.http.HTTPConstants; import javax.validation.constraints.Size; import javax.ws.rs.*; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ActivityProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ActivityProviderServiceImpl.java index bcfdb69aac..5e5ba9d033 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ActivityProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ActivityProviderServiceImpl.java @@ -38,14 +38,7 @@ import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.user.api.UserStoreException; import javax.validation.constraints.Size; -import javax.ws.rs.Consumes; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.text.ParseException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/AnalyticsArtifactsManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/AnalyticsArtifactsManagementServiceImpl.java index 5be79177af..24f8705876 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/AnalyticsArtifactsManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/AnalyticsArtifactsManagementServiceImpl.java @@ -17,23 +17,18 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.Attribute; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.AdapterMappingConfiguration; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.MappingProperty; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.AdapterConfiguration; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.AdapterProperty; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.MessageFormat; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.SiddhiExecutionPlan; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.exception.ArtifactAlreadyExistsException; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.*; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.exception.BadRequestException; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.exception.ErrorDTO; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.exception.InvalidExecutionPlanException; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.exception.NotFoundException; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.exception.*; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.AnalyticsArtifactsManagementService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.Adapter; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.EventStream; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; +import org.apache.axis2.AxisFault; +import org.apache.axis2.client.Stub; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.event.processor.stub.EventProcessorAdminServiceStub; import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceStub; import org.wso2.carbon.event.publisher.stub.types.BasicOutputAdapterPropertyDto; @@ -45,20 +40,10 @@ import org.wso2.carbon.event.receiver.stub.types.EventReceiverConfigurationDto; import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub; import org.wso2.carbon.event.stream.stub.types.EventStreamAttributeDto; import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto; -import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.user.api.UserStoreException; -import org.apache.axis2.AxisFault; -import org.apache.axis2.client.Stub; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - import javax.validation.Valid; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.Response; import java.rmi.RemoteException; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ConfigurationServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ConfigurationServiceImpl.java index 6a3770322e..51c69da4b0 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ConfigurationServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ConfigurationServiceImpl.java @@ -17,22 +17,19 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationEntry; -import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationManagementException; -import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; -import io.entgra.device.mgt.core.device.mgt.core.config.ui.UIConfiguration; -import io.entgra.device.mgt.core.device.mgt.core.config.ui.UIConfigurationManager; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.ConfigurationManagementService; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.common.MDMAppConstants; +import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationEntry; +import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationManagementException; +import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagerUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; -import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.PUT; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceAgentServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceAgentServiceImpl.java index 4231ecc41e..9f89b7f0cd 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceAgentServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceAgentServiceImpl.java @@ -21,6 +21,13 @@ import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonParser; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.OperationList; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.Attribute; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.AttributeType; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.EventAttributeList; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.DeviceAgentService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; import org.apache.axis2.AxisFault; import org.apache.commons.logging.Log; @@ -38,29 +45,20 @@ import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManage import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.ComplianceFeature; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.OperationList; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.Attribute; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.AttributeType; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.EventAttributeList; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.DeviceAgentService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; -import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub; -import org.wso2.carbon.event.stream.stub.types.EventStreamAttributeDto; -import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto; import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; import io.entgra.device.mgt.core.policy.mgt.common.PolicyAdministratorPoint; import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub; +import org.wso2.carbon.event.stream.stub.types.EventStreamAttributeDto; +import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto; import org.wso2.carbon.user.api.UserStoreException; import javax.validation.Valid; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.Response; import java.rmi.RemoteException; import java.util.ArrayList; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceEventManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceEventManagementServiceImpl.java index f7f812715d..277be7b9f8 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceEventManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceEventManagementServiceImpl.java @@ -20,9 +20,15 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; import io.entgra.device.mgt.core.apimgt.analytics.extension.AnalyticsArtifactsDeployer; import io.entgra.device.mgt.core.apimgt.analytics.extension.dto.*; -import io.entgra.device.mgt.core.apimgt.analytics.extension.exception.EventReceiverDeployerException; import io.entgra.device.mgt.core.apimgt.analytics.extension.exception.EventPublisherDeployerException; +import io.entgra.device.mgt.core.apimgt.analytics.extension.exception.EventReceiverDeployerException; import io.entgra.device.mgt.core.apimgt.analytics.extension.exception.EventStreamDeployerException; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.*; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.DeviceEventManagementService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; import org.apache.axis2.AxisFault; import org.apache.axis2.client.Stub; import org.apache.commons.lang.StringUtils; @@ -32,15 +38,6 @@ import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.databridge.commons.StreamDefinition; import org.wso2.carbon.databridge.commons.exception.MalformedStreamDefinitionException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.Attribute; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.AttributeType; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.DeviceTypeEvent; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.EventAttributeList; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.TransportType; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.DeviceEventManagementService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.event.input.adapter.core.InputEventAdapterConfiguration; import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration; import org.wso2.carbon.event.publisher.core.EventPublisherService; @@ -64,7 +61,6 @@ import org.wso2.carbon.event.stream.core.exception.EventStreamConfigurationExcep import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub; import org.wso2.carbon.event.stream.stub.types.EventStreamAttributeDto; import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto; -import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.user.api.UserStoreException; import javax.validation.Valid; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImpl.java index 88cfe125ca..afaab6c01d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -19,6 +19,22 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService; +import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderServiceImpl; +import io.entgra.device.mgt.core.apimgt.application.extension.dto.ApiApplicationKey; +import io.entgra.device.mgt.core.apimgt.application.extension.exception.APIManagerException; +import io.entgra.device.mgt.core.apimgt.application.extension.internal.APIApplicationManagerExtensionDataHolder; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServicesImpl; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.DCRResponse; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenRequest; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenResponse; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtException; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtServiceImpl; import io.entgra.device.mgt.core.application.mgt.common.ApplicationInstallResponse; import io.entgra.device.mgt.core.application.mgt.common.SubscriptionType; import io.entgra.device.mgt.core.application.mgt.common.exception.SubscriptionManagementException; @@ -27,20 +43,22 @@ import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionMan import io.entgra.device.mgt.core.application.mgt.core.util.HelperUtil; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.DisenrollRequest; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtUtil; +import io.entgra.device.mgt.core.device.mgt.common.Device; +import io.entgra.device.mgt.core.device.mgt.common.DeviceFilters; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; +import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; +import io.entgra.device.mgt.core.device.mgt.common.Feature; +import io.entgra.device.mgt.core.device.mgt.common.FeatureManager; +import io.entgra.device.mgt.core.device.mgt.common.MDMAppConstants; +import io.entgra.device.mgt.core.device.mgt.common.OperationLogFilters; +import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; +import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.DCRResponse; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenRequest; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenResponse; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtException; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtServiceImpl; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.*; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.Application; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ApplicationManagementException; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.MobileAppTypes; @@ -90,12 +108,23 @@ import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClie import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import javax.validation.Valid; import javax.validation.constraints.Size; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import java.io.IOException; import java.text.ParseException; @@ -151,6 +180,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @QueryParam("since") String since, @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("requireDeviceInfo") boolean requireDeviceInfo, + @QueryParam("tag") List tags, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { try { @@ -226,6 +256,10 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.OK).entity(devices).build(); } + if (tags != null && !tags.isEmpty()) { + request.setTags(tags); + } + // this is the user who initiates the request String authorizedUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); if (groupId != 0) { @@ -928,10 +962,45 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { KeyMgtService keyMgtService = new KeyMgtServiceImpl(); try { - DCRResponse dcrResponse = keyMgtService.dynamicClientRegistration(applicationName, username, - "client_credentials", null, new String[] {"device_management"}, false, validityTime); - deviceConfig.setClientId(dcrResponse.getClientId()); - deviceConfig.setClientSecret(dcrResponse.getClientSecret()); + ApiApplicationKey apiApplicationKey; + try { + APIApplicationServices apiApplicationServices = DeviceMgtAPIUtils.getApiApplicationServices(); + APIApplicationKey adminDCRResponse = apiApplicationServices.createAndRetrieveApplicationCredentials( + "ClientForJWTTokenGeneration", + "client_credentials password refresh_token urn:ietf:params:oauth:grant-type:jwt-bearer" + ); + + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + JWTClientManagerService jwtClientManagerService = (JWTClientManagerService) ctx. + getOSGiService(JWTClientManagerService.class, null); + JWTClient jwtClient = jwtClientManagerService.getJWTClient(); + AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(adminDCRResponse.getClientId(), + adminDCRResponse.getClientSecret(), + username, "appm:subscribe apim:admin apim:api_key apim:app_import_export apim:app_manage" + + " apim:store_settings apim:sub_alert_manage apim:sub_manage apim:subscribe openid perm:device:enroll " + + "perm:devices:details perm:devices:features perm:devices:search perm:devices:view perm:groups:groups " + + "perm:users:send-invitation"); + + APIManagementProviderService apiManagementProviderService = DeviceMgtAPIUtils.getAPIManagementService(); + apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(applicationName, + new String[] {"device_management"}, "PRODUCTION", null, false, String.valueOf(validityTime), + null, accessTokenInfo.getAccessToken(), null, null,true); + + } catch (JWTClientException e) { + String msg = "Error while generating an application tokens for Tenant Admin."; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } catch (APIServicesException e) { + String msg = "Error while generating api Application"; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } + + //todo call REST APIs + deviceConfig.setClientId(apiApplicationKey.getConsumerKey()); + deviceConfig.setClientSecret(apiApplicationKey.getConsumerSecret()); StringBuilder scopes = new StringBuilder("device:" + type.replace(" ", "") + ":" + id); for (String topic : mqttEventTopicStructure) { @@ -949,7 +1018,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { // add scopes for update operation /tenantDomain/deviceType/deviceId/update/operation scopes.append(" perm:topic:pub:" + tenantDomain + ":" + type + ":" + id + ":update:operation"); - TokenRequest tokenRequest = new TokenRequest(dcrResponse.getClientId(), dcrResponse.getClientSecret(), + TokenRequest tokenRequest = new TokenRequest(apiApplicationKey.getConsumerKey(), + apiApplicationKey.getConsumerSecret(), null, scopes.toString(), "client_credentials", null, null, null, null, validityTime); TokenResponse tokenResponse = keyMgtService.generateAccessToken(tokenRequest); @@ -979,6 +1049,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } catch (APIManagerException e) { + String msg = "Error while calling rest Call for application key generation"; + log.error(msg, e); } return Response.status(Response.Status.OK).entity(deviceConfig).build(); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceStatusFilterServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceStatusFilterServiceImpl.java index 7e5fd01437..cc2a2c90e9 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceStatusFilterServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceStatusFilterServiceImpl.java @@ -20,13 +20,20 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.DeviceStatusFilterService; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataKeyNotFoundException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.DeviceStatusManagementService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; @@ -42,15 +49,14 @@ public class DeviceStatusFilterServiceImpl implements DeviceStatusFilterService @GET @Path("/{deviceType}") public Response getDeviceStatusFilters(@PathParam("deviceType") String deviceType) { - List result; - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); try { DeviceStatusManagementService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceStatusManagmentService(); - result = deviceManagementProviderService.getDeviceStatusFilters(deviceType, tenantId); - if (result != null) { - return Response.status(Response.Status.OK).entity(result).build(); - } - return Response.status(Response.Status.NO_CONTENT).entity(false).build(); + return Response.status(Response.Status.OK).entity(deviceManagementProviderService + .getDeviceStatusFilters(deviceType, CarbonContext.getThreadLocalCarbonContext().getTenantId())).build(); + } catch (MetadataKeyNotFoundException e) { + String msg = "Couldn't find the device status filter details for device type: " + deviceType; + log.error(msg, e); + return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); } catch (MetadataManagementException e) { String msg = "Error occurred while getting device status filter of the tenant."; log.error(msg, e); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceTypeManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceTypeManagementServiceImpl.java index 127c5be203..0d22af9937 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceTypeManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceTypeManagementServiceImpl.java @@ -18,31 +18,27 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceTypeNotFoundException; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.DeviceTypeManagementService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.InputValidationException; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.common.Feature; import io.entgra.device.mgt.core.device.mgt.common.FeatureManager; +import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceTypeNotFoundException; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationConfig; import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.DeviceTypeManagementService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.InputValidationException; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.validation.constraints.Size; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GeoLocationBasedServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GeoLocationBasedServiceImpl.java index 837e9ea9e7..21fdb282df 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GeoLocationBasedServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GeoLocationBasedServiceImpl.java @@ -22,44 +22,6 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.google.gson.Gson; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpStatus; -import org.wso2.carbon.analytics.api.AnalyticsDataAPI; -import org.wso2.carbon.analytics.api.AnalyticsDataAPIUtil; -//import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse; -//import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry; -//import org.wso2.carbon.analytics.dataservice.commons.SortByField; -//import org.wso2.carbon.analytics.dataservice.commons.SortType; -//import org.wso2.carbon.analytics.datasource.commons.Record; -//import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; -import org.wso2.carbon.context.CarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; -import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants.GeoServices; -import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; -import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; -import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; -import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationException; -import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfig; -import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfigurationException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.Alert; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.AlertAlreadyExistException; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.Event; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoCluster; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoCoordinate; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoFence; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoLocationBasedServiceException; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoLocationProviderService; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoQuery; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeofenceData; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroupConstants; -import io.entgra.device.mgt.core.device.mgt.core.geo.geoHash.geoHashStrategy.GeoHashLengthStrategy; -import io.entgra.device.mgt.core.device.mgt.core.geo.geoHash.geoHashStrategy.ZoomGeoHashLengthStrategy; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.EventAction; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.GeofenceWrapper; @@ -70,27 +32,31 @@ import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestV import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtUtil; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import io.entgra.device.mgt.core.device.mgt.common.*; +import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants.GeoServices; +import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationException; +import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfig; +import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfigurationException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.common.geo.service.*; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroupConstants; +import io.entgra.device.mgt.core.device.mgt.core.geo.geoHash.geoHashStrategy.GeoHashLengthStrategy; +import io.entgra.device.mgt.core.device.mgt.core.geo.geoHash.geoHashStrategy.ZoomGeoHashLengthStrategy; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpStatus; +import org.wso2.carbon.analytics.api.AnalyticsDataAPI; + +import javax.ws.rs.*; import javax.ws.rs.core.Response; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; -import java.util.HashMap; import java.util.List; -import java.util.Map; /** * The api for diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GroupManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GroupManagementServiceImpl.java index e8c56680b1..7681176ecc 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GroupManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GroupManagementServiceImpl.java @@ -33,6 +33,13 @@ import io.entgra.device.mgt.core.notification.logger.impl.EntgraGroupMgtLoggerIm import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceGroupList; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceList; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceToGroupsAssignment; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.RoleList; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.GroupManagementService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; @@ -40,17 +47,16 @@ import io.entgra.device.mgt.core.device.mgt.common.GroupPaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceNotFoundException; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.*; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceGroupList; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceList; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceToGroupsAssignment; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.RoleList; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.GroupManagementService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.policy.mgt.common.PolicyAdministratorPoint; import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.CarbonConstants; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/MetadataServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/MetadataServiceImpl.java index fcb864c3cc..2e2999bbda 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/MetadataServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/MetadataServiceImpl.java @@ -18,42 +18,25 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; -import org.apache.commons.io.IOUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.MetadataList; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.MetadataService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataKeyAlreadyExistsException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataKeyNotFoundException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.NotFoundException; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.WhiteLabelTheme; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.WhiteLabelThemeCreateRequest; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.MetadataList; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.MetadataService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import java.util.List; /** * This is the service class for metadata management. @@ -162,21 +145,4 @@ public class MetadataServiceImpl implements MetadataService { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } - - /** - * Useful to send files as application/octet-stream responses - */ - private Response sendFileStream(byte[] content) throws IOException { - try (ByteArrayInputStream binaryDuplicate = new ByteArrayInputStream(content)) { - Response.ResponseBuilder response = Response - .ok(binaryDuplicate, MediaType.APPLICATION_OCTET_STREAM); - response.status(Response.Status.OK); - response.header("Content-Length", content.length); - return response.build(); - } catch (IOException e) { - String msg = "Error occurred while creating input stream from buffer array. "; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/NotificationManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/NotificationManagementServiceImpl.java index cfcf8f7d82..2880e91cb0 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/NotificationManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/NotificationManagementServiceImpl.java @@ -17,28 +17,21 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; -import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; -import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.Notification; -import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.NotificationManagementException; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.NotificationList; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.NotificationManagementService; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; +import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; +import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.Notification; +import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.NotificationManagementException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; import javax.validation.constraints.Size; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/PolicyManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/PolicyManagementServiceImpl.java index d882018073..75640d3223 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/PolicyManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/PolicyManagementServiceImpl.java @@ -34,15 +34,26 @@ import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.PolicyList; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.PolicyWrapper; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.PriorityUpdatedPolicyWrapper; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ProfileFeature; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.*; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.PolicyManagementService; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.FilteringUtil; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtUtil; +import io.entgra.device.mgt.core.device.mgt.common.Device; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; +import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationException; +import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationService; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; +import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import io.entgra.device.mgt.core.policy.mgt.common.PolicyAdministratorPoint; import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import javax.validation.Valid; import javax.ws.rs.*; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/RemoteSessionServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/RemoteSessionServiceImpl.java index 3928123029..3db3061101 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/RemoteSessionServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/RemoteSessionServiceImpl.java @@ -18,19 +18,15 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.RemoteSessionInfo; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.RemoteSessionService; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; import io.entgra.device.mgt.core.device.mgt.core.config.remote.session.RemoteSessionConfiguration; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.RemoteSessionInfo; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.RemoteSessionService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; -import javax.ws.rs.Consumes; -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.Response; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ReportManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ReportManagementServiceImpl.java index 8a143a66ae..3cb2aa1b20 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ReportManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ReportManagementServiceImpl.java @@ -19,30 +19,24 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; import com.google.gson.JsonObject; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceList; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.ReportManagementService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; +import io.entgra.device.mgt.core.device.mgt.common.ReportFiltersList; import io.entgra.device.mgt.core.device.mgt.common.exceptions.BadRequestException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceTypeNotFoundException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.ReportManagementException; import io.entgra.device.mgt.core.device.mgt.core.report.mgt.Constants; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceList; -import io.entgra.device.mgt.core.device.mgt.common.ReportFiltersList; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.ReportManagementService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; -import javax.ws.rs.Consumes; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/RoleManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/RoleManagementServiceImpl.java index d4c00504c7..88cb718117 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/RoleManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/RoleManagementServiceImpl.java @@ -19,6 +19,7 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; import com.google.gson.Gson; import io.entgra.device.mgt.core.apimgt.webapp.publisher.exception.APIManagerPublisherException; +import com.google.common.base.Strings; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupManagementException; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; @@ -42,13 +43,32 @@ import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.SetReferenceTransformer; import org.wso2.carbon.user.api.*; +import org.springframework.util.StringUtils; +import org.wso2.carbon.context.RegistryType; +import org.wso2.carbon.registry.api.Registry; +import org.wso2.carbon.registry.core.session.UserRegistry; +import org.wso2.carbon.registry.resource.services.utils.ChangeRolePermissionsUtil; +import org.wso2.carbon.user.api.AuthorizationManager; +import org.wso2.carbon.user.api.Permission; +import org.wso2.carbon.user.api.UserRealm; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.core.common.AbstractUserStoreManager; import org.wso2.carbon.user.core.constants.UserCoreErrorConstants.ErrorMessages; import org.wso2.carbon.user.mgt.UserRealmProxy; import org.wso2.carbon.user.mgt.common.UIPermissionNode; import org.wso2.carbon.user.mgt.common.UserAdminException; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.UnsupportedEncodingException; @@ -60,6 +80,7 @@ import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.Optional; import static io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants.PRIMARY_USER_STORE; @@ -124,7 +145,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { if (limit == 0){ limit = Constants.DEFAULT_PAGE_LIMIT; } - if (domain != null && !domain.isEmpty()) { + if (!Strings.isNullOrEmpty(domain)) { username = domain + '/' + username; } Metadata metadata; @@ -140,7 +161,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { decision = (boolean) jsonObject.get(Constants.IS_USER_ABLE_TO_VIEW_ALL_ROLES); } if (decision) { - if (userStore == null || "".equals(userStore)){ + if (Strings.isNullOrEmpty(userStore)){ userStore = PRIMARY_USER_STORE; } try { @@ -406,6 +427,16 @@ public class RoleManagementServiceImpl implements RoleManagementService { public Response addRole(RoleInfo roleInfo) { RequestValidationUtil.validateRoleDetails(roleInfo); RequestValidationUtil.validateRoleName(roleInfo.getRoleName()); + + String role; + String[] roles = roleInfo.getRoleName().split("/"); + + if (roles.length > 1) { + role = roleInfo.getRoleName().split("/")[1]; + } else { + role = roleInfo.getRoleName().split("/")[0]; + } + try { String tenantId = String.valueOf(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); String tenantDomain = String.valueOf(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()); @@ -437,11 +468,11 @@ public class RoleManagementServiceImpl implements RoleManagementService { } String stringUsers = new Gson().toJson(roleInfo.getUsers()); log.info( - "Role " + roleInfo.getRoleName().split("/")[1] + " created", + "Role " + role + " created", roleMgtContextBuilder .setActionTag("ADD_ROLE") .setUserStoreDomain(roleInfo.getRoleName().split("/")[0]) - .setRoleName(roleInfo.getRoleName().split("/")[1]) + .setRoleName(role) .setUsers(stringUsers) .setTenantID(tenantId) .setTenantDomain(tenantDomain) @@ -460,8 +491,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { errorCode = e.getMessage().split("-")[0].trim(); } if (ErrorMessages.ERROR_CODE_ROLE_ALREADY_EXISTS.getCode().equals(errorCode)) { - String roleName = roleInfo.getRoleName().split("/")[1]; - String msg = "Role already exists with name : " + roleName + ". Try with another role name."; + String msg = "Role already exists with name : " + role + ". Try with another role name."; log.warn(msg); return Response.status(Response.Status.CONFLICT).entity(msg).build(); } else { @@ -572,7 +602,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { if (newRoleName != null && !roleName.equals(newRoleName)) { userStoreManager.updateRoleName(roleName, newRoleName); } - + if (roleInfo.getUsers() != null) { SetReferenceTransformer transformer = new SetReferenceTransformer<>(); transformer.transform(Arrays.asList(userStoreManager.getUserListOfRole(newRoleName)), @@ -592,12 +622,22 @@ public class RoleManagementServiceImpl implements RoleManagementService { updatePermissions(roleDetails[roleDetails.length - 1], roleInfo, userRealm); } String stringUsers = new Gson().toJson(stringUserList); + + String role; + String[] roles = roleInfo.getRoleName().split("/"); + + if (roles.length > 1) { + role = roleInfo.getRoleName().split("/")[1]; + } else { + role = roleInfo.getRoleName().split("/")[0]; + } + log.info( - "Role " + roleInfo.getRoleName().split("/")[1] + " updated", + "Role " + role + " updated", roleMgtContextBuilder .setActionTag("UPDATE_ROLE") .setUserStoreDomain(roleInfo.getRoleName().split("/")[0]) - .setRoleName(roleInfo.getRoleName().split("/")[1]) + .setRoleName(role) .setUsers(stringUsers) .setTenantID(tenantId) .setTenantDomain(tenantDomain) @@ -654,12 +694,21 @@ public class RoleManagementServiceImpl implements RoleManagementService { log.debug("Deleting the role in user store"); } DeviceMgtAPIUtils.getGroupManagementProviderService().deleteRoleAndRoleGroupMapping(roleName, roleToDelete, tenantId, userStoreManager, authorizationManager); + String role; + String[] roles = roleName.split("/"); + + if (roles.length > 1) { + role = roleName.split("/")[1]; + } else { + role = roleName.split("/")[0]; + } + log.info( - "Role " + roleName.split("/")[1] + " deleted", + "Role " + role + " deleted", roleMgtContextBuilder .setActionTag("DELETE_ROLE") .setUserStoreDomain(userStoreName) - .setRoleName(roleName.split("/")[1]) + .setRoleName(role) .setTenantID(String.valueOf(tenantId)) .setTenantDomain(tenantDomain) .setUserName(userName) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/TagManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/TagManagementServiceImpl.java new file mode 100644 index 0000000000..c780c4226b --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/TagManagementServiceImpl.java @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; + +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.TagInfo; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.TagMappingInfo; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.TagManagementService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.BadRequestException; +import io.entgra.device.mgt.core.device.mgt.common.tag.mgt.Tag; +import io.entgra.device.mgt.core.device.mgt.common.tag.mgt.TagManagementException; +import io.entgra.device.mgt.core.device.mgt.common.tag.mgt.TagNotFoundException; +import io.entgra.device.mgt.core.device.mgt.extensions.logger.spi.EntgraLogger; +import io.entgra.device.mgt.core.notification.logger.impl.EntgraRoleMgtLoggerImpl; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; + +@Path("/tags") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class TagManagementServiceImpl implements TagManagementService { + + private static final EntgraLogger log = new EntgraRoleMgtLoggerImpl(TagManagementServiceImpl.class); + + @GET + @Override + public Response getTags() { + try { + List tags = DeviceMgtAPIUtils.getTagManagementService().getAllTags(); + return Response.status(Response.Status.OK).entity(tags).build(); + } catch (TagManagementException e) { + String msg = "Error occurred while getting tags."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } + } + + @POST + @Override + public Response addTag(List tagInfoList) { + RequestValidationUtil.validateTagListDetails(tagInfoList); + try { + List tags = new ArrayList<>(); + for (TagInfo tagInfo : tagInfoList) { + Tag tag = new Tag(tagInfo.getName(), tagInfo.getDescription()); + tags.add(tag); + } + DeviceMgtAPIUtils.getTagManagementService().addTags(tags); + return Response.status(Response.Status.CREATED).entity(tagInfoList).build(); + } catch (TagManagementException e) { + String msg = "Error occurred while adding tags." ; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity + (new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } catch (BadRequestException e) { + String msg = "Error occurred while adding tags. Please check the request" ; + if(log.isDebugEnabled()) { + log.debug(msg, e); + } + return Response.status(Response.Status.BAD_REQUEST).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(e.getMessage()).build()).build(); + } + } + + @PUT + @Override + public Response updateTag(@QueryParam("tagId") Integer tagId, @QueryParam("tagName") String tagName, TagInfo tagInfo) { + RequestValidationUtil.validateTagDetails(tagId, tagName, tagInfo); + try { + Tag tag; + if (tagId != null) { + tag = DeviceMgtAPIUtils.getTagManagementService().getTagById(tagId); + } else { + tag = DeviceMgtAPIUtils.getTagManagementService().getTagByName(tagName); + } + if (tag == null) { + String msg = (tagId != null) ? "Tag with ID " + tagId + " is not found." + : "Tag with name " + tagName + " is not found."; + log.error(msg); + return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponse.ErrorResponseBuilder(). + setMessage(msg).build()).build(); + } + tag.setName(tagInfo.getName()); + tag.setDescription(tagInfo.getDescription()); + DeviceMgtAPIUtils.getTagManagementService().updateTag(tag); + return Response.status(Response.Status.OK).entity(tag).build(); + } catch (TagManagementException e) { + String msg = (tagId != null) ? "Error occurred while updating tag with ID " + tagId + "." + : "Error occurred while updating tag with name " + tagName + "."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new ErrorResponse. + ErrorResponseBuilder().setMessage(msg).build()).build(); + } catch (TagNotFoundException e) { + String msg = (tagId != null) ? "Tag with ID " + tagId + " is not found." + : "Tag with name " + tagName + " is not found."; + log.error(msg, e); + return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponse.ErrorResponseBuilder(). + setMessage(msg).build()).build(); + } catch (BadRequestException e) { + String msg = (tagId != null) ? "Error occurred while updating tag with ID " + tagId + : "Error occurred while updating tag with name " + tagName; + if(log.isDebugEnabled()) { + log.debug(msg, e); + } + return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponse.ErrorResponseBuilder(). + setMessage(e.getMessage()).build()).build(); + } + } + + @DELETE + @Path("/{tagId}") + @Override + public Response deleteTag(@PathParam("tagId") int tagId) { + try { + DeviceMgtAPIUtils.getTagManagementService().deleteTag(tagId); + return Response.status(Response.Status.NO_CONTENT).build(); + } catch (TagManagementException e) { + String msg = "Error occurred while deleting tag with ID " + tagId + "."; + log.error(msg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponse.ErrorResponseBuilder(). + setMessage(msg).build()).build(); + } catch (TagNotFoundException e) { + String msg = "Tag with ID " + tagId + " is not found."; + log.error(msg, e); + return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponse.ErrorResponseBuilder(). + setMessage(e.getMessage()).build()).build(); + } + } + + @GET + @Path("/{tagId}") + @Override + public Response getTagById(@PathParam("tagId") int tagId) { + try { + Tag tag = DeviceMgtAPIUtils.getTagManagementService().getTagById(tagId); + return Response.status(Response.Status.OK).entity(tag).build(); + } catch (TagManagementException e) { + String msg = "Error occurred while getting tag with ID " + tagId + "."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new ErrorResponse. + ErrorResponseBuilder().setMessage(msg).build()).build(); + } catch (TagNotFoundException e) { + String msg = "Tag with ID " + tagId + " is not found."; + log.error(msg, e); + return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponse. + ErrorResponseBuilder().setMessage(e.getMessage()).build()).build(); + } + } + + @POST + @Path("/mapping") + public Response addDeviceTagMapping(TagMappingInfo tagMappingInfo) { + RequestValidationUtil.validateTagMappingDetails(tagMappingInfo); + try { + DeviceMgtAPIUtils.getTagManagementService().addDeviceTagMapping(tagMappingInfo.getDeviceIdentifiers(), + tagMappingInfo.getDeviceType(), tagMappingInfo.getTags()); + return Response.status(Response.Status.CREATED).entity(tagMappingInfo).build(); + } catch (TagManagementException e) { + String msg = "Error occurred while adding device-tag mapping."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new ErrorResponse. + ErrorResponseBuilder().setMessage(msg).build()).build(); + } catch (BadRequestException e) { + String msg = "Error occurred while adding tag mappings."; + if(log.isDebugEnabled()) { + log.debug(msg, e); + } + return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponse. + ErrorResponseBuilder().setMessage(e.getMessage()).build()).build(); + } + } + + @DELETE + @Path("/mapping") + public Response deleteDeviceTagMapping(TagMappingInfo tagMappingInfo) { + RequestValidationUtil.validateTagMappingDetails(tagMappingInfo); + try { + DeviceMgtAPIUtils.getTagManagementService().deleteDeviceTagMapping(tagMappingInfo.getDeviceIdentifiers(), + tagMappingInfo.getDeviceType(), tagMappingInfo.getTags()); + return Response.status(Response.Status.NO_CONTENT).entity(tagMappingInfo).build(); + } catch (TagManagementException e) { + String msg = "Error occurred while deleting tag mappings."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new ErrorResponse. + ErrorResponseBuilder().setMessage(msg).build()).build(); + } catch (BadRequestException e) { + String msg = "Error occurred while deleting tag mappings."; + if(log.isDebugEnabled()) { + log.debug(msg, e); + } + return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponse. + ErrorResponseBuilder().setMessage(e.getMessage()).build()).build(); + } + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImpl.java index 43c98523a5..acd19f4dbd 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImpl.java @@ -29,6 +29,7 @@ import org.eclipse.wst.common.uriresolver.internal.util.URIEncoder; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.OTPManagementException; import io.entgra.device.mgt.core.device.mgt.common.invitation.mgt.DeviceEnrollmentInvitation; @@ -65,11 +66,7 @@ import org.wso2.carbon.identity.claim.metadata.mgt.dto.LocalClaimDTO; import org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException; import org.wso2.carbon.identity.user.store.count.UserStoreCountRetriever; import org.wso2.carbon.identity.user.store.count.exception.UserStoreCounterException; -import org.wso2.carbon.user.api.Permission; -import org.wso2.carbon.user.api.RealmConfiguration; -import org.wso2.carbon.user.api.UserRealm; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.api.UserStoreManager; +import org.wso2.carbon.user.api.*; import org.wso2.carbon.user.core.UserCoreConstants; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.mgt.UserRealmProxy; @@ -78,6 +75,7 @@ import org.wso2.carbon.user.mgt.common.UserAdminException; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; +import javax.ws.rs.*; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; @@ -98,15 +96,8 @@ import java.security.SecureRandom; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; import java.util.Properties; -import java.util.Set; +import java.util.*; @Path("/users") @Produces(MediaType.APPLICATION_JSON) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/WhiteLabelServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/WhiteLabelServiceImpl.java index 50732fcc15..f818d7a300 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/WhiteLabelServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/WhiteLabelServiceImpl.java @@ -18,24 +18,20 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.WhiteLabelService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.common.FileResponse; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.NotFoundException; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.WhiteLabelTheme; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.WhiteLabelThemeCreateRequest; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.WhiteLabelService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.PathParam; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; + +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.ByteArrayInputStream; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java index 1d8c145ec6..096c4656cc 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java @@ -17,23 +17,23 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.admin; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ApplicationWrapper; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin.ApplicationManagementAdminService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.Platform; +import io.entgra.device.mgt.core.device.mgt.common.app.mgt.App; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ApplicationManagementException; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ApplicationManager; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.UnknownApplicationTypeException; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.UnknownApplicationTypeException; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin.ApplicationManagementAdminService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.core.util.MDMAndroidOperationUtil; import io.entgra.device.mgt.core.device.mgt.core.util.MDMIOSOperationUtil; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ApplicationWrapper; -import io.entgra.device.mgt.core.device.mgt.common.app.mgt.App; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.ws.rs.Consumes; import javax.ws.rs.POST; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceAccessAuthorizationAdminServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceAccessAuthorizationAdminServiceImpl.java index 38addbb5e8..3255629630 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceAccessAuthorizationAdminServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceAccessAuthorizationAdminServiceImpl.java @@ -17,17 +17,17 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.admin; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.AuthorizationRequest; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin.DeviceAccessAuthorizationAdminService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationException; +import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAuthorizationResult; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationException; -import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAuthorizationResult; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.AuthorizationRequest; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin.DeviceAccessAuthorizationAdminService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import javax.ws.rs.Consumes; import javax.ws.rs.POST; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceAnalyticsArtifactUploaderAdminServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceAnalyticsArtifactUploaderAdminServiceImpl.java deleted file mode 100644 index deb393a612..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceAnalyticsArtifactUploaderAdminServiceImpl.java +++ /dev/null @@ -1,504 +0,0 @@ -/* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.admin; - -import org.apache.axis2.AxisFault; -import org.apache.axis2.client.Options; -import org.apache.axis2.client.Stub; -import org.apache.axis2.java.security.SSLProtocolSocketFactory; -import org.apache.axis2.transport.http.HTTPConstants; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.protocol.Protocol; -import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; -import org.wso2.carbon.application.mgt.stub.upload.CarbonAppUploaderStub; -import org.wso2.carbon.application.mgt.stub.upload.types.carbon.UploadedFileItem; -import org.wso2.carbon.base.ServerConfiguration; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.core.util.Utils; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin.DeviceAnalyticsArtifactUploaderAdminService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; -import io.entgra.device.mgt.core.identity.jwt.client.extension.JWTClient; -import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; -import org.wso2.carbon.registry.core.exceptions.RegistryException; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.utils.CarbonUtils; -import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceStub; -import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; - -import javax.activation.DataHandler; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManagerFactory; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.core.Response; -import java.io.*; -import java.nio.file.Files; -import java.rmi.RemoteException; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; -import java.util.ArrayList; -import java.util.List; - -@Path("/admin/publish-artifact") -public class DeviceAnalyticsArtifactUploaderAdminServiceImpl implements DeviceAnalyticsArtifactUploaderAdminService { - - /** - * required soap header for authorization - */ - private static final String AUTHORIZATION_HEADER = "Authorization"; - - /** - * required soap header value for mutualSSL - */ - private static final String AUTHORIZATION_HEADER_VALUE = "Bearer"; - - private static final String KEY_STORE_TYPE = "JKS"; - /** - * Default truststore type of the client - */ - private static final String TRUST_STORE_TYPE = "JKS"; - /** - * Default keymanager type of the client - */ - private static final String KEY_MANAGER_TYPE = "SunX509"; //Default Key Manager Type - /** - * Default trustmanager type of the client - */ - private static final String TRUST_MANAGER_TYPE = "SunX509"; //Default Trust Manager Type - - private static final String SSLV3 = "SSLv3"; - - - - private KeyStore keyStore; - private KeyStore trustStore; - private char[] keyStorePassword; - private SSLContext sslContext; - - private String tenantDomain; - - private static final Log log = LogFactory.getLog(DeviceAnalyticsArtifactUploaderAdminServiceImpl.class); - private static final String DEFAULT_RESOURCE_LOCATION = "/resources/devicetypes"; - private static final String CAR_FILE_LOCATION = CarbonUtils.getCarbonHome() + File.separator + "repository" + - File.separator + "resources" + File.separator + "devicetypes"; - private static final String DAS_PORT = "${iot.analytics.https.port}"; - private static final String DAS_HOST_NAME = "${iot.analytics.host}"; - private static final String DEFAULT_HTTP_PROTOCOL = "https"; - private static final String IOT_MGT_PORT = "${iot.manager.https.port}"; - private static final String IOT_MGT_HOST_NAME = "${iot.manager.host}"; - private static final String DAS_URL = DEFAULT_HTTP_PROTOCOL + "://" + DAS_HOST_NAME - + ":" + DAS_PORT + "/services/CarbonAppUploader/"; - private static final String DAS_EVENT_RECEIVER_EP = DEFAULT_HTTP_PROTOCOL + "://" + DAS_HOST_NAME - + ":" + DAS_PORT + "/services/EventReceiverAdminService/"; - private static final String DAS_EVENT_STREAM_EP = DEFAULT_HTTP_PROTOCOL + "://" + DAS_HOST_NAME - + ":" + DAS_PORT + "/services/EventStreamAdminService/"; - - private static final String IOT_MGT_URL = DEFAULT_HTTP_PROTOCOL + "://" + IOT_MGT_HOST_NAME - + ":" + IOT_MGT_PORT + "/services/CarbonAppUploader/"; - private static final String MEDIA_TYPE_XML = "application/xml"; - private static final String DEVICE_MANAGEMENT_TYPE = "device_management"; - private static final String TENANT_DOMAIN_PROPERTY = "\\$\\{tenant-domain\\}"; - - - @Override - @POST - @Path("/deploy/{type}") - public Response doPublish(@PathParam("type") String type) { - try { - //Getting the tenant Domain - tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); - String tenantAdminUser = username + "@" + tenantDomain; - - String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password"); - String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty( - "Security.TrustStore.Password"); - String keyStoreLocation = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Location"); - String trustStoreLocation = ServerConfiguration.getInstance().getFirstProperty( - "Security.TrustStore.Location"); - - //Call to load the keystore. - loadKeyStore(keyStoreLocation, keyStorePassword); - //Call to load the TrustStore. - loadTrustStore(trustStoreLocation, trustStorePassword); - //Create the SSL context with the loaded TrustStore/keystore. - initSSLConnection(); - JWTClient jwtClient = DeviceMgtAPIUtils.getJWTClientManagerService().getJWTClient(); - - String authValue = AUTHORIZATION_HEADER_VALUE + " " + new String(Base64.encodeBase64( - jwtClient.getJwtToken(tenantAdminUser).getBytes())); - - List
list = new ArrayList<>(); - Header httpHeader = new Header(); - httpHeader.setName(AUTHORIZATION_HEADER); - httpHeader.setValue(authValue); - list.add(httpHeader);//"https" - - List streamFileList = getStreamsList(type); - List receiverFileList = getReceiversList(type); - - if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { - if (streamFileList != null) { - publishDynamicEventStream(type, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, streamFileList); - } - if (receiverFileList != null) { - publishDynamicEventReceivers(type, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, receiverFileList); - } - } - if (streamFileList != null) { - publishDynamicEventStream(type, tenantDomain, streamFileList); - } - if (deployAnalyticsCapp(type, list)){ - return Response.status(Response.Status.BAD_REQUEST) - .entity("\"Error, Artifact does not exist.\"").build(); - } - if (receiverFileList != null) { - publishDynamicEventReceivers(type, tenantDomain, receiverFileList); - } - return Response.status(Response.Status.CREATED).entity("\"OK. \\n Successfully uploaded the artifacts.\"") - .build(); - } catch (AxisFault e) { - log.error("failed to publish event definitions for tenantDomain:" + tenantDomain, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } catch (RemoteException e) { - log.error("Failed to connect with the remote services:" + tenantDomain, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } catch (JWTClientException e) { - log.error("Failed to generate jwt token for tenantDomain:" + tenantDomain, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } catch (UserStoreException e) { - log.error("Failed to connect with the user store, tenantDomain: " + tenantDomain, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } catch (CertificateException | UnrecoverableKeyException | KeyStoreException | - KeyManagementException | IOException | NoSuchAlgorithmException e) { - log.error("Failed to access keystore for, tenantDomain: " + tenantDomain, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } catch (RegistryException e) { - log.error("Failed to load tenant, tenantDomain: " + tenantDomain, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } catch (ParseException e) { - log.error("Invalid stream definition for device type" + type + " for tenant, tenantDomain: " + tenantDomain, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } - } - - private boolean deployAnalyticsCapp(@PathParam("type") String type, List
list) throws IOException, RegistryException { - CarbonAppUploaderStub carbonAppUploaderStub = null; - try { - File directory = new File(CAR_FILE_LOCATION + File.separator + type); - if (directory.isDirectory() && directory.exists()) { - UploadedFileItem[] uploadedFileItems = loadCappFromFileSystem(type); - if (uploadedFileItems.length > 0) { - if (DEVICE_MANAGEMENT_TYPE.equals(type.toLowerCase())) { - carbonAppUploaderStub = new CarbonAppUploaderStub(Utils.replaceSystemProperty( - IOT_MGT_URL)); - Options appUploaderOptions = carbonAppUploaderStub._getServiceClient().getOptions(); - if (appUploaderOptions == null) { - appUploaderOptions = new Options(); - } - appUploaderOptions.setProperty(HTTPConstants.HTTP_HEADERS, list); - appUploaderOptions.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER - , new Protocol(DEFAULT_HTTP_PROTOCOL, - (ProtocolSocketFactory) new SSLProtocolSocketFactory - (sslContext), Integer.parseInt(Utils.replaceSystemProperty( - IOT_MGT_PORT)))); - - carbonAppUploaderStub._getServiceClient().setOptions(appUploaderOptions); - carbonAppUploaderStub.uploadApp(uploadedFileItems); - } else { - carbonAppUploaderStub = new CarbonAppUploaderStub(Utils.replaceSystemProperty(DAS_URL)); - Options appUploaderOptions = carbonAppUploaderStub._getServiceClient().getOptions(); - if (appUploaderOptions == null) { - appUploaderOptions = new Options(); - } - appUploaderOptions.setProperty(HTTPConstants.HTTP_HEADERS, list); - appUploaderOptions.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER - , new Protocol(DEFAULT_HTTP_PROTOCOL - , (ProtocolSocketFactory) new SSLProtocolSocketFactory(sslContext) - , Integer.parseInt(Utils.replaceSystemProperty(DAS_PORT)))); - - carbonAppUploaderStub._getServiceClient().setOptions(appUploaderOptions); - carbonAppUploaderStub.uploadApp(uploadedFileItems); - } - } - } else { - return true; - } - return false; - } finally { - cleanup(carbonAppUploaderStub); - } - } - - private void publishDynamicEventReceivers(String deviceType, String tenantDomain, List receiversList) - throws IOException, UserStoreException, JWTClientException { - - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); - EventReceiverAdminServiceStub receiverAdminServiceStub = null; - try { - receiverAdminServiceStub = new EventReceiverAdminServiceStub - (Utils.replaceSystemProperty(DAS_EVENT_RECEIVER_EP)); - Options eventReciverOptions = receiverAdminServiceStub._getServiceClient().getOptions(); - if (eventReciverOptions == null) { - eventReciverOptions = new Options(); - } - String username; - if(!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { - username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() - .getRealmConfiguration().getAdminUserName()+"@"+tenantDomain; - }else { - username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() - .getRealmConfiguration().getAdminUserName(); - } - - - JWTClient jwtClient = DeviceMgtAPIUtils.getJWTClientManagerService().getJWTClient(); - - String authValue = AUTHORIZATION_HEADER_VALUE + " " + new String(Base64.encodeBase64( - jwtClient.getJwtToken(username).getBytes())); - - List
list = new ArrayList<>(); - Header httpHeader = new Header(); - httpHeader.setName(AUTHORIZATION_HEADER); - httpHeader.setValue(authValue); - list.add(httpHeader);//"https" - - eventReciverOptions.setProperty(HTTPConstants.HTTP_HEADERS, list); - eventReciverOptions.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER - , new Protocol(DEFAULT_HTTP_PROTOCOL - , (ProtocolSocketFactory) new SSLProtocolSocketFactory(sslContext) - , Integer.parseInt(Utils.replaceSystemProperty(DAS_PORT)))); - - receiverAdminServiceStub._getServiceClient().setOptions(eventReciverOptions); - for (String receiverContent:receiversList) { - receiverAdminServiceStub.deployEventReceiverConfiguration(receiverContent); - } - } finally { - cleanup(receiverAdminServiceStub); - PrivilegedCarbonContext.endTenantFlow(); - } - } - - private void publishDynamicEventStream(String deviceType, String tenantDomain, List streamList) - throws IOException, UserStoreException, JWTClientException, ParseException { - - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); - EventStreamAdminServiceStub eventStreamAdminServiceStub = null; - try { - eventStreamAdminServiceStub = new EventStreamAdminServiceStub - (Utils.replaceSystemProperty(DAS_EVENT_STREAM_EP)); - Options eventReciverOptions = eventStreamAdminServiceStub._getServiceClient().getOptions(); - if (eventReciverOptions == null) { - eventReciverOptions = new Options(); - } - String username; - if(!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { - username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() - .getRealmConfiguration().getAdminUserName()+"@"+tenantDomain; - }else { - username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() - .getRealmConfiguration().getAdminUserName(); - } - - - JWTClient jwtClient = DeviceMgtAPIUtils.getJWTClientManagerService().getJWTClient(); - - String authValue = AUTHORIZATION_HEADER_VALUE + " " + new String(Base64.encodeBase64( - jwtClient.getJwtToken(username).getBytes())); - - List
list = new ArrayList<>(); - Header httpHeader = new Header(); - httpHeader.setName(AUTHORIZATION_HEADER); - httpHeader.setValue(authValue); - list.add(httpHeader);//"https" - - eventReciverOptions.setProperty(HTTPConstants.HTTP_HEADERS, list); - eventReciverOptions.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER - , new Protocol(DEFAULT_HTTP_PROTOCOL - , (ProtocolSocketFactory) new SSLProtocolSocketFactory(sslContext) - , Integer.parseInt(Utils.replaceSystemProperty(DAS_PORT)))); - - eventStreamAdminServiceStub._getServiceClient().setOptions(eventReciverOptions); - for (String streamContent:streamList) { - JSONParser jsonParser = new JSONParser(); - JSONObject steamJson = (JSONObject)jsonParser.parse(streamContent); - String name = (String) steamJson.get("name"); - String version = (String) steamJson.get("version"); - String streamId = name +":"+version; - if (eventStreamAdminServiceStub.getStreamDefinitionDto(streamId) == null) { - eventStreamAdminServiceStub.addEventStreamDefinitionAsString(streamContent); - } - } - } finally { - cleanup(eventStreamAdminServiceStub); - PrivilegedCarbonContext.endTenantFlow(); - } - } - - - private List getReceiversList(String deviceType) throws IOException { - File directory = new File(CAR_FILE_LOCATION + File.separator + deviceType+File.separator+"receiver"); - if (!directory.exists()) { - return null; - } - File[] receiverFiles = directory.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.toLowerCase().endsWith(".xml"); - } - }); - List receiverList = new ArrayList<>(); - for (File receiverFile:receiverFiles) { - String receiverContentTemplate =new String(Files.readAllBytes(receiverFile.toPath())); - final String receiverContent = receiverContentTemplate.replaceAll(TENANT_DOMAIN_PROPERTY, tenantDomain.toLowerCase()); - receiverList.add(receiverContent); - } - - return receiverList; - } - - private List getStreamsList(String deviceType) throws IOException { - File directory = new File(CAR_FILE_LOCATION + File.separator + deviceType+File.separator+"streams"); - if (!directory.exists()) { - return null; - } - File[] receiverFiles = directory.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.toLowerCase().endsWith(".json"); - } - }); - List streamList = new ArrayList<>(); - for (File StreamFile:receiverFiles) { - String streamContent =new String(Files.readAllBytes(StreamFile.toPath())); - streamList.add(streamContent); - } - return streamList; - } - - private UploadedFileItem[] loadCappFromFileSystem(String deviceType) throws IOException { - - File directory = new File(CAR_FILE_LOCATION + File.separator + deviceType); - File[] carFiles = directory.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.toLowerCase().endsWith(".car"); - } - }); - List uploadedFileItemLis = new ArrayList<>(); - if (carFiles != null) { - - for (File carFile : carFiles) { - UploadedFileItem uploadedFileItem = new UploadedFileItem(); - DataHandler param = new DataHandler(carFile.toURI().toURL()); - uploadedFileItem.setDataHandler(param); - uploadedFileItem.setFileName(carFile.getName()); - uploadedFileItem.setFileType("jar"); - uploadedFileItemLis.add(uploadedFileItem); - } - } - UploadedFileItem[] fileItems = new UploadedFileItem[uploadedFileItemLis.size()]; - fileItems = uploadedFileItemLis.toArray(fileItems); - return fileItems; - } - - /** - * Loads the keystore. - * - * @param keyStorePath - the path of the keystore - * @param ksPassword - the keystore password - */ - private void loadKeyStore(String keyStorePath, String ksPassword) - throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { - InputStream fis = null; - try { - keyStorePassword = ksPassword.toCharArray(); - keyStore = KeyStore.getInstance(KEY_STORE_TYPE); - fis = new FileInputStream(keyStorePath); - keyStore.load(fis, keyStorePassword); - } finally { - if (fis != null) { - fis.close(); - } - } - } - - /** - * Loads the trustore - * - * @param trustStorePath - the trustore path in the filesystem. - * @param tsPassword - the truststore password - */ - private void loadTrustStore(String trustStorePath, String tsPassword) - throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { - - InputStream fis = null; - try { - trustStore = KeyStore.getInstance(TRUST_STORE_TYPE); - fis = new FileInputStream(trustStorePath); - trustStore.load(fis, tsPassword.toCharArray()); - } finally { - if (fis != null) { - fis.close(); - } - } - } - - /** - * Initializes the SSL Context - */ - private void initSSLConnection() throws NoSuchAlgorithmException, UnrecoverableKeyException, - KeyStoreException, KeyManagementException { - KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE); - keyManagerFactory.init(keyStore, keyStorePassword); - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE); - trustManagerFactory.init(trustStore); - - // Create and initialize SSLContext for HTTPS communication - sslContext = SSLContext.getInstance(SSLV3); - sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); - SSLContext.setDefault(sslContext); - } - - private void cleanup(Stub stub) { - if (stub != null) { - try { - stub.cleanup(); - } catch (AxisFault axisFault) { - //do nothing - } - } - } - -} - diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java index 5a9c4fa55d..7d7e18738e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java @@ -17,45 +17,29 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.admin; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; -import io.entgra.device.mgt.core.device.mgt.common.MDMAppConstants; -import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceList; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin.DeviceManagementAdminService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import io.entgra.device.mgt.core.device.mgt.common.*; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationEntry; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationManagementException; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService; import io.entgra.device.mgt.core.device.mgt.common.exceptions.BadRequestException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceNotFoundException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidDeviceException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.UserNotFoundException; -import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.*; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceList; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin.DeviceManagementAdminService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.service.RealmService; import javax.validation.constraints.Size; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.sql.Timestamp; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceTypeManagementAdminServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceTypeManagementAdminServiceImpl.java index bf9214a640..efee063818 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceTypeManagementAdminServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceTypeManagementAdminServiceImpl.java @@ -18,31 +18,23 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.admin; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceTypeVersionWrapper; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin.DeviceTypeManagementAdminService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService; import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceTypeVersion; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceTypeVersionWrapper; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin.DeviceTypeManagementAdminService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; +import javax.ws.rs.*; import javax.ws.rs.core.Response; import java.util.List; import java.util.regex.Matcher; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java index ec8c3a65f7..0ed3205426 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java @@ -17,20 +17,20 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.admin; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceGroupList; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin.GroupManagementAdminService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroupConstants; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroupRoleWrapper; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupAlreadyExistException; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupManagementException; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.RoleDoesNotExistException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.GroupPaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceGroupList; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin.GroupManagementAdminService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.apache.commons.lang.StringUtils; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java index 91ed3f6d42..858f31e66c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java @@ -20,6 +20,7 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.admin; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.tenant.mgt.common.exception.TenantMgtException; +import io.entgra.device.mgt.core.tenant.mgt.common.spi.TenantManagerAdminService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; @@ -32,7 +33,13 @@ import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.CarbonContext; import javax.validation.constraints.Size; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -89,37 +96,46 @@ public class UserManagementAdminServiceImpl implements UserManagementAdminServic @DELETE @Path("/domain/{tenantDomain}") @Override - public Response deleteTenantByDomain(@PathParam("tenantDomain") String tenantDomain, @QueryParam("deleteAppArtifacts") boolean deleteAppArtifacts) { + public Response deleteTenantByDomain(@PathParam("tenantDomain") String tenantDomain, + @QueryParam("deleteAppArtifacts") boolean deleteAppArtifacts) { try { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - if (tenantId != MultitenantConstants.SUPER_TENANT_ID){ - String msg = "Only super tenants are allowed to delete tenants"; + if (CarbonContext.getThreadLocalCarbonContext().getTenantId() != MultitenantConstants.SUPER_TENANT_ID){ + String msg = "Only super tenants are allowed to delete tenants."; log.error(msg); return Response.status(Response.Status.UNAUTHORIZED).entity(msg).build(); - } else { - if (deleteAppArtifacts) { - DeviceMgtAPIUtils.getApplicationManager().deleteApplicationArtifactsByTenantDomain(tenantDomain); - } - DeviceMgtAPIUtils.getApplicationManager().deleteApplicationDataByTenantDomain(tenantDomain); - DeviceMgtAPIUtils.getDeviceManagementService().deleteDeviceDataByTenantDomain(tenantDomain); - DeviceMgtAPIUtils.getTenantManagerAdminService().deleteTenant(tenantDomain); - String msg = "Tenant Deletion process has been initiated for tenant:" + tenantDomain; - if (log.isDebugEnabled()) { - log.debug(msg); - } - return Response.status(Response.Status.OK).entity(msg).build(); } + if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { + String msg = "You are not allowed to delete the super tenant."; + log.error(msg); + return Response.status(Response.Status.UNAUTHORIZED).entity(msg).build(); + } + + if (log.isDebugEnabled()) { + log.debug("Tenant Deletion process has been initiated for tenant:" + tenantDomain); + } + + TenantManagerAdminService tenantManagerAdminService = DeviceMgtAPIUtils.getTenantManagerAdminService(); + int tenantId = tenantManagerAdminService.getTenantId(tenantDomain); + + if (deleteAppArtifacts) { + DeviceMgtAPIUtils.getApplicationManager().deleteApplicationArtifactsByTenantId(tenantId); + } + DeviceMgtAPIUtils.getApplicationManager().deleteApplicationDataByTenantId(tenantId); + DeviceMgtAPIUtils.getDeviceManagementService().deleteDeviceDataByTenantId(tenantId); + DeviceMgtAPIUtils.getTenantManagerAdminService().deleteTenant(tenantDomain); + return Response.status(Response.Status.OK).entity("Tenant Deletion process has been completed " + + "successfully for tenant: " + tenantDomain).build(); } catch (TenantMgtException e) { - String msg = "Error deleting tenant: " + tenantDomain; + String msg = "Error occurred while deleting tenant: " + tenantDomain; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (ApplicationManagementException e) { - String msg = "Error deleting application data of tenant: " + tenantDomain; + String msg = "Error occurred while deleting application data of tenant: " + tenantDomain; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (DeviceManagementException e) { - String msg = "Error deleting device data of tenant: " + tenantDomain; + String msg = "Error occurred while deleting device data of tenant: " + tenantDomain; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/util/RequestValidationUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/util/RequestValidationUtil.java index ab66e75d1c..12de45f445 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/util/RequestValidationUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/util/RequestValidationUtil.java @@ -19,12 +19,10 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpStatus; -import org.json.JSONArray; -import org.json.JSONObject; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.*; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.exception.BadRequestException; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.common.Base64File; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.Feature; @@ -36,30 +34,24 @@ import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementEx import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceTypeNotFoundException; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.WhiteLabelImageRequestPayload; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.WhiteLabelThemeCreateRequest; import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.Notification; import io.entgra.device.mgt.core.device.mgt.core.common.util.HttpUtil; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.WhiteLabelThemeCreateRequest; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ApplicationWrapper; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.EventConfig; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.GeofenceWrapper; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.OldPasswordResetWrapper; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.PolicyWrapper; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ProfileFeature; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.RoleInfo; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.Scope; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.exception.BadRequestException; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.policy.mgt.common.PolicyPayloadValidator; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpStatus; +import org.json.JSONArray; +import org.json.JSONObject; import java.lang.reflect.InvocationTargetException; -import java.util.List; import java.util.ArrayList; -import java.util.Calendar; import java.util.Arrays; +import java.util.Calendar; +import java.util.List; public class RequestValidationUtil { @@ -492,6 +484,70 @@ public class RequestValidationUtil { } } + /** + * Validates the provided tag details to ensure that either a valid tagId or a non-empty tagName is provided, + * and that the tagInfo is not null. Throws InputValidationException if any of these conditions are not met. + * + * @param tagId the ID of the tag (must be greater than 0) + * @param tagName the name of the tag (must be non-empty if tagId is not provided) + * @param tagInfo the TagInfo object to validate (must not be null) + * @throws InputValidationException if neither a valid tagId nor a tagName is provided, or if tagInfo is null + */ + public static void validateTagDetails(Integer tagId, String tagName, TagInfo tagInfo) { + if ((tagId == null || tagId <= 0) && StringUtils.isBlank(tagName)) { + String msg = "Either valid tagId or tagName must be provided."; + log.error(msg); + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(msg).build()); + } + if (tagInfo == null) { + String msg = "Provided request body is empty."; + log.error(msg); + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Request body is " + + "empty").build()); + } + } + + /** + * Validates the provided list of TagInfo objects to ensure that it is not null. + * Throws InputValidationException if the list is null. + * + * @param tagInfo the list of TagInfo objects to validate (must not be null) + * @throws InputValidationException if the list is null + */ + public static void validateTagListDetails(List tagInfo) { + if (tagInfo == null) { + String msg = "Provided request body is empty."; + log.error(msg); + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Request body is " + + "empty").build()); + } + } + + /** + * Validates the provided TagMappingInfo object to ensure it is not null and contains valid + * device identifiers, device type, and tags. Throws InputValidationException if validation fails. + * + * @param tagMappingInfo the TagMappingInfo object to validate + * @throws InputValidationException if the tagMappingInfo or its required fields are invalid + */ + public static void validateTagMappingDetails(TagMappingInfo tagMappingInfo) { + if (tagMappingInfo == null) { + String msg = "Provided request body is empty."; + log.error(msg); + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400L).setMessage("Request body is empty").build()); + } else if (tagMappingInfo.getDeviceIdentifiers() == null || tagMappingInfo.getDeviceType() == null + || tagMappingInfo.getTags() == null) { + String msg = "Invalid tag mapping request body."; + log.error(msg); + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400L).setMessage("Invalid tag mapping request body").build()); + } + } + public static void validateScopes(List scopes) { if (scopes == null || scopes.isEmpty()) { throw new InputValidationException( diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/swagger/extension/SecurityDefinitionConfigurator.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/swagger/extension/SecurityDefinitionConfigurator.java index 26ad33f207..9687a03779 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/swagger/extension/SecurityDefinitionConfigurator.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/swagger/extension/SecurityDefinitionConfigurator.java @@ -23,11 +23,8 @@ import io.swagger.jaxrs.config.ReaderListener; import io.swagger.models.Swagger; import io.swagger.models.auth.OAuth2Definition; import io.swagger.models.auth.SecuritySchemeDefinition; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.Scope; -import java.util.ArrayList; import java.util.HashMap; -import java.util.List; import java.util.Map; @SwaggerDefinition( diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/CredentialManagementResponseBuilder.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/CredentialManagementResponseBuilder.java index 570ef69419..43f2459ab8 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/CredentialManagementResponseBuilder.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/CredentialManagementResponseBuilder.java @@ -18,13 +18,13 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.util; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.OldPasswordResetWrapper; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.PasswordResetWrapper; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/DeviceMgtAPIUtils.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/DeviceMgtAPIUtils.java index 5451572519..0bd3938dd9 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/DeviceMgtAPIUtils.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/DeviceMgtAPIUtils.java @@ -19,11 +19,21 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.util; import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherService; +import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceTypeVersionWrapper; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.OperationStatusBean; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.EventAttributeList; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.InputValidationException; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; import io.entgra.device.mgt.core.device.mgt.common.authorization.GroupAccessAuthorizationService; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.DeviceStatusManagementService; import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; +import io.entgra.device.mgt.core.device.mgt.core.service.TagManagementProviderService; import io.entgra.device.mgt.core.tenant.mgt.common.spi.TenantManagerAdminService; import org.apache.axis2.AxisFault; import org.apache.axis2.client.Options; @@ -38,7 +48,6 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.analytics.api.AnalyticsDataAPI; import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceStub; -import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub; import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -65,7 +74,6 @@ import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.common.report.mgt.ReportManagementService; import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceTypeGeneratorService; import io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService; -import io.entgra.device.mgt.core.device.mgt.common.spi.TraccarManagementService; import io.entgra.device.mgt.core.device.mgt.core.app.mgt.ApplicationManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.device.details.mgt.DeviceInformationManager; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceTypeVersion; @@ -75,12 +83,12 @@ import io.entgra.device.mgt.core.device.mgt.core.search.mgt.SearchManagerService import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.traccar.api.service.DeviceAPIClientService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceTypeVersionWrapper; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.OperationStatusBean; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.EventAttributeList; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.InputValidationException; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; +import io.entgra.device.mgt.core.identity.jwt.client.extension.JWTClient; +import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; +import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; +import io.entgra.device.mgt.core.policy.mgt.common.PolicyMonitoringTaskException; +import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; +import io.entgra.device.mgt.core.policy.mgt.core.task.TaskScheduleService; import org.wso2.carbon.event.processor.stub.EventProcessorAdminServiceStub; import org.wso2.carbon.event.publisher.core.EventPublisherService; import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceStub; @@ -89,17 +97,11 @@ import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceStub; import org.wso2.carbon.event.stream.core.EventStreamService; import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub; import org.wso2.carbon.identity.claim.metadata.mgt.dto.ClaimPropertyDTO; -import io.entgra.device.mgt.core.identity.jwt.client.extension.JWTClient; -import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; -import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; import org.wso2.carbon.identity.user.store.count.AbstractCountRetrieverFactory; import org.wso2.carbon.identity.user.store.count.UserStoreCountRetriever; import org.wso2.carbon.identity.user.store.count.exception.UserStoreCounterException; import org.wso2.carbon.identity.user.store.count.jdbc.JDBCCountRetrieverFactory; import org.wso2.carbon.identity.user.store.count.jdbc.internal.InternalCountRetrieverFactory; -import io.entgra.device.mgt.core.policy.mgt.common.PolicyMonitoringTaskException; -import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; -import io.entgra.device.mgt.core.policy.mgt.core.task.TaskScheduleService; import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.user.api.*; import org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager; @@ -162,9 +164,12 @@ public class DeviceMgtAPIUtils { private static OTPManagementService otpManagementService; private static volatile SubscriptionManager subscriptionManager; private static volatile ApplicationManager applicationManager; - + private static volatile APIApplicationServices apiApplicationServices; + private static volatile ConsumerRESTAPIServices consumerRESTAPIServices; + private static volatile APIManagementProviderService apiManagementProviderService; private static volatile APIPublisherService apiPublisher; private static volatile TenantManagerAdminService tenantManagerAdminService; + private static volatile TagManagementProviderService tagManagementService; static { String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password"); @@ -427,6 +432,63 @@ public class DeviceMgtAPIUtils { return otpManagementService; } + /** + * Initializing and accessing method for APIM Consumer REST API. + * + * @return ConsumerRESTAPIServices instance + * @throws IllegalStateException if ConsumerRESTAPIServices cannot be initialized + */ + public static synchronized ConsumerRESTAPIServices getConsumerRESTAPIServices() { + if (consumerRESTAPIServices == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + consumerRESTAPIServices = (ConsumerRESTAPIServices) ctx.getOSGiService(ConsumerRESTAPIServices.class, null); + if (consumerRESTAPIServices == null) { + String msg = "Consumer Rest API service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + } + return consumerRESTAPIServices; + } + + /** + * Initializing and accessing method for APIM API application REST API. + * + * @return APIApplicationServices instance + * @throws IllegalStateException if APIApplicationServices cannot be initialized + */ + public static synchronized APIApplicationServices getApiApplicationServices() { + if (apiApplicationServices == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + apiApplicationServices = (APIApplicationServices) ctx.getOSGiService(APIApplicationServices.class, null); + if (apiApplicationServices == null) { + String msg = "API application service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + } + return apiApplicationServices; + } + + /** + * Initializing and accessing method for API management Provider Service. + * + * @return APIManagementProviderService instance + * @throws IllegalStateException if APIManagementProviderService cannot be initialized + */ + public static synchronized APIManagementProviderService getAPIManagementService() { + if (apiManagementProviderService == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + apiManagementProviderService = (APIManagementProviderService) ctx.getOSGiService(APIManagementProviderService.class, null); + if (apiManagementProviderService == null) { + String msg = "API Management Provider service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + } + return apiManagementProviderService; + } + public static RegistryService getRegistryService() { RegistryService registryService; PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); @@ -505,6 +567,28 @@ public class DeviceMgtAPIUtils { return policyManagementService; } + /** + * Initializing and accessing method for TagManagementService. + * + * @return TagManagementService instance + * @throws IllegalStateException if TagManagementService cannot be initialized + */ + public static TagManagementProviderService getTagManagementService() { + if (tagManagementService == null) { + synchronized (DeviceMgtAPIUtils.class) { + if (tagManagementService == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + tagManagementService = (TagManagementProviderService) ctx.getOSGiService( + TagManagementProviderService.class, null); + if (tagManagementService == null) { + throw new IllegalStateException("Tag Management service not initialized."); + } + } + } + } + return tagManagementService; + } + public static PlatformConfigurationManagementService getPlatformConfigurationManagementService() { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PlatformConfigurationManagementService tenantConfigurationManagementService = diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml index 7cdb4ffa0e..7bf4992e1a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -43,7 +43,6 @@ - @@ -51,6 +50,7 @@ + @@ -95,7 +95,6 @@ - @@ -103,6 +102,7 @@ + diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ActivityProviderServiceImplTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ActivityProviderServiceImplTest.java index 59baa18242..1cc391a3e7 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ActivityProviderServiceImplTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ActivityProviderServiceImplTest.java @@ -18,6 +18,11 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationService; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManagementException; +import io.entgra.device.mgt.core.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mockito.Mockito; @@ -31,14 +36,9 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationService; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import io.entgra.device.mgt.core.device.mgt.common.ActivityPaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.DeviceActivity; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManagementException; -import io.entgra.device.mgt.core.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.common.ActivityIdList; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ConfigurationServiceImplTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ConfigurationServiceImplTest.java index bf4ccaafd4..5fa7eecb6b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ConfigurationServiceImplTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ConfigurationServiceImplTest.java @@ -18,6 +18,13 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.ConfigurationManagementService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationEntry; +import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationManagementException; +import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; +import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService; +import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagerUtil; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; @@ -28,13 +35,6 @@ import org.testng.IObjectFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; -import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationEntry; -import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationManagementException; -import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; -import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.ConfigurationManagementService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; -import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagerUtil; import javax.ws.rs.core.Response; import java.util.ArrayList; @@ -43,10 +43,11 @@ import java.util.List; /** * This is a test class for {@link ConfigurationServiceImpl}. */ -@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*"}) +@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*", "org.mockito.*"}) @SuppressStaticInitializationFor({"io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils", "org.wso2.carbon.context.CarbonContext"}) @PrepareForTest({DeviceMgtAPIUtils.class, PolicyManagerUtil.class}) +//@PowerMockIgnore("org.mockito.*") public class ConfigurationServiceImplTest { private ConfigurationManagementService configurationManagementService; private PlatformConfigurationManagementService platformConfigurationManagementService; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceAgentServiceTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceAgentServiceTest.java index d7ac8671ee..1abf3d5fc3 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceAgentServiceTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceAgentServiceTest.java @@ -17,6 +17,25 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.DeviceAgentService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin.DeviceTypeManagementAdminService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.DeviceMgtAPITestHelper; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import io.entgra.device.mgt.core.device.mgt.common.Device; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; +import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationException; +import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationService; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManagementException; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; +import io.entgra.device.mgt.core.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; +import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; +import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerServiceImpl; import org.apache.axis2.AxisFault; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -34,28 +53,7 @@ import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.caching.impl.CacheImpl; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; -import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationException; -import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationService; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManagementException; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; -import io.entgra.device.mgt.core.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.DeviceAgentService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin.DeviceTypeManagementAdminService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.DeviceMgtAPITestHelper; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub; -import org.wso2.carbon.event.stream.stub.types.EventStreamAttributeDto; -import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto; -import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; -import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; -import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerServiceImpl; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.utils.CarbonUtils; @@ -71,7 +69,7 @@ import static org.mockito.MockitoAnnotations.initMocks; /** * This class holds the unit tests for the class {@link DeviceAgentServiceImpl} */ -@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*"}) +@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*", "org.mockito.*"}) @SuppressStaticInitializationFor({"io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils", "org.wso2.carbon.context.CarbonContext", "org.wso2.carbon.context.internal.CarbonContextDataHolder"}) @PrepareForTest({DeviceMgtAPIUtils.class, DeviceManagementProviderService.class, diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImplTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImplTest.java index b66773e84d..cd54693953 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImplTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImplTest.java @@ -18,19 +18,9 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; -import org.wso2.carbon.context.CarbonContext; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.DeviceManagementService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.DeviceMgtAPITestHelper; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; @@ -52,11 +42,21 @@ import io.entgra.device.mgt.core.device.mgt.core.search.mgt.SearchMgtException; import io.entgra.device.mgt.core.device.mgt.core.search.mgt.impl.SearchManagerServiceImpl; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.DeviceManagementService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.DeviceMgtAPITestHelper; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; +import org.testng.Assert; +import org.testng.IObjectFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.ObjectFactory; +import org.testng.annotations.Test; +import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; @@ -72,7 +72,7 @@ import static org.mockito.MockitoAnnotations.initMocks; /** * This class includes unit tests for testing the functionality of {@link DeviceManagementServiceImpl} */ -@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*"}) +@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*", "org.mockito.*"}) @SuppressStaticInitializationFor({"io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils", "org.wso2.carbon.context.CarbonContext", "org.wso2.carbon.user.core.service.RealmService"}) @PrepareForTest({DeviceMgtAPIUtils.class, MultitenantUtils.class, CarbonContext.class, RealmService.class}) @@ -158,7 +158,7 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, - 10, 5); + null, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); } @@ -178,22 +178,22 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, null,null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, - 10, 5); + null, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); response = this.deviceManagementService .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, null, DEFAULT_OWNERSHIP, null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, - 10, 5); + null, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); response = this.deviceManagementService .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP, null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, - 10, 5); + null, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); response = this.deviceManagementService .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP, null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, true, - 10, 5); + null, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); } @@ -307,7 +307,7 @@ public class DeviceManagementServiceImplTest { Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true); deviceManagementService.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, null,null, DEFAULT_STATUS_LIST, 1, - 0, null, null, false, 10, 5); + 0, null, null, false, null, 10, 5); } @Test(description = "Testing get devices when user is the device admin") @@ -326,11 +326,11 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP - , null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, 10, 5); + , null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, null, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, null, DEFAULT_USERNAME, DEFAULT_ROLE, DEFAULT_OWNERSHIP - , null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, 10, 5); + , null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, null, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); } @@ -353,7 +353,7 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, "newuser", null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, null, null, DEFAULT_STATUS_LIST, 0, 0, null, null, false, - 10, 5); + null, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode()); Mockito.reset(this.deviceAccessAuthorizationService); } @@ -375,17 +375,17 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, null, null, DEFAULT_STATUS_LIST, 0, 0, null, ifModifiedSince, false, - 10, 5); + null, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode()); response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, null, null, DEFAULT_STATUS_LIST, 0, 0, null, ifModifiedSince, true, - 10, 5); + null, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode()); response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, null, null, DEFAULT_STATUS_LIST, 0, 0, null, "ErrorModifiedSince", - false, 10, 5); + false, null, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); } @@ -406,17 +406,17 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, null, null,DEFAULT_STATUS_LIST, 0, 0, since, null, false, - 10, 5); + null, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, null, null,DEFAULT_STATUS_LIST, 0, 0, since, null, true, - 10, 5); + null, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, null, null,DEFAULT_STATUS_LIST, 0, 0, "ErrorSince", null, false, - 10, 5); + null, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); } @@ -439,7 +439,7 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, - 10, 5); + null, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); Mockito.reset(this.deviceManagementProviderService); } @@ -461,8 +461,8 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, - 10, 5); + null, null, DEFAULT_STATUS_LIST, 1, 0,null, null, false, + null, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); Mockito.reset(this.deviceAccessAuthorizationService); } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceTypeManagementAdminServiceTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceTypeManagementAdminServiceTest.java index fb84bc2e59..4fe4473930 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceTypeManagementAdminServiceTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceTypeManagementAdminServiceTest.java @@ -18,6 +18,16 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin.DeviceTypeManagementAdminService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.admin.DeviceTypeManagementAdminServiceImpl; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.DeviceMgtAPITestHelper; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceTypeGeneratorService; +import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.DeviceTypeGeneratorServiceImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mockito.Mockito; @@ -33,16 +43,6 @@ import org.testng.annotations.Test; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceTypeGeneratorService; -import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.DeviceTypeGeneratorServiceImpl; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin.DeviceTypeManagementAdminService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.admin.DeviceTypeManagementAdminServiceImpl; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.DeviceMgtAPITestHelper; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import javax.ws.rs.core.Response; @@ -51,7 +51,7 @@ import static org.mockito.MockitoAnnotations.initMocks; /** * This class holds the unit tests for the class {@link DeviceTypeManagementAdminService} */ -@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*"}) +@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*", "org.mockito.*"}) @SuppressStaticInitializationFor({"io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils", "org.wso2.carbon.context.PrivilegedCarbonContext"}) @PrepareForTest({DeviceMgtAPIUtils.class, DeviceManagementProviderService.class, CarbonContext.class}) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceTypeManagementServiceTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceTypeManagementServiceTest.java index 636ecdca33..24f8841ca8 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceTypeManagementServiceTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceTypeManagementServiceTest.java @@ -17,6 +17,14 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.DeviceTypeManagementService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.DeviceMgtAPITestHelper; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import io.entgra.device.mgt.core.device.mgt.common.FeatureManager; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mockito.Mockito; @@ -29,14 +37,6 @@ import org.testng.IObjectFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.FeatureManager; -import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.DeviceTypeManagementService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.DeviceMgtAPITestHelper; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import javax.ws.rs.core.Response; import java.lang.reflect.InvocationTargetException; @@ -48,7 +48,7 @@ import static org.mockito.MockitoAnnotations.initMocks; /** * This class holds the unit tests for the class {@link DeviceTypeManagementService} */ -@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*"}) +@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*", "org.mockito.*"}) @SuppressStaticInitializationFor({"io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils"}) @PrepareForTest({DeviceMgtAPIUtils.class, DeviceManagementProviderService.class}) public class DeviceTypeManagementServiceTest { @@ -129,8 +129,9 @@ public class DeviceTypeManagementServiceTest { FeatureManager featureManager = Mockito.mock(FeatureManager.class); Mockito.when(this.deviceManagementProviderService.getFeatureManager(Mockito.anyString())).thenReturn (featureManager); - Mockito.when((featureManager).getFeatures(Mockito.anyString())).thenThrow(new DeviceManagementException()); - Mockito.when((featureManager).getFeatures(Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new DeviceManagementException()); + Mockito.when(featureManager.getFeatures(Mockito.anyString())).thenThrow(new DeviceManagementException()); + Mockito.when(featureManager.getFeatures(Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new DeviceManagementException()); + Mockito.when(featureManager.getFeatures(Mockito.any(), Mockito.anyBoolean())).thenThrow(new DeviceManagementException()); Response response = this.deviceTypeManagementService.getFeatures(TEST_DEVICE_TYPE, null, "false", MODIFIED_SINCE); Assert.assertNotNull(response, "The response object is null."); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GeoLocationBasedServiceImplTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GeoLocationBasedServiceImplTest.java index 53eca5ff87..7ac7b28340 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GeoLocationBasedServiceImplTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GeoLocationBasedServiceImplTest.java @@ -18,18 +18,18 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.GeoLocationBasedService; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoCluster; +import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoCoordinate; +import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoQuery; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import org.mockito.Mockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoCluster; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoCoordinate; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoQuery; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.GeoLocationBasedService; import javax.ws.rs.core.Response; import java.util.ArrayList; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GroupManagementServiceImplTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GroupManagementServiceImplTest.java index 1f88b3b77c..8eadf18e5a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GroupManagementServiceImplTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/GroupManagementServiceImplTest.java @@ -18,6 +18,18 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceToGroupsAssignment; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.GroupManagementService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import io.entgra.device.mgt.core.device.mgt.common.Device; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.GroupPaginationRequest; +import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceNotFoundException; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.*; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderService; +import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; @@ -31,22 +43,6 @@ import org.testng.annotations.Test; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceNotFoundException; -import io.entgra.device.mgt.core.device.mgt.common.GroupPaginationRequest; -import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupAlreadyExistException; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupManagementException; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupNotExistException; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.RoleDoesNotExistException; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceToGroupsAssignment; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.GroupManagementService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; -import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; import javax.ws.rs.core.Response; import java.util.ArrayList; @@ -55,7 +51,7 @@ import java.util.List; /** * This is a test case for {@link GroupManagementServiceImpl}. */ -@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*", "javax.xml.parsers"}) +@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*", "javax.xml.parsers", "org.mockito.*"}) @SuppressStaticInitializationFor({"io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils", "org.wso2.carbon.context.CarbonContext", "org.wso2.carbon.context.PrivilegedCarbonContext"}) @PrepareForTest({DeviceMgtAPIUtils.class, CarbonContext.class}) @@ -129,13 +125,13 @@ public class GroupManagementServiceImplTest { PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext")) .toReturn(context); Mockito.doReturn(2).when(groupManagementProviderService) - .getGroupCount(Mockito.anyString(), Mockito.anyString()); + .getGroupCount(Mockito.anyString(), Mockito.any()); Response response = groupManagementService.getGroupCount(); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "GetGroupCount request failed with valid parameters"); Mockito.reset(groupManagementProviderService); Mockito.doThrow(new GroupManagementException()).when(groupManagementProviderService) - .getGroupCount(Mockito.anyString(), Mockito.anyString()); + .getGroupCount(Mockito.anyString(), Mockito.any()); response = groupManagementService.getGroupCount(); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "GetGroupCount request succeeded with in-valid parameters"); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/NotificationManagementServiceImplTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/NotificationManagementServiceImplTest.java index 6735329a7d..d40b8bd406 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/NotificationManagementServiceImplTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/NotificationManagementServiceImplTest.java @@ -18,6 +18,11 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; +import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.Notification; +import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.NotificationManagementException; +import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.NotificationManagementService; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; @@ -29,13 +34,9 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; import org.wso2.carbon.context.CarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; -import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.Notification; -import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.NotificationManagementException; -import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.NotificationManagementService; -import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; + import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; @@ -45,7 +46,7 @@ import static org.mockito.MockitoAnnotations.initMocks; /** * This is a test class for {@link NotificationManagementServiceImpl}. */ -@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*"}) +@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*", "org.mockito.*"}) @SuppressStaticInitializationFor({"io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils", "org.wso2.carbon.context.CarbonContext"}) @PrepareForTest({DeviceMgtAPIUtils.class, MultitenantUtils.class, CarbonContext.class}) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImplTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImplTest.java index f25a37c9e7..60530eed80 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImplTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImplTest.java @@ -62,7 +62,7 @@ import static org.mockito.MockitoAnnotations.initMocks; /** * This is a test case for {@link UserManagementService}. */ -@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*"}) +@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*", "org.mockito.*"}) @SuppressStaticInitializationFor({"io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils", "org.wso2.carbon.context.CarbonContext"}) @PrepareForTest({DeviceMgtAPIUtils.class, MultitenantUtils.class, CarbonContext.class}) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/pom.xml index 98859c7087..cc9da3624c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/pom.xml @@ -30,10 +30,18 @@ bundle WSO2 Carbon - Device Management Commons WSO2 Carbon - Device Management Commons - http://wso2.org + https://entgra.io + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + org.apache.felix maven-bundle-plugin @@ -48,10 +56,28 @@ io.entgra.device.mgt.core.device.mgt.common.* - javax.xml.bind.annotation; version="${javax.xml.bind.imp.pkg.version}", - com.fasterxml.jackson.annotation;version="${jackson-annotations.version}", - io.swagger.annotations; version="${swagger.annotations.version}"; resolution:=optional, - com.google.gson + com.fasterxml.jackson.annotation;version="[2.9,3)", + com.google.gson;version="[2.9,3)", + io.entgra.device.mgt.core.device.mgt.common, + io.entgra.device.mgt.core.device.mgt.common.app.mgt, + io.entgra.device.mgt.core.device.mgt.common.configuration.mgt, + io.entgra.device.mgt.core.device.mgt.common.device.details, + io.entgra.device.mgt.core.device.mgt.common.event.config, + io.entgra.device.mgt.core.device.mgt.common.exceptions, + io.entgra.device.mgt.core.device.mgt.common.general, + io.entgra.device.mgt.core.device.mgt.common.group.mgt, + io.entgra.device.mgt.core.device.mgt.common.invitation.mgt, + io.entgra.device.mgt.core.device.mgt.common.license.mgt, + io.entgra.device.mgt.core.device.mgt.common.metadata.mgt, + io.entgra.device.mgt.core.device.mgt.common.operation.mgt, + io.entgra.device.mgt.core.device.mgt.common.otp.mgt.dto, + io.entgra.device.mgt.core.device.mgt.common.policy.mgt, + io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor, + io.entgra.device.mgt.core.device.mgt.common.pull.notification, + io.entgra.device.mgt.core.device.mgt.common.push.notification, + io.entgra.device.mgt.core.device.mgt.common.type.mgt, + io.swagger.annotations;version="[1.6,2)", + javax.xml.bind.annotation;version="[0.0,1)" @@ -99,6 +125,11 @@ com.google.code.gson gson + + org.wso2.orbit.javax.xml.bind + jaxb-api + + diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/Billing.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/Billing.java index 558c74afb0..c1d7b63317 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/Billing.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/Billing.java @@ -20,6 +20,7 @@ package io.entgra.device.mgt.core.device.mgt.common; import com.google.gson.Gson; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; + import java.io.Serializable; @ApiModel(value = "Billing", description = "This class carries all information related to a device billing.") diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/BillingResponse.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/BillingResponse.java index 0dfa45d444..6a6d96d512 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/BillingResponse.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/BillingResponse.java @@ -20,6 +20,7 @@ package io.entgra.device.mgt.core.device.mgt.common; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; + import java.io.Serializable; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/Device.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/Device.java index 2819364327..592301ff12 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/Device.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/Device.java @@ -17,14 +17,14 @@ */ package io.entgra.device.mgt.core.device.mgt.common; -import com.google.gson.Gson; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.Gson; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.Application; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceInfo; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceLocationHistorySnapshotWrapper; import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceStatus; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.util.ArrayList; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/DeviceBilling.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/DeviceBilling.java index a5442bdb79..863bd8a3f7 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/DeviceBilling.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/DeviceBilling.java @@ -18,10 +18,10 @@ package io.entgra.device.mgt.core.device.mgt.common; import com.google.gson.Gson; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceInfo; import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceStatus; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.util.ArrayList; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/EnrolmentInfo.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/EnrolmentInfo.java index 450fe0c5df..6a80c23703 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/EnrolmentInfo.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/EnrolmentInfo.java @@ -21,7 +21,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; -import java.math.BigInteger; +import java.util.List; @ApiModel(value = "EnrolmentInfo", description = "This class carries all information related to a devices enrollment" + " status.") @@ -61,6 +61,9 @@ public class EnrolmentInfo implements Serializable { @ApiModelProperty(name = "owner", value = "The device owner's name.", required = true ) private String owner; + @ApiModelProperty(name = "tags", value = "Tags associated with enrolment.", required = false ) + private List tags; + public EnrolmentInfo() { } @@ -134,6 +137,14 @@ public class EnrolmentInfo implements Serializable { this.owner = owner; } + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + @Override public boolean equals(Object obj) { if (obj instanceof EnrolmentInfo) { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/Feature.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/Feature.java index 399389271e..a495acc279 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/Feature.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/Feature.java @@ -58,6 +58,13 @@ public class Feature implements Serializable { ) private String description; + @ApiModelProperty( + name = "tooltip", + value = "Provides a tooltip for the features.", + required = false + ) + private String tooltip; + @ApiModelProperty( name = "type", value = "Type of the feature.", @@ -86,6 +93,20 @@ public class Feature implements Serializable { ) private List metadataEntries; + @ApiModelProperty( + name = "confirmationTexts", + value = "Disenroll delete confirmation modal texts.", + required = false + ) + private ConfirmationTexts confirmationTexts; + + @ApiModelProperty( + name = "dangerZoneTooltipTexts", + value = "Danger zone tooltip texts.", + required = false + ) + private DangerZoneTooltipTexts dangerZoneTooltipTexts; + @XmlElement public int getId() { return id; @@ -139,6 +160,16 @@ public class Feature implements Serializable { this.description = description; } + @XmlElement + public String getTooltip() { + return tooltip; + } + + public void setTooltip(String tooltip) { + this.tooltip = tooltip; + } + + @XmlAttribute public String getType() { return type; @@ -156,6 +187,24 @@ public class Feature implements Serializable { this.hidden = hidden; } + @XmlElement + public ConfirmationTexts getConfirmationTexts() { + return confirmationTexts; + } + + public void setConfirmationTexts(ConfirmationTexts confirmationTexts) { + this.confirmationTexts = confirmationTexts; + } + + @XmlElement + public DangerZoneTooltipTexts getDangerZoneTooltipTexts() { + return dangerZoneTooltipTexts; + } + + public void setDangerZoneTooltipTexts(DangerZoneTooltipTexts dangerZoneTooltipTexts) { + this.dangerZoneTooltipTexts = dangerZoneTooltipTexts; + } + public static class MetadataEntry implements Serializable { private int id; @@ -186,4 +235,136 @@ public class Feature implements Serializable { this.value = value; } } + + public static class ConfirmationTexts implements Serializable { + private int id; + private String deleteConfirmModalTitle; + private String deleteConfirmModalText; + private String deleteConfirmationTextDescribe; + private String deleteConfirmationText; + private String cancelText; + private String confirmText; + private String inputLabel; + private String inputRequireMessage; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getCancelText() { + return cancelText; + } + + public void setCancelText(String cancelText) { + this.cancelText = cancelText; + } + + public String getConfirmText() { + return confirmText; + } + + public void setConfirmText(String confirmText) { + this.confirmText = confirmText; + } + + public String getInputLabel() { + return inputLabel; + } + + public void setInputLabel(String inputLabel) { + this.inputLabel = inputLabel; + } + + public String getInputRequireMessage() { + return inputRequireMessage; + } + + public void setInputRequireMessage(String inputRequireMessage) { + this.inputRequireMessage = inputRequireMessage; + } + + public String getDeleteConfirmModalTitle() { + return deleteConfirmModalTitle; + } + + public void setDeleteConfirmModalTitle(String deleteConfirmModalTitle) { + this.deleteConfirmModalTitle = deleteConfirmModalTitle; + } + + public String getDeleteConfirmModalText() { + return deleteConfirmModalText; + } + + public void setDeleteConfirmModalText(String deleteConfirmModalText) { + this.deleteConfirmModalText = deleteConfirmModalText; + } + + public String getDeleteConfirmationTextDescribe() { + return deleteConfirmationTextDescribe; + } + + public void setDeleteConfirmationTextDescribe(String deleteConfirmationTextDescribe) { + this.deleteConfirmationTextDescribe = deleteConfirmationTextDescribe; + } + + public String getDeleteConfirmationText() { + return deleteConfirmationText; + } + + public void setDeleteConfirmationText(String deleteConfirmationText) { + this.deleteConfirmationText = deleteConfirmationText; + } + } + + public static class DangerZoneTooltipTexts implements Serializable { + private String toolTipTitle; + private String toolTipPopConfirmText; + private String confirmText; + private String cancelText; + private String toolTipAvailable; + + public String getToolTipAvailable() { + return toolTipAvailable; + } + + public void setToolTipAvailable(String toolTipAvailable) { + this.toolTipAvailable = toolTipAvailable; + } + + public String getToolTipTitle() { + return toolTipTitle; + } + + public void setToolTipTitle(String toolTipTitle) { + this.toolTipTitle = toolTipTitle; + } + + public String getToolTipPopConfirmText() { + return toolTipPopConfirmText; + } + + public void setToolTipPopConfirmText(String toolTipPopConfirmText) { + this.toolTipPopConfirmText = toolTipPopConfirmText; + } + + public String getConfirmText() { + return confirmText; + } + + public void setConfirmText(String confirmText) { + this.confirmText = confirmText; + } + + public String getCancelText() { + return cancelText; + } + + public void setCancelText(String cancelText) { + this.cancelText = cancelText; + } + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/PaginationRequest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/PaginationRequest.java index c4e01eb282..5d54db3b28 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/PaginationRequest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/PaginationRequest.java @@ -18,11 +18,7 @@ package io.entgra.device.mgt.core.device.mgt.common; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; /** * This class holds required parameters for a querying a paginated device response. @@ -52,6 +48,7 @@ public class PaginationRequest { private Map customProperty = new HashMap<>(); private Map property = new HashMap<>(); private List statusList = new ArrayList<>(); + private List tags = new ArrayList<>(); private OperationLogFilters operationLogFilters = new OperationLogFilters(); private List sortColumn = new ArrayList<>(); private int deviceTypeId; @@ -199,6 +196,14 @@ public class PaginationRequest { public List getSortColumn() { return sortColumn; } + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + /** * Convert SortColumns field parameter and splitting string into columnName and sortType * diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/device/details/DeviceDetailsWrapper.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/device/details/DeviceDetailsWrapper.java index 4101f16b96..8f9f7ce0cd 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/device/details/DeviceDetailsWrapper.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/device/details/DeviceDetailsWrapper.java @@ -24,7 +24,6 @@ import io.entgra.device.mgt.core.device.mgt.common.app.mgt.Application; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; import java.util.List; -import java.util.Map; public class DeviceDetailsWrapper { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/device/details/DeviceLocation.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/device/details/DeviceLocation.java index 79918dd088..ee2395e390 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/device/details/DeviceLocation.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/device/details/DeviceLocation.java @@ -19,9 +19,9 @@ package io.entgra.device.mgt.core.device.mgt.common.device.details; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import java.io.Serializable; import java.util.Date; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/exceptions/MetadataKeyAlreadyExistsException.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/exceptions/MetadataKeyAlreadyExistsException.java index f138d5c12c..5feabe2708 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/exceptions/MetadataKeyAlreadyExistsException.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/exceptions/MetadataKeyAlreadyExistsException.java @@ -21,7 +21,7 @@ package io.entgra.device.mgt.core.device.mgt.common.exceptions; /** * Custom exception class to be used in MetadataMgmt related functionalities. */ -public class MetadataKeyAlreadyExistsException extends Exception { +public class MetadataKeyAlreadyExistsException extends MetadataManagementException { private static final long serialVersionUID = -1814347544027733436L; private String errorMessage; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/exceptions/MetadataKeyNotFoundException.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/exceptions/MetadataKeyNotFoundException.java index 965c1b757b..0f95bdaf05 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/exceptions/MetadataKeyNotFoundException.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/exceptions/MetadataKeyNotFoundException.java @@ -21,7 +21,7 @@ package io.entgra.device.mgt.core.device.mgt.common.exceptions; /** * Custom exception class to be used in MetadataMgmt related functionalities. */ -public class MetadataKeyNotFoundException extends Exception { +public class MetadataKeyNotFoundException extends MetadataManagementException { private static final long serialVersionUID = 5260831982626354815L; private String errorMessage; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/Alert.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/Alert.java index 61bfd6faa7..d5aa1d4203 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/Alert.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/Alert.java @@ -17,11 +17,7 @@ */ package io.entgra.device.mgt.core.device.mgt.common.geo.service; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.*; /** * The Class Alert Bean. diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/Event.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/Event.java index d462542e5f..377f62b857 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/Event.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/Event.java @@ -18,11 +18,7 @@ package io.entgra.device.mgt.core.device.mgt.common.geo.service; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.*; import java.util.ArrayList; import java.util.List; import java.util.Map; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/GeoLocationProviderService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/GeoLocationProviderService.java index c214971604..4a9da7c79c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/GeoLocationProviderService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/GeoLocationProviderService.java @@ -20,11 +20,9 @@ package io.entgra.device.mgt.core.device.mgt.common.geo.service; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; -import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfig; import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfigurationException; -import java.util.ArrayList; import java.util.List; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/GeofenceData.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/GeofenceData.java index b0e97bdb64..7e8c7636c8 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/GeofenceData.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/geo/service/GeofenceData.java @@ -19,7 +19,6 @@ package io.entgra.device.mgt.core.device.mgt.common.geo.service; import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfig; -import io.entgra.device.mgt.core.device.mgt.common.event.config.EventMetaData; import java.util.List; import java.util.Map; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/group/mgt/GroupUser.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/group/mgt/GroupUser.java index 28a459f78e..bb061024b7 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/group/mgt/GroupUser.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/group/mgt/GroupUser.java @@ -20,8 +20,6 @@ package io.entgra.device.mgt.core.device.mgt.common.group.mgt; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/metadata/mgt/DeviceStatusManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/metadata/mgt/DeviceStatusManagementService.java index 5ee7c8fce0..5abb9c7e88 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/metadata/mgt/DeviceStatusManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/metadata/mgt/DeviceStatusManagementService.java @@ -38,7 +38,7 @@ public interface DeviceStatusManagementService { * * @throws MetadataManagementException if error while resetting default device status */ - void resetToDefaultDeviceStausFilter() throws MetadataManagementException; + void resetToDefaultDeviceStatusFilter(int tenantId) throws MetadataManagementException; /** * This method is useful to update existing allowed device status diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/metadata/mgt/MetadataManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/metadata/mgt/MetadataManagementService.java index d02614ce2c..941377f04f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/metadata/mgt/MetadataManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/metadata/mgt/MetadataManagementService.java @@ -23,6 +23,7 @@ import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataKeyAlreadyExistsException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataKeyNotFoundException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; + import java.util.List; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/operation/mgt/ActivityStatus.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/operation/mgt/ActivityStatus.java index a90d69a8c1..a1d9c4f1c5 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/operation/mgt/ActivityStatus.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/operation/mgt/ActivityStatus.java @@ -20,9 +20,9 @@ package io.entgra.device.mgt.core.device.mgt.common.operation.mgt; import com.fasterxml.jackson.annotation.JsonProperty; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/operation/mgt/OperationManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/operation/mgt/OperationManager.java index e7fa23304e..f223c20ea5 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/operation/mgt/OperationManager.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/operation/mgt/OperationManager.java @@ -17,12 +17,7 @@ */ package io.entgra.device.mgt.core.device.mgt.common.operation.mgt; -import io.entgra.device.mgt.core.device.mgt.common.ActivityPaginationRequest; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.DynamicTaskContext; -import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; -import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; +import io.entgra.device.mgt.core.device.mgt.common.*; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidDeviceException; import io.entgra.device.mgt.core.device.mgt.common.push.notification.NotificationStrategy; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/policy/mgt/Policy.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/policy/mgt/Policy.java index c002a1648d..cd0aee7be7 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/policy/mgt/Policy.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/policy/mgt/Policy.java @@ -17,9 +17,9 @@ */ package io.entgra.device.mgt.core.device.mgt.common.policy.mgt; +import io.entgra.device.mgt.core.device.mgt.common.Device; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import io.entgra.device.mgt.core.device.mgt.common.Device; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/policy/mgt/ui/Modal.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/policy/mgt/ui/Modal.java index 8da35abdb6..093677b8e4 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/policy/mgt/ui/Modal.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/policy/mgt/ui/Modal.java @@ -18,7 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ui; -import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/policy/mgt/ui/SearchInput.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/policy/mgt/ui/SearchInput.java index 9491fbefc6..e098520725 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/policy/mgt/ui/SearchInput.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/policy/mgt/ui/SearchInput.java @@ -19,9 +19,7 @@ package io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ui; import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; -import java.util.List; @XmlRootElement(name = "SearchInput") public class SearchInput { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/report/mgt/ReportManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/report/mgt/ReportManagementService.java index 747fd8ec60..0874fed6ff 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/report/mgt/ReportManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/report/mgt/ReportManagementService.java @@ -20,7 +20,6 @@ package io.entgra.device.mgt.core.device.mgt.common.report.mgt; import com.google.gson.JsonObject; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; -import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ApplicationManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.BadRequestException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceTypeNotFoundException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.ReportManagementException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/tag/mgt/DeviceTag.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/tag/mgt/DeviceTag.java new file mode 100644 index 0000000000..f60dbe2aed --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/tag/mgt/DeviceTag.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.common.tag.mgt; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * DTO of DeviceTag object which is used to manage Device Tags. + */ + +@ApiModel(value = "DeviceTag", description = "This is used to manage device tags.") +public class DeviceTag { + + @ApiModelProperty(name = "enrolmentId", value = "Defines the device id.", required = true) + private int enrolmentId; + + @ApiModelProperty(name = "tagId", value = "Defines the tag id.", required = true) + private int tagId; + + public int getEnrolmentId() { + return enrolmentId; + } + + public void setEnrolmentId(int enrolmentId) { + this.enrolmentId = enrolmentId; + } + + public int getTagId() { + return tagId; + } + + public void setTagId(int tagId) { + this.tagId = tagId; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/tag/mgt/Tag.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/tag/mgt/Tag.java new file mode 100644 index 0000000000..ba2ffecf16 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/tag/mgt/Tag.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.common.tag.mgt; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * DTO of Tag object which is used to manage Tags in devices. + */ + +@ApiModel(value = "Tag", description = "This is used to manage tags in devices.") +public class Tag { + + @ApiModelProperty(name = "id", value = "Defines the tag ID.", required = false) + private int id; + + @ApiModelProperty(name = "name", value = "Defines the tag name.", required = true) + private String name; + + @ApiModelProperty(name = "description", value = "Defines the tag description.", required = false) + private String description; + + public Tag(String name, String description) { + this.name = name; + this.description = description; + } + + public Tag() {} + + public Tag(int id, String name, String description) { + this.id = id; + this.name = name; + this.description = description; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public String toString() { + return "tag {" + + " id= " + id + + ", name= '" + name + '\'' + + ", description= '" + description + '\'' + + '}'; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/tag/mgt/TagManagementException.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/tag/mgt/TagManagementException.java new file mode 100644 index 0000000000..f8c0755d65 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/tag/mgt/TagManagementException.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.common.tag.mgt; + +/** + * Custom exception class to be used in TagManagement related functionalities. + */ +public class TagManagementException extends Exception { + + private static final long serialVersionUID = -8933146283800122660L; + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public TagManagementException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public TagManagementException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public TagManagementException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public TagManagementException() { + super(); + } + + public TagManagementException(Throwable cause) { + super(cause); + } + +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/tag/mgt/TagMappingDTO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/tag/mgt/TagMappingDTO.java new file mode 100644 index 0000000000..3bfe899cf2 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/tag/mgt/TagMappingDTO.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.common.tag.mgt; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.List; + +/** + * DTO of TagMapping object which is used to manage Device Tags. + */ + +@ApiModel(value = "TagMappingDTO", description = "This is used to manage device tags.") +public class TagMappingDTO { + + @ApiModelProperty(name = "deviceIdentifiers", value = "Defines the device identifiers.", required = true) + private List deviceIdentifiers; + + @ApiModelProperty(name = "deviceType", value = "Defines the device type.", required = true) + private String deviceType; + + @ApiModelProperty(name = "tags", value = "Defines the tag.", required = true) + private List tags; + + public TagMappingDTO() {} + + public TagMappingDTO(List deviceIdentifiers, String deviceType, List tags) { + this.deviceIdentifiers = deviceIdentifiers; + this.deviceType = deviceType; + this.tags = tags; + } + + public List getDeviceIdentifiers() { + return deviceIdentifiers; + } + + public void setDeviceIdentifiers(List deviceIdentifiers) { + this.deviceIdentifiers = deviceIdentifiers; + } + + public String getDeviceType() { + return deviceType; + } + + public void setDeviceType(String deviceType) { + this.deviceType = deviceType; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/tag/mgt/TagNotFoundException.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/tag/mgt/TagNotFoundException.java new file mode 100644 index 0000000000..f80e41c096 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/tag/mgt/TagNotFoundException.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.common.tag.mgt; + +/** + * Custom exception class to be used in TagManagement related functionalities. + */ +public class TagNotFoundException extends Exception { + + private static final long serialVersionUID = -8933146283800122660L; + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public TagNotFoundException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public TagNotFoundException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public TagNotFoundException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public TagNotFoundException() { + super(); + } + + public TagNotFoundException(Throwable cause) { + super(cause); + } + +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java index e89fe58ab2..2a24f97e42 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java @@ -23,7 +23,6 @@ import io.entgra.device.mgt.core.device.mgt.common.InitialOperationConfig; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.License; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationConfig; -import java.util.ArrayList; import java.util.List; public class DeviceTypeMetaDefinition { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/pom.xml index 05f6beeeba..62e006db4b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/pom.xml @@ -37,10 +37,7 @@ maven-compiler-plugin - - 1.8 - 1.8 - + maven-war-plugin @@ -79,12 +76,20 @@ org.apache.maven.plugins maven-surefire-plugin - - file:src/test/resources/log4j.properties - + + --add-opens=java.xml/jdk.xml.internal=ALL-UNNAMED + --add-opens=java.base/jdk.internal.loader=ALL-UNNAMED + src/test/resources/testng.xml + + ${basedir}/target/coverage-reports/jacoco-unit.exec + file:src/test/resources/log4j.properties + + + org.ops4j.pax.logging + @@ -99,7 +104,6 @@ org.apache.maven.plugins maven-antrun-plugin - 1.7 compile @@ -129,7 +133,6 @@ org.codehaus.mojo exec-maven-plugin - 1.2.1 test @@ -177,6 +180,10 @@ javassist javassist + + org.wso2.orbit.javax.xml.bind + jaxb-api + @@ -194,6 +201,11 @@ + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.device.mgt.common + provided + io.swagger swagger-annotations @@ -255,7 +267,7 @@ org.powermock - powermock-api-mockito + powermock-api-mockito2 test diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/ApiOriginFilter.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/ApiOriginFilter.java index 32b6cb52cc..75bc8e9805 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/ApiOriginFilter.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/ApiOriginFilter.java @@ -18,12 +18,7 @@ package io.entgra.device.mgt.core.device.mgt.config.api; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/common/GsonMessageBodyHandler.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/common/GsonMessageBodyHandler.java index dfd02e3007..9bc6e7748c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/common/GsonMessageBodyHandler.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/common/GsonMessageBodyHandler.java @@ -29,11 +29,7 @@ import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; +import java.io.*; import java.lang.annotation.Annotation; import java.lang.reflect.Type; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/service/DeviceManagementConfigService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/service/DeviceManagementConfigService.java index 63467ddb28..97627393d5 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/service/DeviceManagementConfigService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/service/DeviceManagementConfigService.java @@ -18,32 +18,16 @@ package io.entgra.device.mgt.core.device.mgt.config.api.service; -import io.entgra.device.mgt.core.device.mgt.common.DeviceTransferRequest; -import io.entgra.device.mgt.core.device.mgt.config.api.beans.ErrorResponse; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; +import io.entgra.device.mgt.core.device.mgt.common.DeviceTransferRequest; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.DeviceConfiguration; import io.entgra.device.mgt.core.device.mgt.common.general.TenantDetail; +import io.entgra.device.mgt.core.device.mgt.config.api.beans.ErrorResponse; +import io.swagger.annotations.*; +import io.entgra.device.mgt.core.device.mgt.core.operation.change.status.task.dto.OperationConfig; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; @@ -94,6 +78,13 @@ import java.util.List; key = "admin:permissions:add", roles = {"Internal/devicemgt-user"}, permissions = {"/permissions/add"} + ), + @Scope( + name = "Manage operation configuration", + description = "Add or update operation configuration", + key = "admin:operation_config:manage", + roles = {"Internal/devicemgt-user"}, + permissions = {"/operation-configuration/manage"} ) } ) @@ -336,4 +327,173 @@ public interface DeviceManagementConfigService { }) @Produces(MediaType.APPLICATION_JSON) Response addPermission(List permissions); + + @GET + @Path("/operation-configuration") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HttpMethod.GET, + value = "Getting operation configuration", + notes = "Retrieve the operation configuration", + tags = "Device Management Configuration", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = "scope", value = "admin:operation_config:manage") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully fetched the operation configuration.", + response = OperationConfig.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource was last modified.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 400, + message = "Bad Request.", + response = ErrorResponse.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Unauthorized operation! Only admin role can perform this operation."), + @ApiResponse( + code = 404, + message = "Not Found. \n No operation found", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while adding operation configuration.", + response = ErrorResponse.class) + }) + Response getOperationConfiguration(); + + @POST + @Path("/operation-configuration") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HttpMethod.POST, + value = "Add operation configuration", + notes = "Add operation configuration.", + tags = "Device Management Configuration", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = "scope", value = + "admin:operation_config:manage") + }) + } + ) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully added the operation configuration.", + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource was last modified.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 400, + message = "The incoming request has wrong operation configuration.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while adding operation configuration", + response = ErrorResponse.class) + }) + @Produces(MediaType.APPLICATION_JSON) + Response addOperationConfiguration(OperationConfig config); + + @PUT + @Path("/operation-configuration") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HttpMethod.PUT, + value = "Update operation configuration", + notes = "Update operation configuration.", + tags = "Device Management Configuration", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = "scope", value = "admin:operation_config:manage") + }) + } + ) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully Update the operation configuration.", + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource was last modified.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 400, + message = "The incoming request has wrong operation configuration.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while adding operation configuration.", + response = ErrorResponse.class) + }) + @Produces(MediaType.APPLICATION_JSON) + Response updateOperationConfiguration(OperationConfig config); + + @DELETE + @Path("/operation-configuration") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HttpMethod.DELETE, + value = "Delete operation configuration", + notes = "Delete operation configuration", + tags = {"Device Management Configuration"}, + extensions = { + @Extension(properties = { + @ExtensionProperty(name = "scope", value = "admin:operation_config:manage") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully deleted the operation configuration", + response = Response.class), + @ApiResponse( + code = 400, + message = "Bad Request.", + response = Response.class), + @ApiResponse( + code = 404, + message = "Not Found. \n Operation configuration not provided", + response = Response.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while deleting the operation configuration.", + response = Response.class) + } + ) + Response deleteOperationConfiguration(); } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/service/impl/DeviceManagementConfigServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/service/impl/DeviceManagementConfigServiceImpl.java index c7b191704e..b394f36b78 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/service/impl/DeviceManagementConfigServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/service/impl/DeviceManagementConfigServiceImpl.java @@ -21,14 +21,13 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.OTPManagementException; -import io.entgra.device.mgt.core.device.mgt.common.otp.mgt.OTPEmailTypes; -import io.entgra.device.mgt.core.device.mgt.common.otp.mgt.dto.OneTimePinDTO; -import io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService; -import io.entgra.device.mgt.core.device.mgt.config.api.beans.ErrorResponse; -import io.entgra.device.mgt.core.device.mgt.config.api.service.DeviceManagementConfigService; -import io.entgra.device.mgt.core.device.mgt.config.api.util.DeviceMgtAPIUtils; import org.apache.commons.logging.Log; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.OTPManagementException; +import io.entgra.device.mgt.core.device.mgt.core.operation.change.status.task.OperationConfigurationService; +import io.entgra.device.mgt.core.device.mgt.core.operation.change.status.task.dto.OperationConfig; +import io.entgra.device.mgt.core.device.mgt.core.operation.change.status.task.exceptions.OperationConfigAlreadyExistsException; +import io.entgra.device.mgt.core.device.mgt.core.operation.change.status.task.exceptions.OperationConfigException; +import io.entgra.device.mgt.core.device.mgt.core.operation.change.status.task.exceptions.OperationConfigNotFoundException; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -41,6 +40,13 @@ import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementEx import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceNotFoundException; import io.entgra.device.mgt.core.device.mgt.common.general.TenantDetail; import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.OTPManagementException; +import io.entgra.device.mgt.core.device.mgt.common.otp.mgt.OTPEmailTypes; +import io.entgra.device.mgt.core.device.mgt.common.otp.mgt.dto.OneTimePinDTO; +import io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService; +import io.entgra.device.mgt.core.device.mgt.config.api.beans.ErrorResponse; +import io.entgra.device.mgt.core.device.mgt.config.api.service.DeviceManagementConfigService; +import io.entgra.device.mgt.core.device.mgt.config.api.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.core.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; @@ -61,6 +67,7 @@ import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; +import javax.ws.rs.DELETE; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; @@ -313,4 +320,89 @@ public class DeviceManagementConfigServiceImpl implements DeviceManagementConfig return Response.status(Response.Status.OK).build(); } + @GET + @Path("/operation-configuration") + @Produces({MediaType.APPLICATION_JSON}) + public Response getOperationConfiguration() { + OperationConfig config; + try { + config = OperationConfigurationService.getOperationConfig(); + } catch (OperationConfigException e) { + String msg = "Error occurred getting operation configuration"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } + if (config == null) { + String msg = "Operation configuration not provided"; + log.error(msg); + return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); + } else { + return Response.status(Response.Status.OK).entity(config).build(); + } + } + + @POST + @Path("/operation-configuration") + @Produces({MediaType.APPLICATION_JSON}) + public Response addOperationConfiguration(OperationConfig config) { + try { + if (config != null) { + OperationConfigurationService.addOperationConfiguration(config); + } else { + String msg = "Operation configuration not provided"; + log.error(msg); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } + } catch (OperationConfigException e) { + String msg = "Error occurred adding operation configuration"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (OperationConfigAlreadyExistsException e) { + String msg = "Operation configuration already exists"; + log.error(msg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } + return Response.status(Response.Status.OK).entity(config).build(); + } + + @PUT + @Path("/operation-configuration") + @Produces({MediaType.APPLICATION_JSON}) + public Response updateOperationConfiguration(OperationConfig config) { + try { + if (config != null) { + OperationConfigurationService.updateOperationConfiguration(config); + } else { + String msg = "Operation configuration body not provided"; + log.error(msg); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } + } catch (OperationConfigException e) { + String msg = "Error occurred adding operation configuration"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).entity(config).build(); + } + + @DELETE + @Path("/operation-configuration") + @Produces({MediaType.APPLICATION_JSON}) + public Response deleteOperationConfiguration() { + String msg; + try { + OperationConfigurationService.deleteOperationConfiguration(); + } catch (OperationConfigException e) { + msg = "Error occurred while deleting operation configuration"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (OperationConfigNotFoundException e) { + msg = "Operation configuration not provided"; + log.error(msg, e); + return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); + } + msg = "Operation configuration deleted successfully"; + log.info(msg); + return Response.status(Response.Status.OK).entity(msg).build(); + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/util/DeviceMgtAPIUtils.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/util/DeviceMgtAPIUtils.java index c958b79e3d..4a2a416e92 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/util/DeviceMgtAPIUtils.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/util/DeviceMgtAPIUtils.java @@ -18,11 +18,11 @@ package io.entgra.device.mgt.core.device.mgt.config.api.util; +import io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.user.core.service.RealmService; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/pom.xml index fdd6b0c25b..00788c96f4 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/pom.xml @@ -31,14 +31,10 @@ bundle WSO2 Carbon - Device Management Core WSO2 Carbon - Device Management Core - http://wso2.org + https://entgra.io - - org.apache.felix - maven-scr-plugin - org.jacoco jacoco-maven-plugin @@ -65,6 +61,14 @@ + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + org.apache.felix maven-bundle-plugin @@ -77,45 +81,205 @@ Device Management Core Bundle io.entgra.device.mgt.core.device.mgt.core.internal - org.apache.axis2.*;version="${axis2.osgi.version.range}", + com.fasterxml.jackson.databind;version="[2.14,3)", + com.google.common.collect;version="[32.1,33)";resolution:=optional, + com.google.common.reflect;version="[32.1,33)";resolution:=optional, + com.google.gson;version="[2.9,3)", + com.google.gson.reflect;version="[2.9,3)", + io.entgra.device.mgt.core.apimgt.annotations;version="[5.0,6)", + io.entgra.device.mgt.core.apimgt.extension.rest.api;version="[5.0,6)", + io.entgra.device.mgt.core.apimgt.extension.rest.api.dto;version="[5.0,6)", + io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;version="[5.0,6)", + io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions;version="[5.0,6)", + io.entgra.device.mgt.core.apimgt.extension.rest.api.util;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.app.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.app.mgt.android;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.app.mgt.ios;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.app.mgt.windows;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.authorization;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.configuration.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.cost.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.device.details;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.enrollment.notification;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.event.config;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.exceptions;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.general;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.geo.service;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.group.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.invitation.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.license.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.metadata.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.notification.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.operation.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.otp.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.otp.mgt.dto;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.permission.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.policy.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.pull.notification;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.push.notification;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.report.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.roles.config;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.search;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.spi;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.type.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.app.mgt.config, + io.entgra.device.mgt.core.device.mgt.core.archival, + io.entgra.device.mgt.core.device.mgt.core.archival.dao, + io.entgra.device.mgt.core.device.mgt.core.archival.dao.impl, + io.entgra.device.mgt.core.device.mgt.core.cache, + io.entgra.device.mgt.core.device.mgt.core.cache.impl, + io.entgra.device.mgt.core.device.mgt.core.common.exception, + io.entgra.device.mgt.core.device.mgt.core.common.util, + io.entgra.device.mgt.core.device.mgt.core.config, + io.entgra.device.mgt.core.device.mgt.core.config.analytics, + io.entgra.device.mgt.core.device.mgt.core.config.analytics.operation, + io.entgra.device.mgt.core.device.mgt.core.config.archival, + io.entgra.device.mgt.core.device.mgt.core.config.cache, + io.entgra.device.mgt.core.device.mgt.core.config.datasource, + io.entgra.device.mgt.core.device.mgt.core.config.enrollment.guide, + io.entgra.device.mgt.core.device.mgt.core.config.geo.location, + io.entgra.device.mgt.core.device.mgt.core.config.identity, + io.entgra.device.mgt.core.device.mgt.core.config.keymanager, + io.entgra.device.mgt.core.device.mgt.core.config.license, + io.entgra.device.mgt.core.device.mgt.core.config.metadata.mgt, + io.entgra.device.mgt.core.device.mgt.core.config.metadata.mgt.documentation, + io.entgra.device.mgt.core.device.mgt.core.config.metadata.mgt.whitelabel, + io.entgra.device.mgt.core.device.mgt.core.config.operation.timeout, + io.entgra.device.mgt.core.device.mgt.core.config.pagination, + io.entgra.device.mgt.core.device.mgt.core.config.permission, + io.entgra.device.mgt.core.device.mgt.core.config.policy, + io.entgra.device.mgt.core.device.mgt.core.config.pull.notification, + io.entgra.device.mgt.core.device.mgt.core.config.push.notification, + io.entgra.device.mgt.core.device.mgt.core.config.remote.session, + io.entgra.device.mgt.core.device.mgt.core.config.status.task, + io.entgra.device.mgt.core.device.mgt.core.config.task, + io.entgra.device.mgt.core.device.mgt.core.config.tenant, + io.entgra.device.mgt.core.device.mgt.core.config.ui, + io.entgra.device.mgt.core.device.mgt.core.dao, + io.entgra.device.mgt.core.device.mgt.core.dao.impl, + io.entgra.device.mgt.core.device.mgt.core.dao.impl.device, + io.entgra.device.mgt.core.device.mgt.core.dao.impl.enrolment, + io.entgra.device.mgt.core.device.mgt.core.dao.impl.event, + io.entgra.device.mgt.core.device.mgt.core.dao.impl.geofence, + io.entgra.device.mgt.core.device.mgt.core.dao.impl.group, + io.entgra.device.mgt.core.device.mgt.core.dao.impl.tracker, + io.entgra.device.mgt.core.device.mgt.core.device.details.mgt, + io.entgra.device.mgt.core.device.mgt.core.device.details.mgt.dao, + io.entgra.device.mgt.core.device.mgt.core.device.details.mgt.dao.impl, + io.entgra.device.mgt.core.device.mgt.core.dto, + io.entgra.device.mgt.core.device.mgt.core.dto.event.config, + io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt, + io.entgra.device.mgt.core.device.mgt.core.geo.geoHash, + io.entgra.device.mgt.core.device.mgt.core.geo.task, + io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao, + io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.impl, + io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.util, + io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.util, + io.entgra.device.mgt.core.device.mgt.core.notification.mgt.dao, + io.entgra.device.mgt.core.device.mgt.core.notification.mgt.dao.impl, + io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao, + io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl, + io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl.operation, + io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.util, + io.entgra.device.mgt.core.device.mgt.core.operation.mgt.util, + io.entgra.device.mgt.core.device.mgt.core.operation.timeout.task, + io.entgra.device.mgt.core.device.mgt.core.otp.mgt.dao, + io.entgra.device.mgt.core.device.mgt.core.otp.mgt.dao.impl, + io.entgra.device.mgt.core.device.mgt.core.otp.mgt.exception, + io.entgra.device.mgt.core.device.mgt.core.otp.mgt.util, + io.entgra.device.mgt.core.device.mgt.core.privacy, + io.entgra.device.mgt.core.device.mgt.core.privacy.dao, + io.entgra.device.mgt.core.device.mgt.core.privacy.dao.impl, + io.entgra.device.mgt.core.device.mgt.core.report.mgt, + io.entgra.device.mgt.core.device.mgt.core.report.mgt.config, + io.entgra.device.mgt.core.device.mgt.core.search.mgt, + io.entgra.device.mgt.core.device.mgt.core.search.mgt.dao, + io.entgra.device.mgt.core.device.mgt.core.status.task, + io.entgra.device.mgt.core.device.mgt.core.task, + io.entgra.device.mgt.core.device.mgt.core.traccar.api.service, + io.entgra.device.mgt.core.device.mgt.core.traccar.api.service.impl, + io.entgra.device.mgt.core.device.mgt.core.traccar.common.beans, + io.entgra.device.mgt.core.device.mgt.core.traccar.common.config, + io.entgra.device.mgt.core.device.mgt.core.traccar.common.util, + io.entgra.device.mgt.core.device.mgt.core.traccar.core.config, + io.entgra.device.mgt.core.device.mgt.extensions.logger;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.extensions.logger.spi;version="[5.0,6)", + io.entgra.device.mgt.core.identity.jwt.client.extension;version="[5.0,6)", + io.entgra.device.mgt.core.identity.jwt.client.extension.dto;version="[5.0,6)", + io.entgra.device.mgt.core.identity.jwt.client.extension.exception;version="[5.0,6)", + io.entgra.device.mgt.core.identity.jwt.client.extension.service;version="[5.0,6)", + io.entgra.device.mgt.core.notification.logger;version="[5.0,6)", + io.entgra.device.mgt.core.notification.logger.impl;version="[5.0,6)", + io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception;version="[5.0,6)", + io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service;version="[5.0,6)", + io.entgra.device.mgt.core.transport.mgt.email.sender.core;version="[5.0,6)", + io.entgra.device.mgt.core.transport.mgt.email.sender.core.service;version="[5.0,6)", + io.swagger.annotations;version="[1.6,2)", + javax.cache;version="[1.0,2)", + javax.naming, + javax.net.ssl, + javax.servlet;version="[2.6,3)", + javax.sql, + javax.ws.rs, + javax.xml.bind;version="[0.0,1)", + javax.xml.bind.annotation;version="[0.0,1)", + javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}", + javax.xml.stream;version="[1.0,2)", + okhttp3, + org.apache.axis2;version="[1.6,2)", + org.apache.axis2.client;version="[1.6,2)", + org.apache.axis2.context;version="[1.6,2)", + org.apache.axis2.java.security;version="[1.6,2)", + org.apache.axis2.transport.http;version="[1.6,2)", + org.apache.catalina;version="${catalina.version.range}", + org.apache.catalina.core;version="${catalina.version.range}", + org.apache.commons.codec.binary;version="[1.4,2)", + org.apache.commons.collections.map;version="[3.2,4)", + org.apache.commons.httpclient;version="[3.1,4)", + org.apache.commons.httpclient.protocol;version="[3.1,4)", + org.apache.commons.io;version="[2.0,3)", + org.apache.commons.lang;version="[2.6,3)", + org.apache.commons.lang3;version="[3.11,4)", + org.apache.commons.logging;version="[1.2,2)", + org.apache.commons.validator.routines;version="[1.7,2)", + org.apache.http;version="[4.4,5)", + org.apache.http.client.methods;version="[4.3,5)", + org.apache.http.entity;version="[4.4,5)", + org.apache.http.impl.client;version="[4.3,5)", + org.apache.http.util;version="[4.4,5)", + org.apache.solr.common;version="[8.11,9)", + org.json;version="[3.0,4)", org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.apache.commons.logging, - javax.naming, - javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, - javax.servlet.*, - org.xml.sax, - javax.sql.*, - org.wso2.carbon.context, - org.wso2.carbon.core, - org.wso2.carbon.utils.*, - io.entgra.device.mgt.core.device.mgt.common.*, - org.wso2.carbon.user.api, - org.wso2.carbon.user.core.*, - org.wso2.carbon.registry.core.service, - org.wso2.carbon.registry.core, - org.wso2.carbon.registry.core.exceptions, - org.wso2.carbon.registry.core.session, - org.wso2.carbon.registry.api, - org.w3c.dom, - org.wso2.carbon.identity.oauth.stub, - org.wso2.carbon.identity.oauth.stub.dto, - org.wso2.carbon.ndatasource.core, - org.wso2.carbon.ntask.core.*, - org.wso2.carbon.ntask.common, - io.entgra.device.mgt.core.task.mgt.common.*, - org.apache.commons.collections;version="${commons-collections.version.range}", - io.entgra.device.mgt.core.email.sender.*, - io.swagger.annotations.*;resolution:=optional, - org.wso2.carbon, - org.wso2.carbon.base, - org.scannotation.*, - org.wso2.carbon.event.processor.stub, - io.entgra.device.mgt.core.identity.jwt.client.extension.service, - org.apache.commons.codec.binary, - io.entgra.device.mgt.core.server.bootup.heartbeat.beacon, - io.entgra.device.mgt.core.device.mgt.extensions.logger.*, - io.entgra.device.mgt.core.notification.logger.* + org.scannotation;version="[1.0,2)", + org.scannotation.archiveiterator;version="[1.0,2)", + org.w3c.dom,org.wso2.carbon.base;version="[1.0,2)", + org.wso2.carbon.caching.impl;version="[4.6,5)", + org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.core;version="[4.8,5)", + org.wso2.carbon.core.util;version="[4.8,5)", + org.wso2.carbon.event.processor.stub;version="[2.3,3)", + org.wso2.carbon.event.processor.stub.types;version="[2.3,3)", + org.wso2.carbon.ndatasource.core;version="[4.8,5)", + org.wso2.carbon.ntask.common;version="[4.9,5)", + org.wso2.carbon.ntask.core;version="[4.9,5)", + org.wso2.carbon.ntask.core.service;version="[4.9,5)", + org.wso2.carbon.registry.api;version="[1.0,2)", + org.wso2.carbon.registry.core;version="[1.0,2)", + org.wso2.carbon.registry.core.exceptions;version="[1.0,2)", + org.wso2.carbon.registry.core.service;version="[1.0,2)", + org.wso2.carbon.registry.core.session;version="[1.0,2)", + org.wso2.carbon.stratos.common.beans;version="[4.7,5)", + org.wso2.carbon.stratos.common.util;version="[4.7,5)", + org.wso2.carbon.tenant.mgt.exception;version="[4.9,5)", + org.wso2.carbon.tenant.mgt.services;version="[4.9,5)", + org.wso2.carbon.user.api;version="[1.0,2)", + org.wso2.carbon.user.core.config;version="[4.8,5)", + org.wso2.carbon.user.core.service;version="[4.8,5)", + org.wso2.carbon.user.core.tenant;version="[4.8,5)", + org.wso2.carbon.utils;version="[4.8,5)", + org.wso2.carbon.utils.dbcreator;version="[4.8,5)" !io.entgra.device.mgt.core.device.mgt.core.internal, @@ -149,15 +313,12 @@ - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services + org.apache.felix + org.apache.felix.scr.ds-annotations + provided - org.wso2.orbit.org.scannotation + io.entgra.org.scannotation scannotation @@ -165,8 +326,9 @@ io.entgra.device.mgt.core.device.mgt.common - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api + provided org.wso2.carbon @@ -187,8 +349,8 @@ - com.h2database.wso2 - h2-database-engine + org.wso2.orbit.com.h2database + h2 test @@ -211,13 +373,15 @@ org.wso2.carbon org.wso2.carbon.registry.api + provided org.wso2.carbon org.wso2.carbon.registry.core + provided - org.apache.tomcat.wso2 + org.wso2.orbit.org.apache.tomcat jdbc-pool @@ -236,14 +400,6 @@ org.apache.ws.commons.axiom.wso2 axiom - org.apache.axis2.wso2 axis2 @@ -253,11 +409,11 @@ org.wso2.carbon.identity.oauth.stub - org.wso2.tomcat + org.wso2.orbit.org.apache.tomcat tomcat - org.wso2.tomcat + org.wso2.orbit.org.apache.tomcat tomcat-servlet-api @@ -324,10 +480,11 @@ org.javassist javassist + provided org.powermock - powermock-api-mockito + powermock-api-mockito2 org.wso2.carbon.multitenancy @@ -344,6 +501,7 @@ com.google.guava guava + provided com.squareup.okhttp3 @@ -361,10 +519,21 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.notification.logger + org.wso2.orbit.javax.xml.bind jaxb-api + provided + + + com.sun.xml.bind + jaxb-core + compile + + + com.sun.xml.bind + jaxb-impl compile @@ -372,6 +541,5 @@ io.entgra.device.mgt.core.apimgt.extension.rest.api - diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementPluginRepository.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementPluginRepository.java index 6ad7b53c74..9f58717c7d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementPluginRepository.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementPluginRepository.java @@ -18,14 +18,11 @@ package io.entgra.device.mgt.core.device.mgt.core; import com.google.gson.Gson; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.DeviceStatusTaskPluginConfig; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidConfigurationException; import io.entgra.device.mgt.core.device.mgt.common.OperationMonitoringTaskConfig; import io.entgra.device.mgt.core.device.mgt.common.ProvisioningConfig; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidConfigurationException; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManager; import io.entgra.device.mgt.core.device.mgt.common.pull.notification.PullNotificationSubscriber; import io.entgra.device.mgt.core.device.mgt.common.push.notification.NotificationStrategy; @@ -49,6 +46,9 @@ import io.entgra.device.mgt.core.device.mgt.core.status.task.impl.DeviceStatusTa import io.entgra.device.mgt.core.device.mgt.core.task.DeviceMgtTaskException; import io.entgra.device.mgt.core.device.mgt.core.task.DeviceTaskManagerService; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.util.Collections; import java.util.HashMap; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java index 368157ca48..240ebad171 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java @@ -26,12 +26,12 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.app.mgt.Application; +import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ApplicationManagementException; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceDetailsWrapper; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidDeviceException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; -import io.entgra.device.mgt.core.device.mgt.common.app.mgt.Application; -import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ApplicationManagementException; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManagementException; @@ -42,6 +42,10 @@ import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOExceptio import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import io.entgra.device.mgt.core.device.mgt.core.util.HttpReportingUtil; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; import java.sql.SQLException; import java.util.ArrayList; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/config/AppManagementConfigurationManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/config/AppManagementConfigurationManager.java index 3e09b59daf..5f45417d77 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/config/AppManagementConfigurationManager.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/config/AppManagementConfigurationManager.java @@ -18,9 +18,9 @@ package io.entgra.device.mgt.core.device.mgt.core.app.mgt.config; -import org.w3c.dom.Document; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ApplicationManagementException; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; +import org.w3c.dom.Document; import org.wso2.carbon.utils.CarbonUtils; import javax.xml.bind.JAXBContext; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/oauth/ServiceAuthenticator.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/oauth/ServiceAuthenticator.java index a096d6ed15..e54ba4aa89 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/oauth/ServiceAuthenticator.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/oauth/ServiceAuthenticator.java @@ -18,10 +18,10 @@ package io.entgra.device.mgt.core.device.mgt.core.app.mgt.oauth; +import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ApplicationManagementException; import org.apache.axis2.client.Options; import org.apache.axis2.client.ServiceClient; import org.apache.axis2.transport.http.HttpTransportProperties; -import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ApplicationManagementException; /** * Authenticate a given service client. diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/ArchivalServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/ArchivalServiceImpl.java index 1af72b81bd..a478404422 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/ArchivalServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/ArchivalServiceImpl.java @@ -18,15 +18,11 @@ package io.entgra.device.mgt.core.device.mgt.core.archival; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; -import io.entgra.device.mgt.core.device.mgt.core.archival.dao.ArchivalDAO; -import io.entgra.device.mgt.core.device.mgt.core.archival.dao.ArchivalDAOException; -import io.entgra.device.mgt.core.device.mgt.core.archival.dao.ArchivalDestinationDAOFactory; -import io.entgra.device.mgt.core.device.mgt.core.archival.dao.ArchivalSourceDAOFactory; -import io.entgra.device.mgt.core.device.mgt.core.archival.dao.DataDeletionDAO; +import io.entgra.device.mgt.core.device.mgt.core.archival.dao.*; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.SQLException; import java.sql.Timestamp; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/dao/ArchivalDestinationDAOFactory.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/dao/ArchivalDestinationDAOFactory.java index 44642c4ce9..9beb7dac6c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/dao/ArchivalDestinationDAOFactory.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/dao/ArchivalDestinationDAOFactory.java @@ -18,8 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.archival.dao; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; import io.entgra.device.mgt.core.device.mgt.core.archival.dao.impl.DataDeletionDAOImpl; @@ -28,6 +26,8 @@ import io.entgra.device.mgt.core.device.mgt.core.config.datasource.DataSourceCon import io.entgra.device.mgt.core.device.mgt.core.config.datasource.JNDILookupDefinition; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.sql.DataSource; import java.sql.Connection; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/dao/ArchivalSourceDAOFactory.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/dao/ArchivalSourceDAOFactory.java index a8964ef616..e04e3fe74e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/dao/ArchivalSourceDAOFactory.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/dao/ArchivalSourceDAOFactory.java @@ -18,8 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.archival.dao; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; import io.entgra.device.mgt.core.device.mgt.core.archival.dao.impl.ArchivalDAOImpl; @@ -29,6 +27,8 @@ import io.entgra.device.mgt.core.device.mgt.core.config.datasource.DataSourceCon import io.entgra.device.mgt.core.device.mgt.core.config.datasource.JNDILookupDefinition; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.sql.DataSource; import java.sql.Connection; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/dao/impl/ArchivalDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/dao/impl/ArchivalDAOImpl.java index 2efe723785..1f085745f4 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/dao/impl/ArchivalDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/dao/impl/ArchivalDAOImpl.java @@ -18,21 +18,12 @@ package io.entgra.device.mgt.core.device.mgt.core.archival.dao.impl; +import io.entgra.device.mgt.core.device.mgt.core.archival.dao.*; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.core.archival.dao.ArchivalDAO; -import io.entgra.device.mgt.core.device.mgt.core.archival.dao.ArchivalDAOException; -import io.entgra.device.mgt.core.device.mgt.core.archival.dao.ArchivalDAOUtil; -import io.entgra.device.mgt.core.device.mgt.core.archival.dao.ArchivalDestinationDAOFactory; -import io.entgra.device.mgt.core.device.mgt.core.archival.dao.ArchivalSourceDAOFactory; -import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; +import java.sql.*; import java.util.ArrayList; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/dao/impl/DataDeletionDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/dao/impl/DataDeletionDAOImpl.java index 8d4f90c975..fc959b6ea0 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/dao/impl/DataDeletionDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/dao/impl/DataDeletionDAOImpl.java @@ -18,13 +18,13 @@ package io.entgra.device.mgt.core.device.mgt.core.archival.dao.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.core.archival.dao.ArchivalDAOException; import io.entgra.device.mgt.core.device.mgt.core.archival.dao.ArchivalDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.archival.dao.ArchivalDestinationDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.archival.dao.DataDeletionDAO; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java index 25120a07e0..137f79eb22 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java @@ -18,23 +18,24 @@ package io.entgra.device.mgt.core.device.mgt.core.authorization; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.CarbonConstants; -import org.wso2.carbon.context.CarbonContext; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationException; import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationService; import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAuthorizationResult; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupManagementException; import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.Permission; import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.CarbonConstants; +import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; + import java.util.Iterator; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/authorization/GroupAccessAuthorizationServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/authorization/GroupAccessAuthorizationServiceImpl.java index acceb466c1..2f796f929f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/authorization/GroupAccessAuthorizationServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/authorization/GroupAccessAuthorizationServiceImpl.java @@ -73,21 +73,24 @@ public class GroupAccessAuthorizationServiceImpl implements GroupAccessAuthoriza UserRealm userRealm = DeviceManagementDataHolder.getInstance().getRealmService() .getTenantUserRealm(getTenantId()); String[] userRoles = userRealm.getUserStoreManager().getRoleListOfUser(username); - boolean isAuthorized = true; + boolean isAuthorized; for (String groupPermission : groupPermissions) { + isAuthorized = false; for (String role : userRoles) { - if (!userRealm.getAuthorizationManager(). + if (userRealm.getAuthorizationManager(). isRoleAuthorized(role, groupPermission, CarbonConstants.UI_PERMISSION_ACTION)) { - isAuthorized = false; + isAuthorized = true; break; } } + if (!isAuthorized) { + return false; + } } - return isAuthorized; + return true; } catch (UserStoreException e) { throw new GroupAccessAuthorizationException("Unable to authorize the access to group : " + - groupId + " for the user : " + - username, e); + groupId + " for the user : " + username, e); } } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/cache/DeviceCacheManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/cache/DeviceCacheManager.java index 4ba316fbdb..d392a81cd7 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/cache/DeviceCacheManager.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/cache/DeviceCacheManager.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.device.mgt.core.cache; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.Device; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/cache/impl/BillingCacheManagerImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/cache/impl/BillingCacheManagerImpl.java index d5f63dd652..84efc8d106 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/cache/impl/BillingCacheManagerImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/cache/impl/BillingCacheManagerImpl.java @@ -18,13 +18,13 @@ package io.entgra.device.mgt.core.device.mgt.core.cache.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.core.cache.BillingCacheKey; import io.entgra.device.mgt.core.device.mgt.core.cache.BillingCacheManager; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.cache.Cache; import java.sql.Timestamp; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/cache/impl/DeviceCacheManagerImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/cache/impl/DeviceCacheManagerImpl.java index 2e6e3c4d7f..467e9783af 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/cache/impl/DeviceCacheManagerImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/cache/impl/DeviceCacheManagerImpl.java @@ -18,13 +18,13 @@ package io.entgra.device.mgt.core.device.mgt.core.cache.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.core.cache.DeviceCacheKey; import io.entgra.device.mgt.core.device.mgt.core.cache.DeviceCacheManager; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.cache.Cache; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/common/util/FileUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/common/util/FileUtil.java index 4bd3f9455b..cc25b794cb 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/common/util/FileUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/common/util/FileUtil.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.device.mgt.core.common.util; -import org.apache.commons.io.FileUtils; import io.entgra.device.mgt.core.device.mgt.common.Base64File; +import org.apache.commons.io.FileUtils; import java.io.ByteArrayInputStream; import java.io.File; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/common/util/HttpUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/common/util/HttpUtil.java index ecdf63d8c5..13842dad56 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/common/util/HttpUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/common/util/HttpUtil.java @@ -17,13 +17,14 @@ */ package io.entgra.device.mgt.core.device.mgt.core.common.util; +import io.entgra.device.mgt.core.device.mgt.core.common.Constants; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; import org.apache.commons.validator.routines.UrlValidator; import org.apache.http.HttpResponse; import org.apache.http.entity.ContentType; import org.apache.http.util.EntityUtils; -import io.entgra.device.mgt.core.device.mgt.core.common.Constants; + import java.io.IOException; import java.net.URI; import java.util.ArrayList; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/common/util/StorageManagementUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/common/util/StorageManagementUtil.java index bf37d0bab6..7d3f69ee8b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/common/util/StorageManagementUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/common/util/StorageManagementUtil.java @@ -18,20 +18,18 @@ package io.entgra.device.mgt.core.device.mgt.core.common.util; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.Base64File; import io.entgra.device.mgt.core.device.mgt.core.common.exception.StorageManagementException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; -import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/DeviceConfigurationManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/DeviceConfigurationManager.java index 30d4961f99..938ea132b5 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/DeviceConfigurationManager.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/DeviceConfigurationManager.java @@ -18,10 +18,10 @@ package io.entgra.device.mgt.core.device.mgt.core.config; -import org.w3c.dom.Document; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; +import org.w3c.dom.Document; import org.wso2.carbon.utils.CarbonUtils; import javax.xml.bind.JAXBContext; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/DeviceManagementConfig.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/DeviceManagementConfig.java index 94d873b192..d38eb41338 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/DeviceManagementConfig.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/DeviceManagementConfig.java @@ -26,12 +26,11 @@ import io.entgra.device.mgt.core.device.mgt.core.config.cache.CertificateCacheCo import io.entgra.device.mgt.core.device.mgt.core.config.cache.DeviceCacheConfiguration; import io.entgra.device.mgt.core.device.mgt.core.config.cache.GeoFenceCacheConfiguration; import io.entgra.device.mgt.core.device.mgt.core.config.enrollment.guide.EnrollmentGuideConfiguration; -import io.entgra.device.mgt.core.device.mgt.core.config.operation.timeout.OperationTimeoutConfiguration; -import io.entgra.device.mgt.core.device.mgt.core.config.metadata.mgt.MetaDataConfiguration; -import io.entgra.device.mgt.core.device.mgt.core.event.config.EventOperationTaskConfiguration; import io.entgra.device.mgt.core.device.mgt.core.config.geo.location.GeoLocationConfiguration; import io.entgra.device.mgt.core.device.mgt.core.config.identity.IdentityConfigurations; import io.entgra.device.mgt.core.device.mgt.core.config.keymanager.KeyManagerConfigurations; +import io.entgra.device.mgt.core.device.mgt.core.config.metadata.mgt.MetaDataConfiguration; +import io.entgra.device.mgt.core.device.mgt.core.config.operation.timeout.OperationTimeoutConfiguration; import io.entgra.device.mgt.core.device.mgt.core.config.pagination.PaginationConfiguration; import io.entgra.device.mgt.core.device.mgt.core.config.policy.PolicyConfiguration; import io.entgra.device.mgt.core.device.mgt.core.config.pull.notification.PullNotificationConfiguration; @@ -39,6 +38,7 @@ import io.entgra.device.mgt.core.device.mgt.core.config.push.notification.PushNo import io.entgra.device.mgt.core.device.mgt.core.config.remote.session.RemoteSessionConfiguration; import io.entgra.device.mgt.core.device.mgt.core.config.status.task.DeviceStatusTaskConfig; import io.entgra.device.mgt.core.device.mgt.core.config.task.TaskConfiguration; +import io.entgra.device.mgt.core.device.mgt.core.event.config.EventOperationTaskConfiguration; import io.entgra.device.mgt.core.device.mgt.core.config.permission.DefaultPermissions; import javax.xml.bind.annotation.XmlElement; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/license/LicenseConfigurationManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/license/LicenseConfigurationManager.java index e6e7a783db..7a29d37f85 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/license/LicenseConfigurationManager.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/license/LicenseConfigurationManager.java @@ -18,10 +18,10 @@ package io.entgra.device.mgt.core.device.mgt.core.config.license; -import org.w3c.dom.Document; -import io.entgra.device.mgt.core.device.mgt.core.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.LicenseManagementException; +import io.entgra.device.mgt.core.device.mgt.core.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; +import org.w3c.dom.Document; import org.wso2.carbon.utils.CarbonUtils; import javax.xml.bind.JAXBContext; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/permission/AnnotationProcessor.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/permission/AnnotationProcessor.java index ef6b5e68a4..e3686ec884 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/permission/AnnotationProcessor.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/permission/AnnotationProcessor.java @@ -19,22 +19,14 @@ package io.entgra.device.mgt.core.device.mgt.core.config.permission; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; +import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.Permission; import io.swagger.annotations.SwaggerDefinition; import org.apache.catalina.core.StandardContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.Permission; import javax.servlet.ServletContext; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HttpMethod; -import javax.ws.rs.OPTIONS; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; +import javax.ws.rs.*; import java.io.File; import java.io.IOException; import java.lang.annotation.Annotation; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java index 7160d29ccc..22021627aa 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java @@ -18,17 +18,17 @@ package io.entgra.device.mgt.core.device.mgt.core.config.permission.lifecycle; +import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.Permission; +import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException; +import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagerService; +import io.entgra.device.mgt.core.device.mgt.core.config.permission.AnnotationProcessor; +import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleEvent; import org.apache.catalina.LifecycleListener; import org.apache.catalina.core.StandardContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.Permission; -import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException; -import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagerService; -import io.entgra.device.mgt.core.device.mgt.core.config.permission.AnnotationProcessor; -import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; import javax.servlet.ServletContext; import java.io.IOException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/tenant/PlatformConfigurationManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/tenant/PlatformConfigurationManagementServiceImpl.java index dc8263edda..eaa66e225b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/tenant/PlatformConfigurationManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/tenant/PlatformConfigurationManagementServiceImpl.java @@ -17,15 +17,15 @@ */ package io.entgra.device.mgt.core.device.mgt.core.config.tenant; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationManagementException; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService; import io.entgra.device.mgt.core.device.mgt.core.config.ConfigurationManagerConstants; import io.entgra.device.mgt.core.device.mgt.core.config.util.ConfigurationManagerUtil; -import org.wso2.carbon.registry.api.Resource; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.registry.api.RegistryException; +import org.wso2.carbon.registry.api.Resource; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/UIConfigurationManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/UIConfigurationManager.java index b9c6470eb1..c3633df02f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/UIConfigurationManager.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/UIConfigurationManager.java @@ -18,12 +18,12 @@ package io.entgra.device.mgt.core.device.mgt.core.config.ui; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; import org.wso2.carbon.utils.CarbonUtils; import javax.xml.bind.JAXBContext; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/util/ConfigurationManagerUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/util/ConfigurationManagerUtil.java index 20262a218a..e30b01657a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/util/ConfigurationManagerUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/util/ConfigurationManagerUtil.java @@ -17,9 +17,9 @@ */ package io.entgra.device.mgt.core.device.mgt.core.config.util; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationManagementException; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.registry.api.RegistryException; import org.wso2.carbon.registry.api.Resource; import org.wso2.carbon.registry.core.Registry; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/ApplicationDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/ApplicationDAO.java index 826c5a07e7..30fb957122 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/ApplicationDAO.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/ApplicationDAO.java @@ -18,7 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.dao; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; -import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.Application; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceDAO.java index 5189068242..62aa6b4439 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceDAO.java @@ -18,17 +18,21 @@ package io.entgra.device.mgt.core.device.mgt.core.dao; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import org.apache.commons.collections.map.SingletonMap; -import io.entgra.device.mgt.core.device.mgt.common.*; +import io.entgra.device.mgt.core.device.mgt.common.Count; +import io.entgra.device.mgt.core.device.mgt.common.Device; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo.Status; +import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.DevicePropertyInfo; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceData; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceLocationHistorySnapshot; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceMonitoringData; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoCluster; import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoQuery; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoCluster; +import org.apache.commons.collections.map.SingletonMap; import java.sql.SQLException; import java.sql.Timestamp; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceManagementDAOFactory.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceManagementDAOFactory.java index b7768f9c52..97ffc1b836 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceManagementDAOFactory.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceManagementDAOFactory.java @@ -18,8 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.dao; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; @@ -39,6 +37,8 @@ import io.entgra.device.mgt.core.device.mgt.core.device.details.mgt.dao.DeviceDe import io.entgra.device.mgt.core.device.mgt.core.device.details.mgt.dao.impl.DeviceDetailsDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.privacy.dao.PrivacyComplianceDAO; import io.entgra.device.mgt.core.device.mgt.core.privacy.dao.impl.PrivacyComplianceDAOImpl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.sql.DataSource; import java.sql.Connection; @@ -171,6 +171,22 @@ public class DeviceManagementDAOFactory { throw new IllegalStateException("Database engine has not initialized properly."); } + public static TagDAO getTagDAO() { + if (databaseEngine != null) { + switch (databaseEngine) { + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL: + return new TagDAOImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); + } + public static DeviceStatusDAO getDeviceStatusDAO() { return new DeviceStatusDAOImpl(); } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceStatusDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceStatusDAO.java index bee39b3a99..0ee8d7cfa5 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceStatusDAO.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceStatusDAO.java @@ -17,9 +17,6 @@ */ package io.entgra.device.mgt.core.device.mgt.core.dao; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; -import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo.Status; import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceStatus; import java.util.Date; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java index 70b791db7b..f92adc4e4f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java @@ -24,7 +24,6 @@ import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo.Status; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceDetailsDTO; import io.entgra.device.mgt.core.device.mgt.core.dto.OwnerWithDeviceDTO; -import java.sql.Timestamp; import java.util.List; import java.util.Map; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EventConfigDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EventConfigDAO.java index f2c0a263fd..49b4668590 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EventConfigDAO.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EventConfigDAO.java @@ -21,7 +21,6 @@ package io.entgra.device.mgt.core.device.mgt.core.dao; import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfig; import java.util.List; -import java.util.Map; public interface EventConfigDAO { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupManagementDAOFactory.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupManagementDAOFactory.java index 6026badab5..68923d6d5c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupManagementDAOFactory.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupManagementDAOFactory.java @@ -18,8 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.dao; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; @@ -31,6 +29,8 @@ import io.entgra.device.mgt.core.device.mgt.core.dao.impl.group.OracleGroupDAOIm import io.entgra.device.mgt.core.device.mgt.core.dao.impl.group.PostgreSQLGroupDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.dao.impl.group.SQLServerGroupDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.dao.util.GroupManagementDAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.sql.DataSource; import java.sql.Connection; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/TagDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/TagDAO.java new file mode 100644 index 0000000000..7db392dec6 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/TagDAO.java @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.core.dao; + +import io.entgra.device.mgt.core.device.mgt.common.tag.mgt.DeviceTag; +import io.entgra.device.mgt.core.device.mgt.common.tag.mgt.Tag; + +import java.util.List; + +/** + * This interface represents the key operations associated with persisting tag related information. + */ +public interface TagDAO { + + /** + * Add a new tag. + * + * @param tags to be added. + * @param tenantId of the tag. + * @throws TagManagementDAOException + */ + void addTags(List tags, int tenantId) throws TagManagementDAOException; + + /** + * Update an existing tag. + * + * @param tag to be updated. + * @param tenantId of the tag. + * @throws TagManagementDAOException + */ + void updateTag(Tag tag, int tenantId) throws TagManagementDAOException; + + /** + * Delete an existing tag. + * + * @param tagId of the tag. + * @param tenantId of the tag. + * @throws TagManagementDAOException + */ + void deleteTag(int tagId, int tenantId) throws TagManagementDAOException; + + /** + * Get a tag by id. + * + * @param tagId of the tag. + * @param tenantId of the tag. + * @return Tag object. + * @throws TagManagementDAOException + */ + Tag getTagById(int tagId, int tenantId) throws TagManagementDAOException; + + /** + * Method to retrieve a tag by its name. + * + * @param tagName - Name of the tag to be retrieved. + * @param tenantId - Tenant ID. + * @return Tag object retrieved from the database. + * @throws TagManagementDAOException if something goes wrong while retrieving the Tag. + */ + Tag getTagByName(String tagName, int tenantId) throws TagManagementDAOException; + + /** + * Get all tags for a tenant. + * + * @param tenantId of the tag. + * @return List of all tags. + * @throws TagManagementDAOException + */ + List getTags(int tenantId) throws TagManagementDAOException; + + /** + * Add a device tag mapping. + * + * @param deviceIdentifiers of the mapping. + * @param deviceType of the mapping. + * @param tagNames of the mapping. + * @param tenantId of the mapping. + * @throws TagManagementDAOException + */ + void addDeviceTagMapping(List deviceIdentifiers, String deviceType, List tagNames, int tenantId) + throws TagManagementDAOException; + + /** + * Delete a device tag mapping. + * + * @param deviceIdentifiers of the mapping. + * @param deviceType of the mapping. + * @param tagNames of the mapping. + * @param tenantId of the mapping. + * @throws TagManagementDAOException + */ + void deleteDeviceTagMapping(List deviceIdentifiers, String deviceType, List tagNames, int tenantId) + throws TagManagementDAOException; + + /** + * Get all device tags for a device. + * + * @param deviceId of the device. + * @param tenantId of the mapping. + * @return List of device tags. + * @throws TagManagementDAOException + */ + List getTagsForDevice(int deviceId, int tenantId) throws TagManagementDAOException; + + /** + * Get all devices for a tag. + * + * @param tagId of the tag. + * @param tenantId of the mapping. + * @return List of device tags. + * @throws TagManagementDAOException + */ + List getDevicesForTag(int tagId, int tenantId) throws TagManagementDAOException; +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/TagManagementDAOException.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/TagManagementDAOException.java new file mode 100644 index 0000000000..179d887dc5 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/TagManagementDAOException.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.core.dao; + +/** + * Custom exception class for tag management data access related exceptions. + */ +public class TagManagementDAOException extends Exception { + + private static final long serialVersionUID = 2021891706072918864L; + private String message; + private boolean uniqueConstraintViolation; + + /** + * Constructs a new exception with the specified detail message and nested exception. + * + * @param message error message + * @param nestedException exception + */ + public TagManagementDAOException(String message, Exception nestedException) { + super(message, nestedException); + setErrorMessage(message); + } + + /** + * Constructs a new exception with the specified detail message and cause. + * + * @param message the detail message. + * @param cause the cause of this exception. + */ + public TagManagementDAOException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + /** + * Constructs a new exception with the specified detail message. + * + * @param message the detail message. + */ + public TagManagementDAOException(String message) { + super(message); + setErrorMessage(message); + } + + /** + * Constructs a new exception with the specified cause. + * + * @param cause the cause of this exception. + */ + public TagManagementDAOException(Throwable cause) { + super(cause); + } + + public TagManagementDAOException(String message, Throwable cause, boolean uniqueConstraintViolation) { + super(message, cause); + setErrorMessage(message); + this.uniqueConstraintViolation = uniqueConstraintViolation; + } + + public String getMessage() { + return message; + } + + public void setErrorMessage(String errorMessage) { + this.message = errorMessage; + } + + public boolean isUniqueConstraintViolation() { + return uniqueConstraintViolation; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/TrackerManagementDAOFactory.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/TrackerManagementDAOFactory.java index 87755c5dd1..200012e73f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/TrackerManagementDAOFactory.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/TrackerManagementDAOFactory.java @@ -18,8 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.dao; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; @@ -28,6 +26,8 @@ import io.entgra.device.mgt.core.device.mgt.core.config.datasource.DataSourceCon import io.entgra.device.mgt.core.device.mgt.core.config.datasource.JNDILookupDefinition; import io.entgra.device.mgt.core.device.mgt.core.dao.impl.tracker.TrackerDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.sql.DataSource; import java.sql.Connection; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 3b8aa18647..ffebacf1e0 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -18,10 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.dao.impl; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import org.apache.commons.collections.map.SingletonMap; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; @@ -31,12 +27,16 @@ import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.DevicePrope import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceData; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceLocationHistorySnapshot; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceMonitoringData; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoQuery; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceDAO; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; +import org.apache.commons.collections.map.SingletonMap; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoCluster; import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoCoordinate; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -1030,6 +1030,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { boolean isStatusProvided = false; Date since = request.getSince(); boolean isSinceProvided = false; + List tagList = request.getTags(); + boolean isTagsProvided = false; try { Connection conn = getConnection(); @@ -1084,6 +1086,15 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { sql += buildStatusQuery(statusList); isStatusProvided = true; } + if (tagList != null && !tagList.isEmpty()) { + sql += " AND e.ID IN ( " + + "SELECT dtm.ENROLMENT_ID " + + "FROM DM_DEVICE_TAG_MAPPING dtm " + + "JOIN DM_TAG t ON dtm.TAG_ID = t.ID " + + "WHERE t.NAME IN (" + buildTagQuery(tagList); + sql += ") GROUP BY dtm.ENROLMENT_ID HAVING COUNT(DISTINCT t.NAME) = ? )"; + isTagsProvided = true; + } try (PreparedStatement stmt = conn.prepareStatement(sql)) { int paramIdx = 1; @@ -1112,6 +1123,12 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { stmt.setString(paramIdx++, status); } } + if (isTagsProvided) { + for (String tag : tagList) { + stmt.setString(paramIdx++, tag); + } + stmt.setInt(paramIdx++, tagList.size()); + } try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { @@ -1300,6 +1317,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { boolean isStatusProvided = false; Date since = request.getSince(); boolean isSinceProvided = false; + List tagList = request.getTags(); + boolean isTagsProvided = false; try { Connection conn = getConnection(); @@ -1342,6 +1361,15 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { sql += buildStatusQuery(statusList); isStatusProvided = true; } + if (tagList != null && !tagList.isEmpty()) { + sql += " AND e.ID IN ( " + + "SELECT dtm.ENROLMENT_ID " + + "FROM DM_DEVICE_TAG_MAPPING dtm " + + "JOIN DM_TAG t ON dtm.TAG_ID = t.ID " + + "WHERE t.NAME IN (" + buildTagQuery(tagList); + sql += ") GROUP BY dtm.ENROLMENT_ID HAVING COUNT(DISTINCT t.NAME) = ? )"; + isTagsProvided = true; + } try (PreparedStatement stmt = conn.prepareStatement(sql)) { int paramIdx = 1; @@ -1368,6 +1396,12 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { stmt.setString(paramIdx++, status); } } + if (isTagsProvided) { + for (String tag : tagList) { + stmt.setString(paramIdx++, tag); + } + stmt.setInt(paramIdx++, tagList.size()); + } try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { @@ -2942,6 +2976,11 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { return joiner.toString(); } + protected String buildTagQuery(List tagList) + throws DeviceManagementDAOException { + return String.join(", ", Collections.nCopies(tagList.size(), "?")); + } + public int getFunctioningDevicesInSystem() throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java index 091716bfe7..b4415fdf37 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java @@ -17,12 +17,8 @@ */ package io.entgra.device.mgt.core.device.mgt.core.dao.impl; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.util.OperationDAOUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; @@ -31,6 +27,9 @@ import io.entgra.device.mgt.core.device.mgt.core.dao.EnrollmentDAO; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.dto.OwnerWithDeviceDTO; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceDetailsDTO; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.sql.Connection; import java.sql.PreparedStatement; @@ -38,9 +37,9 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; +import java.util.ArrayList; import java.util.Date; import java.util.List; -import java.util.ArrayList; public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO { private static final Log log = LogFactory.getLog(AbstractEnrollmentDAOImpl.class); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEventConfigDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEventConfigDAO.java index dfe882ed44..6e3b69a1ce 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEventConfigDAO.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEventConfigDAO.java @@ -18,12 +18,12 @@ package io.entgra.device.mgt.core.device.mgt.core.dao.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfig; import io.entgra.device.mgt.core.device.mgt.core.dao.EventConfigDAO; import io.entgra.device.mgt.core.device.mgt.core.dao.EventManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dao.EventManagementDAOFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGeofenceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGeofenceDAOImpl.java index 9c560a35cc..1b4f09b7e5 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGeofenceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGeofenceDAOImpl.java @@ -18,8 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.dao.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfig; @@ -28,21 +26,12 @@ import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOExceptio import io.entgra.device.mgt.core.device.mgt.core.dao.EventManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.dao.GeofenceDAO; import io.entgra.device.mgt.core.device.mgt.core.dto.event.config.GeoFenceGroupMap; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Collections; +import java.sql.*; import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; public abstract class AbstractGeofenceDAOImpl implements GeofenceDAO { private static final Log log = LogFactory.getLog(AbstractGeofenceDAOImpl.class); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java index 518919add1..21f831e712 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java @@ -18,20 +18,20 @@ package io.entgra.device.mgt.core.device.mgt.core.dao.impl; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroupRoleWrapper; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.GroupPaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; -import io.entgra.device.mgt.core.device.mgt.core.dto.GroupDetailsDTO; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroupRoleWrapper; import io.entgra.device.mgt.core.device.mgt.core.dao.GroupDAO; +import io.entgra.device.mgt.core.device.mgt.core.dto.GroupDetailsDTO; import io.entgra.device.mgt.core.device.mgt.core.dao.GroupManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dao.GroupManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.dao.util.GroupManagementDAOUtil; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java index 60c86f0876..5107002ddc 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java @@ -23,7 +23,6 @@ import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceStatus; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceStatusDAO; -import io.entgra.device.mgt.core.device.mgt.core.dao.EnrollmentDAO; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import java.sql.*; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/DeviceTypeDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/DeviceTypeDAOImpl.java index 28e5a473b2..04a4316647 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/DeviceTypeDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/DeviceTypeDAOImpl.java @@ -19,9 +19,6 @@ package io.entgra.device.mgt.core.device.mgt.core.dao.impl; import com.google.gson.Gson; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; @@ -30,19 +27,11 @@ import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceTypeDAO; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceTypeVersion; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; -import java.nio.file.Files; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.sql.*; import java.util.ArrayList; import java.util.Date; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/TagDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/TagDAOImpl.java new file mode 100644 index 0000000000..bd901e0fed --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/TagDAOImpl.java @@ -0,0 +1,382 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.core.dao.impl; + +import io.entgra.device.mgt.core.device.mgt.common.tag.mgt.DeviceTag; +import io.entgra.device.mgt.core.device.mgt.common.tag.mgt.Tag; +import io.entgra.device.mgt.core.device.mgt.core.dao.*; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLIntegrityConstraintViolationException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import static io.entgra.device.mgt.core.device.mgt.core.dao.util.TagManagementDAOUtil.loadDeviceTagMapping; +import static io.entgra.device.mgt.core.device.mgt.core.dao.util.TagManagementDAOUtil.loadTag; +import static io.entgra.device.mgt.core.device.mgt.core.dao.util.TagManagementDAOUtil.cleanupResources; + +public class TagDAOImpl implements TagDAO { + + private static final Log log = LogFactory.getLog(TagDAOImpl.class); + + protected Connection getConnection() throws SQLException { + return DeviceManagementDAOFactory.getConnection(); + } + + @Override + public void addTags(List tags, int tenantId) throws TagManagementDAOException { + String query = "INSERT INTO DM_TAG (NAME, DESCRIPTION, TENANT_ID) " + + "SELECT ?, ?, ? " + + "WHERE NOT EXISTS ( " + + " SELECT 1 FROM DM_TAG " + + " WHERE NAME = ? AND TENANT_ID = ? " + + ")"; + Connection connection; + PreparedStatement preparedStatement = null; + + try { + connection = getConnection(); + preparedStatement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); + for (Tag tag : tags) { + preparedStatement.setString(1, tag.getName()); + preparedStatement.setString(2, tag.getDescription()); + preparedStatement.setInt(3, tenantId); + preparedStatement.setString(4, tag.getName()); + preparedStatement.setInt(5, tenantId); + preparedStatement.addBatch(); + } + int[] updateCounts = preparedStatement.executeBatch(); + for (int count : updateCounts) { + if (count == PreparedStatement.EXECUTE_FAILED) { + String msg = "Error occurred while adding tags, adding some tags failed."; + log.error(msg); + throw new TagManagementDAOException(msg); + } + } + } catch (SQLException e) { + String msg = "Error occurred while adding tags."; + log.error(msg, e); + throw new TagManagementDAOException(msg, e); + } finally { + cleanupResources(preparedStatement, null); + } + } + + @Override + public void updateTag(Tag tag, int tenantId) throws TagManagementDAOException { + String query = "UPDATE DM_TAG SET NAME = ?, DESCRIPTION = ? WHERE ID = ? AND TENANT_ID = ?"; + Connection connection; + PreparedStatement preparedStatement = null; + + try { + connection = getConnection(); + preparedStatement = connection.prepareStatement(query); + preparedStatement.setString(1, tag.getName()); + preparedStatement.setString(2, tag.getDescription()); + preparedStatement.setInt(3, tag.getId()); + preparedStatement.setInt(4, tenantId); + preparedStatement.executeUpdate(); + } catch (SQLException e) { + String msg = "Error occurred while updating tag."; + log.error(msg, e); + throw new TagManagementDAOException(msg, e); + } finally { + cleanupResources(preparedStatement, null); + } + } + + @Override + public void deleteTag(int tagId, int tenantId) throws TagManagementDAOException { + String query = "DELETE FROM DM_TAG WHERE ID = ? AND TENANT_ID = ?"; + Connection connection; + PreparedStatement preparedStatement = null; + + try { + connection = getConnection(); + preparedStatement = connection.prepareStatement(query); + preparedStatement.setInt(1, tagId); + preparedStatement.setInt(2, tenantId); + preparedStatement.executeUpdate(); + } catch (SQLException e) { + String msg = "Error occurred while deleting tag."; + log.error(msg, e); + throw new TagManagementDAOException(msg, e); + } finally { + cleanupResources(preparedStatement, null); + } + } + + @Override + public Tag getTagById(int tagId, int tenantId) throws TagManagementDAOException { + String query = "SELECT * FROM DM_TAG WHERE ID = ? AND TENANT_ID = ?"; + Connection connection; + PreparedStatement preparedStatement = null; + ResultSet resultSet = null; + Tag tag = null; + + try { + connection = getConnection(); + preparedStatement = connection.prepareStatement(query); + preparedStatement.setInt(1, tagId); + preparedStatement.setInt(2, tenantId); + + resultSet = preparedStatement.executeQuery(); + if (resultSet.next()) { + tag = loadTag(resultSet); + } + } catch (SQLException e) { + String msg = "Error occurred while getting a specific tag." + tagId; + log.error(msg, e); + throw new TagManagementDAOException(msg, e); + } finally { + cleanupResources(preparedStatement, resultSet); + } + return tag; + } + + @Override + public Tag getTagByName(String tagName, int tenantId) throws TagManagementDAOException { + String query = "SELECT * FROM DM_TAG WHERE NAME = ? AND TENANT_ID = ?"; + Connection connection; + PreparedStatement preparedStatement = null; + ResultSet resultSet = null; + Tag tag = null; + + try { + connection = getConnection(); + preparedStatement = connection.prepareStatement(query); + preparedStatement.setString(1, tagName); + preparedStatement.setInt(2, tenantId); + + resultSet = preparedStatement.executeQuery(); + if (resultSet.next()) { + tag = loadTag(resultSet); + } + } catch (SQLException e) { + String msg = "Error occurred while retrieving tag with name: " + tagName; + log.error(msg, e); + throw new TagManagementDAOException(msg, e); + } finally { + cleanupResources(preparedStatement, resultSet); + } + return tag; + } + + + @Override + public List getTags(int tenantId) throws TagManagementDAOException { + String query = "SELECT * FROM DM_TAG WHERE TENANT_ID = ?"; + Connection connection; + PreparedStatement preparedStatement = null; + ResultSet resultSet = null; + List tags = new ArrayList<>(); + + try { + connection = getConnection(); + preparedStatement = connection.prepareStatement(query); + preparedStatement.setInt(1, tenantId); + + resultSet = preparedStatement.executeQuery(); + while (resultSet.next()) { + Tag tag = loadTag(resultSet); + tags.add(tag); + } + } catch (SQLException e) { + String msg = "Error occurred while retrieving tags"; + log.error(msg, e); + throw new TagManagementDAOException(msg, e); + } finally { + cleanupResources(preparedStatement, resultSet); + } + return tags; + } + + @Override + public void addDeviceTagMapping(List deviceIdentifiers, String deviceType, List tagNames, int tenantId) throws TagManagementDAOException { + String deviceIdentifiersPlaceholders = String.join(", ", Collections.nCopies(deviceIdentifiers.size(), "?")); + String tagNamesPlaceholders = String.join(", ", Collections.nCopies(tagNames.size(), "?")); + + String query = String.format( + "INSERT INTO DM_DEVICE_TAG_MAPPING (ENROLMENT_ID, TAG_ID, TENANT_ID) " + + "SELECT e.ID, t.ID, ? " + + "FROM DM_ENROLMENT e " + + "JOIN DM_DEVICE d ON d.ID = e.DEVICE_ID " + + "JOIN DM_TAG t ON t.NAME IN (%s) " + + "WHERE d.DEVICE_IDENTIFICATION IN (%s) " + + "AND e.DEVICE_TYPE = ? " + + "AND e.STATUS != 'REMOVED' " + + "AND e.TENANT_ID = ? " + + "AND t.TENANT_ID = ? " + + "AND NOT EXISTS ( " + + " SELECT 1 " + + " FROM DM_DEVICE_TAG_MAPPING m " + + " WHERE m.ENROLMENT_ID = e.ID " + + " AND m.TAG_ID = t.ID " + + " AND m.TENANT_ID = ? " + + ")", + tagNamesPlaceholders, + deviceIdentifiersPlaceholders + ); + + Connection connection; + PreparedStatement preparedStatement = null; + try { + connection = getConnection(); + preparedStatement = connection.prepareStatement(query); + int paramIndex = 1; + preparedStatement.setInt(paramIndex++, tenantId); + for (String tagName : tagNames) { + preparedStatement.setString(paramIndex++, tagName); + } + for (String deviceIdentifier : deviceIdentifiers) { + preparedStatement.setString(paramIndex++, deviceIdentifier); + } + preparedStatement.setString(paramIndex++, deviceType); + preparedStatement.setInt(paramIndex++, tenantId); + preparedStatement.setInt(paramIndex++, tenantId); + preparedStatement.setInt(paramIndex, tenantId); + preparedStatement.executeUpdate(); + } catch (SQLIntegrityConstraintViolationException e) { + String msg = "Tag is already mapped to this device"; + log.error(msg, e); + throw new TagManagementDAOException(msg, e, true); + } catch (SQLException e) { + String msg = "Error occurred while adding device tag mapping"; + log.error(msg, e); + throw new TagManagementDAOException(msg, e); + } finally { + cleanupResources(preparedStatement, null); + } + } + + @Override + public void deleteDeviceTagMapping(List deviceIdentifiers, String deviceType, List tagNames, int tenantId) throws TagManagementDAOException { + String deviceIdentifiersPlaceholders = String.join(", ", Collections.nCopies(deviceIdentifiers.size(), "?")); + String tagNamesPlaceholders = String.join(", ", Collections.nCopies(tagNames.size(), "?")); + + String query = String.format( + "DELETE FROM DM_DEVICE_TAG_MAPPING " + + "WHERE ENROLMENT_ID IN ( " + + " SELECT e.ID " + + " FROM DM_ENROLMENT e " + + " JOIN DM_DEVICE d ON d.ID = e.DEVICE_ID " + + " WHERE d.DEVICE_IDENTIFICATION IN (%s) " + + " AND e.DEVICE_TYPE = ? " + + " AND e.TENANT_ID = ? " + + " AND e.STATUS != 'REMOVED' " + + ") " + + "AND TAG_ID IN ( " + + " SELECT t.ID " + + " FROM DM_TAG t " + + " WHERE t.NAME IN (%s) " + + " AND t.TENANT_ID = ? " + + ")", + deviceIdentifiersPlaceholders, + tagNamesPlaceholders + ); + Connection connection; + PreparedStatement preparedStatement = null; + try { + connection = getConnection(); + preparedStatement = connection.prepareStatement(query); + int paramIndex = 1; + for (String deviceIdentifier : deviceIdentifiers) { + preparedStatement.setString(paramIndex++, deviceIdentifier); + } + preparedStatement.setString(paramIndex++, deviceType); + preparedStatement.setInt(paramIndex++, tenantId); + for (String tagName : tagNames) { + preparedStatement.setString(paramIndex++, tagName); + } + preparedStatement.setInt(paramIndex, tenantId); + preparedStatement.executeUpdate(); + } catch (SQLException e) { + String msg = "Error occurred while deleting device tag mapping"; + log.error(msg, e); + throw new TagManagementDAOException(msg, e); + } finally { + cleanupResources(preparedStatement, null); + } + } + + @Override + public List getTagsForDevice(int deviceId, int tenantId) throws TagManagementDAOException { + String query = "SELECT * FROM DM_DEVICE_TAG_MAPPING WHERE DEVICE_ID = ? AND TENANT_ID = ?"; + Connection connection; + PreparedStatement preparedStatement = null; + ResultSet resultSet = null; + List deviceTags = new ArrayList<>(); + + try { + connection = getConnection(); + preparedStatement = connection.prepareStatement(query); + preparedStatement.setInt(1, deviceId); + preparedStatement.setInt(2, tenantId); + + resultSet = preparedStatement.executeQuery(); + while (resultSet.next()) { + DeviceTag deviceTag = loadDeviceTagMapping(resultSet); + deviceTags.add(deviceTag); + } + } catch (SQLException e) { + String msg = "Error occurred while retrieving device tags"; + log.error(msg, e); + throw new TagManagementDAOException(msg, e); + } finally { + cleanupResources(preparedStatement, resultSet); + } + return deviceTags; + } + + @Override + public List getDevicesForTag(int tagId, int tenantId) throws TagManagementDAOException { + String query = "SELECT * FROM DM_DEVICE_TAG_MAPPING WHERE TAG_ID = ? AND TENANT_ID = ?"; + Connection connection; + PreparedStatement preparedStatement = null; + ResultSet resultSet = null; + List deviceTags = new ArrayList<>(); + + try { + connection = getConnection(); + preparedStatement = connection.prepareStatement(query); + preparedStatement.setInt(1, tagId); + preparedStatement.setInt(2, tenantId); + + resultSet = preparedStatement.executeQuery(); + while (resultSet.next()) { + DeviceTag deviceTag = loadDeviceTagMapping(resultSet); + deviceTags.add(deviceTag); + } + } catch (SQLException e) { + String msg = "Error occurred while retrieving devices for tag"; + log.error(msg, e); + throw new TagManagementDAOException(msg, e); + } finally { + cleanupResources(preparedStatement, resultSet); + } + return deviceTags; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index 85b4b5553d..7159c3d33c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -18,9 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.dao.impl.device; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.Count; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; @@ -31,6 +28,9 @@ import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOExceptio import io.entgra.device.mgt.core.device.mgt.core.dao.impl.AbstractDeviceDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.report.mgt.Constants; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; @@ -71,6 +71,8 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isSinceProvided = false; String serial = request.getSerialNumber(); boolean isSerialProvided = false; + List tagList = request.getTags(); + boolean isTagsProvided = false; try { Connection conn = getConnection(); @@ -86,7 +88,10 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "e.IS_TRANSFERRED, " + "e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + + "e.ID AS ENROLMENT_ID, " + + "( SELECT GROUP_CONCAT(t.NAME ORDER BY t.NAME SEPARATOR ', ') " + + "FROM DM_DEVICE_TAG_MAPPING dtm JOIN DM_TAG t ON dtm.TAG_ID = t.ID " + + "WHERE dtm.ENROLMENT_ID = e.ID ) AS TAGS " + "FROM DM_ENROLMENT e, " + "(SELECT d.ID, " + "d.DESCRIPTION, " + @@ -162,7 +167,21 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { sql += buildStatusQuery(statusList); isStatusProvided = true; } - sql = sql + " LIMIT ? OFFSET ?"; + sql += " AND e.ID IN (" + + "SELECT e.ID " + + "FROM DM_ENROLMENT e " + + "LEFT JOIN DM_DEVICE_TAG_MAPPING dtm ON e.ID = dtm.ENROLMENT_ID " + + "LEFT JOIN DM_TAG t ON dtm.TAG_ID = t.ID "; + + if (tagList != null && !tagList.isEmpty()) { + sql += " WHERE t.NAME IN (" + buildTagQuery(tagList); + sql += ") GROUP BY e.ID HAVING COUNT(DISTINCT t.NAME) = ? "; + isTagsProvided = true; + } else { + sql += " GROUP BY e.ID "; + } + sql += ") "; + sql += " LIMIT ? OFFSET ?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { int paramIdx = 1; @@ -198,13 +217,19 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setString(paramIdx++, status); } } + if (isTagsProvided) { + for (String tag : tagList) { + stmt.setString(paramIdx++, tag); + } + stmt.setInt(paramIdx++, tagList.size()); + } stmt.setInt(paramIdx++, request.getRowCount()); stmt.setInt(paramIdx, request.getStartIndex()); try (ResultSet rs = stmt.executeQuery()) { devices = new ArrayList<>(); while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); + Device device = DeviceManagementDAOUtil.loadDevice(rs, true); devices.add(device); } return devices; @@ -667,6 +692,8 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isSinceProvided = false; String serial = request.getSerialNumber(); boolean isSerialProvided = false; + List tagList = request.getTags(); + boolean isTagsProvided = false; try { Connection conn = getConnection(); @@ -682,7 +709,10 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "e.IS_TRANSFERRED, " + "e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + + "e.ID AS ENROLMENT_ID, " + + "( SELECT GROUP_CONCAT(t.NAME ORDER BY t.NAME SEPARATOR ', ') " + + "FROM DM_DEVICE_TAG_MAPPING dtm JOIN DM_TAG t ON dtm.TAG_ID = t.ID " + + "WHERE dtm.ENROLMENT_ID = e.ID ) AS TAGS " + "FROM DM_ENROLMENT e, " + "(SELECT gd.DEVICE_ID, " + "gd.DESCRIPTION, " + @@ -739,7 +769,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { //Filter Group with serial number or any Custom Property in DM_DEVICE_INFO if (serial != null || !request.getCustomProperty().isEmpty()) { if (serial != null) { - sql += "AND EXISTS (" + + sql += " AND EXISTS (" + "SELECT VALUE_FIELD " + "FROM DM_DEVICE_INFO di " + "WHERE di.DEVICE_ID = d1.DEVICE_ID " + @@ -749,7 +779,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } if (!request.getCustomProperty().isEmpty()) { for (Map.Entry entry : request.getCustomProperty().entrySet()) { - sql += "AND EXISTS (" + + sql += " AND EXISTS (" + "SELECT VALUE_FIELD " + "FROM DM_DEVICE_INFO di2 " + "WHERE di2.DEVICE_ID = d1.DEVICE_ID " + @@ -758,6 +788,18 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } } + if (tagList != null && !tagList.isEmpty()) { + sql += " AND e.ID IN (" + + "SELECT e.ID " + + "FROM DM_ENROLMENT e " + + "LEFT JOIN DM_DEVICE_TAG_MAPPING dtm ON e.ID = dtm.ENROLMENT_ID " + + "LEFT JOIN DM_TAG t ON dtm.TAG_ID = t.ID " + + "WHERE t.NAME IN (" + buildTagQuery(tagList); + sql += ") GROUP BY e.ID HAVING COUNT(DISTINCT t.NAME) = ? ) "; + isTagsProvided = true; + } else { + sql += " GROUP BY e.ID "; + } sql = sql + " LIMIT ? OFFSET ?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { @@ -795,13 +837,19 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setString(paramIdx++, "%" + entry.getValue() + "%"); } } + if (isTagsProvided) { + for (String tag : tagList) { + stmt.setString(paramIdx++, tag); + } + stmt.setInt(paramIdx++, tagList.size()); + } stmt.setInt(paramIdx++, request.getRowCount()); stmt.setInt(paramIdx, request.getStartIndex()); try (ResultSet rs = stmt.executeQuery()) { devices = new ArrayList<>(); while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); + Device device = DeviceManagementDAOUtil.loadDevice(rs, true); devices.add(device); } return devices; @@ -1317,7 +1365,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { query += " AND i.VALUE_FIELD LIKE ?" ; } if (user != null && !user.isEmpty()) { - query += " AND e.OWNER = ?"; + query += " AND e.OWNER LIKE ?"; isOwnerProvided = true; } if (status != null && !status.isEmpty()) { @@ -1347,7 +1395,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { ps.setString(index++, EnrolmentInfo.Status.REMOVED.toString()); ps.setString(index++, EnrolmentInfo.Status.DELETED.toString()); if (isDeviceNameProvided) { - ps.setString(index++, name + "%"); + ps.setString(index++, "%" + name + "%"); } if (isOwnershipProvided) { ps.setString(index++, ownership); @@ -1356,7 +1404,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { ps.setString(index++, "%" + serial + "%"); } if (isOwnerProvided) { - ps.setString(index++, user); + ps.setString(index++, "%" + user + "%"); } if (isStatusProvided) { for (String deviceStatus : status) { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java index 0f502cf874..79afa4e4fe 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java @@ -18,8 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.dao.impl.device; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.Count; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; @@ -28,12 +26,10 @@ import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceInfo; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.report.mgt.Constants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; +import java.sql.*; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -68,6 +64,8 @@ public class PostgreSQLDeviceDAOImpl extends GenericDeviceDAOImpl { boolean isSinceProvided = false; String serial = request.getSerialNumber(); boolean isSerialProvided = false; + List tagList = request.getTags(); + boolean isTagsProvided = false; try { conn = getConnection(); @@ -82,7 +80,10 @@ public class PostgreSQLDeviceDAOImpl extends GenericDeviceDAOImpl { "e.IS_TRANSFERRED, " + "e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + + "e.ID AS ENROLMENT_ID, " + + "(SELECT STRING_AGG(t.NAME, ', ') FROM DM_DEVICE_TAG_MAPPING dtm " + + "JOIN DM_TAG t ON dtm.TAG_ID = t.ID " + + "WHERE dtm.ENROLMENT_ID = e.ID) AS TAGS " + "FROM DM_ENROLMENT e, " + "(SELECT d.ID, " + "d.DESCRIPTION, " + @@ -155,6 +156,13 @@ public class PostgreSQLDeviceDAOImpl extends GenericDeviceDAOImpl { sql += buildStatusQuery(statusList); isStatusProvided = true; } + if (tagList != null && !tagList.isEmpty()) { + sql += " AND e.ID IN (SELECT e.ID FROM DM_ENROLMENT e " + + "LEFT JOIN DM_DEVICE_TAG_MAPPING dtm ON e.ID = dtm.ENROLMENT_ID " + + "LEFT JOIN DM_TAG t ON dtm.TAG_ID = t.ID WHERE t.NAME IN (" + buildTagQuery(tagList); + sql += ") GROUP BY e.ID HAVING COUNT(DISTINCT t.NAME) = ? ) "; + isTagsProvided = true; + } sql = sql + " LIMIT ? OFFSET ?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { @@ -188,6 +196,12 @@ public class PostgreSQLDeviceDAOImpl extends GenericDeviceDAOImpl { stmt.setString(paramIdx++, status); } } + if (isTagsProvided) { + for (String tag : tagList) { + stmt.setString(paramIdx++, tag); + } + stmt.setInt(paramIdx++, tagList.size()); + } stmt.setInt(paramIdx++, request.getRowCount()); stmt.setInt(paramIdx, request.getStartIndex()); @@ -466,6 +480,8 @@ public class PostgreSQLDeviceDAOImpl extends GenericDeviceDAOImpl { boolean isSinceProvided = false; String serial = request.getSerialNumber(); boolean isSerialProvided = false; + List tagList = request.getTags(); + boolean isTagsProvided = false; try { conn = getConnection(); @@ -480,7 +496,10 @@ public class PostgreSQLDeviceDAOImpl extends GenericDeviceDAOImpl { "e.IS_TRANSFERRED, " + "e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + + "e.ID AS ENROLMENT_ID, " + + "(SELECT STRING_AGG(t.NAME, ', ') FROM DM_DEVICE_TAG_MAPPING dtm " + + "JOIN DM_TAG t ON dtm.TAG_ID = t.ID " + + "WHERE dtm.ENROLMENT_ID = e.ID) AS TAGS " + "FROM DM_ENROLMENT e, " + "(SELECT gd.DEVICE_ID, " + "gd.DESCRIPTION, " + @@ -555,6 +574,18 @@ public class PostgreSQLDeviceDAOImpl extends GenericDeviceDAOImpl { } } } + if (tagList != null && !tagList.isEmpty()) { + sql += " AND e.ID IN (" + + "SELECT e.ID " + + "FROM DM_ENROLMENT e " + + "LEFT JOIN DM_DEVICE_TAG_MAPPING dtm ON e.ID = dtm.ENROLMENT_ID " + + "LEFT JOIN DM_TAG t ON dtm.TAG_ID = t.ID " + + "WHERE t.NAME IN (" + buildTagQuery(tagList); + sql += ") GROUP BY e.ID HAVING COUNT(DISTINCT t.NAME) = ? ) "; + isTagsProvided = true; + } else { + sql += " GROUP BY e.ID "; + } sql = sql + " LIMIT ? OFFSET ?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { @@ -592,13 +623,19 @@ public class PostgreSQLDeviceDAOImpl extends GenericDeviceDAOImpl { stmt.setString(paramIdx++, "%" + entry.getValue() + "%"); } } + if (isTagsProvided) { + for (String tag : tagList) { + stmt.setString(paramIdx++, tag); + } + stmt.setInt(paramIdx++, tagList.size()); + } stmt.setInt(paramIdx++, request.getRowCount()); stmt.setInt(paramIdx, request.getStartIndex()); try (ResultSet rs = stmt.executeQuery()) { devices = new ArrayList<>(); while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); + Device device = DeviceManagementDAOUtil.loadDevice(rs, true); devices.add(device); } return devices; @@ -1068,7 +1105,7 @@ public class PostgreSQLDeviceDAOImpl extends GenericDeviceDAOImpl { isOwnershipProvided = true; } if (user != null && !user.isEmpty()) { - query += " AND e.OWNER = ?"; + query += " AND e.OWNER LIKE ?"; isOwnerProvided = true; } if (status != null && !status.isEmpty()) { @@ -1099,13 +1136,13 @@ public class PostgreSQLDeviceDAOImpl extends GenericDeviceDAOImpl { ps.setString(index++, EnrolmentInfo.Status.REMOVED.toString()); ps.setString(index++, EnrolmentInfo.Status.DELETED.toString()); if (isDeviceNameProvided) { - ps.setString(index++, name + "%"); + ps.setString(index++, "%" + name + "%"); } if (isOwnershipProvided) { ps.setString(index++, ownership); } if (isOwnerProvided) { - ps.setString(index++, user); + ps.setString(index++, "%" + user + "%"); } if (isStatusProvided) { for (String deviceStatus : status) { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index 7de242ead9..e977d7bd6e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -22,13 +22,13 @@ import io.entgra.device.mgt.core.device.mgt.common.Count; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceInfo; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.report.mgt.Constants; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; @@ -69,6 +69,8 @@ public class SQLServerDeviceDAOImpl extends GenericDeviceDAOImpl { boolean isSinceProvided = false; String serial = request.getSerialNumber(); boolean isSerialProvided = false; + List tagList = request.getTags(); + boolean isTagsProvided = false; try { conn = getConnection(); @@ -83,7 +85,10 @@ public class SQLServerDeviceDAOImpl extends GenericDeviceDAOImpl { "e.IS_TRANSFERRED, " + "e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + + "e.ID AS ENROLMENT_ID, " + + "(SELECT STRING_AGG(t.NAME, ', ') FROM DM_DEVICE_TAG_MAPPING dtm " + + "JOIN DM_TAG t ON dtm.TAG_ID = t.ID " + + "WHERE dtm.ENROLMENT_ID = e.ID) AS TAGS " + "FROM DM_ENROLMENT e, " + "(SELECT d.ID, " + "d.DESCRIPTION, " + @@ -161,6 +166,13 @@ public class SQLServerDeviceDAOImpl extends GenericDeviceDAOImpl { sql += buildStatusQuery(statusList); isStatusProvided = true; } + if (tagList!= null && !tagList.isEmpty()) { + sql += " AND e.ID IN (SELECT e.ID FROM DM_ENROLMENT e " + + "LEFT JOIN DM_DEVICE_TAG_MAPPING dtm ON e.ID = dtm.ENROLMENT_ID " + + "LEFT JOIN DM_TAG t ON dtm.TAG_ID = t.ID WHERE t.NAME IN (" + buildTagQuery(tagList); + sql += ") GROUP BY e.ID HAVING COUNT(DISTINCT t.NAME) = ? ) "; + isTagsProvided = true; + } sql = sql + " ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { @@ -197,13 +209,19 @@ public class SQLServerDeviceDAOImpl extends GenericDeviceDAOImpl { stmt.setString(paramIdx++, status); } } + if (isTagsProvided) { + for (String tag : tagList) { + stmt.setString(paramIdx++, tag); + } + stmt.setInt(paramIdx++, tagList.size()); + } stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx, request.getRowCount()); try (ResultSet rs = stmt.executeQuery()) { devices = new ArrayList<>(); while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); + Device device = DeviceManagementDAOUtil.loadDevice(rs, true); devices.add(device); } return devices; @@ -485,6 +503,8 @@ public class SQLServerDeviceDAOImpl extends GenericDeviceDAOImpl { boolean isSinceProvided = false; String serial = request.getSerialNumber(); boolean isSerialProvided = false; + List tagList = request.getTags(); + boolean isTagsProvided = false; try { conn = getConnection(); @@ -499,7 +519,10 @@ public class SQLServerDeviceDAOImpl extends GenericDeviceDAOImpl { "e.IS_TRANSFERRED, " + "e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + + "e.ID AS ENROLMENT_ID, " + + "(SELECT STRING_AGG(t.NAME, ', ') FROM DM_DEVICE_TAG_MAPPING dtm " + + "JOIN DM_TAG t ON dtm.TAG_ID = t.ID " + + "WHERE dtm.ENROLMENT_ID = e.ID) AS TAGS " + "FROM DM_ENROLMENT e, " + "(SELECT gd.DEVICE_ID, " + "gd.DESCRIPTION, " + @@ -574,6 +597,18 @@ public class SQLServerDeviceDAOImpl extends GenericDeviceDAOImpl { } } } + + if (tagList != null && !tagList.isEmpty()) { + sql += " AND e.ID IN (" + + "SELECT e.ID FROM DM_ENROLMENT e " + + "LEFT JOIN DM_DEVICE_TAG_MAPPING dtm ON e.ID = dtm.ENROLMENT_ID " + + "LEFT JOIN DM_TAG t ON dtm.TAG_ID = t.ID " + + "WHERE t.NAME IN (" + buildTagQuery(tagList); + sql += ") GROUP BY e.ID HAVING COUNT(DISTINCT t.NAME) = ?)"; + isTagsProvided = true; + } else { + sql += " GROUP BY e.ID "; + } sql = sql + " ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { @@ -611,13 +646,19 @@ public class SQLServerDeviceDAOImpl extends GenericDeviceDAOImpl { stmt.setString(paramIdx++, "%" + entry.getValue() + "%"); } } + if (isTagsProvided) { + for (String tag : tagList) { + stmt.setString(paramIdx++, tag); + } + stmt.setInt(paramIdx++, tagList.size()); + } stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx, request.getRowCount()); try (ResultSet rs = stmt.executeQuery()) { devices = new ArrayList<>(); while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); + Device device = DeviceManagementDAOUtil.loadDevice(rs, true); devices.add(device); } return devices; @@ -936,7 +977,7 @@ public class SQLServerDeviceDAOImpl extends GenericDeviceDAOImpl { isOwnershipProvided = true; } if (user != null && !user.isEmpty()) { - query += " AND e.OWNER = ?"; + query += " AND e.OWNER LIKE ?"; isOwnerProvided = true; } if (status != null && !status.isEmpty()) { @@ -967,13 +1008,13 @@ public class SQLServerDeviceDAOImpl extends GenericDeviceDAOImpl { ps.setString(index++, EnrolmentInfo.Status.REMOVED.toString()); ps.setString(index++, EnrolmentInfo.Status.DELETED.toString()); if (isDeviceNameProvided) { - ps.setString(index++, name + "%"); + ps.setString(index++, "%" + name + "%"); } if (isOwnershipProvided) { ps.setString(index++, ownership); } if (isOwnerProvided) { - ps.setString(index++, user); + ps.setString(index++, "%" + user + "%"); } if (isStatusProvided) { for (String deviceStatus : status) { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/enrolment/SQLServerEnrollmentDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/enrolment/SQLServerEnrollmentDAOImpl.java index 73903d15f1..7ff839512f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/enrolment/SQLServerEnrollmentDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/enrolment/SQLServerEnrollmentDAOImpl.java @@ -17,19 +17,19 @@ */ package io.entgra.device.mgt.core.device.mgt.core.dao.impl.enrolment; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; -import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.dao.impl.AbstractEnrollmentDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; -import java.sql.*; -import java.util.ArrayList; +import org.wso2.carbon.context.PrivilegedCarbonContext; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; import java.util.Date; -import java.util.List; public class SQLServerEnrollmentDAOImpl extends AbstractEnrollmentDAOImpl { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/event/GenericEventConfigDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/event/GenericEventConfigDAOImpl.java index 450dcdf012..74cce2b8a9 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/event/GenericEventConfigDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/event/GenericEventConfigDAOImpl.java @@ -18,19 +18,14 @@ package io.entgra.device.mgt.core.device.mgt.core.dao.impl.event; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfig; import io.entgra.device.mgt.core.device.mgt.core.dao.EventManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dao.EventManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.dao.impl.AbstractEventConfigDAO; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; +import java.sql.*; import java.util.ArrayList; import java.util.Date; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/event/H2EventConfigDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/event/H2EventConfigDAOImpl.java index c7d2e994f4..3e3b6edc76 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/event/H2EventConfigDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/event/H2EventConfigDAOImpl.java @@ -18,20 +18,14 @@ package io.entgra.device.mgt.core.device.mgt.core.dao.impl.event; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfig; -import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.dao.EventManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dao.EventManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.dao.impl.AbstractEventConfigDAO; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; +import java.sql.*; import java.util.ArrayList; import java.util.Date; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/geofence/GenericGeofenceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/geofence/GenericGeofenceDAOImpl.java index 67c8bf26f7..f1575b7642 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/geofence/GenericGeofenceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/geofence/GenericGeofenceDAOImpl.java @@ -18,17 +18,16 @@ package io.entgra.device.mgt.core.device.mgt.core.dao.impl.geofence; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfig; import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeofenceData; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dao.EventManagementDAOFactory; -import io.entgra.device.mgt.core.device.mgt.core.dao.GeofenceDAO; import io.entgra.device.mgt.core.device.mgt.core.dao.impl.AbstractGeofenceDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.dto.event.config.GeoFenceGroupMap; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.*; import java.util.Date; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/group/OracleGroupDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/group/OracleGroupDAOImpl.java index 26547f417d..fcb86cf2ee 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/group/OracleGroupDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/group/OracleGroupDAOImpl.java @@ -18,7 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.dao.impl.group; -import org.apache.commons.lang.StringUtils; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.GroupPaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; @@ -27,6 +26,7 @@ import io.entgra.device.mgt.core.device.mgt.core.dao.GroupManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.dao.impl.AbstractGroupDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.dao.util.GroupManagementDAOUtil; +import org.apache.commons.lang.StringUtils; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/group/PostgreSQLGroupDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/group/PostgreSQLGroupDAOImpl.java index da0312c89c..2d17e8bdbb 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/group/PostgreSQLGroupDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/group/PostgreSQLGroupDAOImpl.java @@ -19,9 +19,6 @@ package io.entgra.device.mgt.core.device.mgt.core.dao.impl.group; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroupRoleWrapper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.solr.common.StringUtils; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; import io.entgra.device.mgt.core.device.mgt.core.dao.GroupManagementDAOException; @@ -29,6 +26,9 @@ import io.entgra.device.mgt.core.device.mgt.core.dao.GroupManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.dao.impl.AbstractGroupDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.dao.util.GroupManagementDAOUtil; +import org.apache.solr.common.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/group/SQLServerGroupDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/group/SQLServerGroupDAOImpl.java index 37a0ebba80..340705e28f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/group/SQLServerGroupDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/group/SQLServerGroupDAOImpl.java @@ -18,7 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.dao.impl.group; -import org.apache.commons.lang.StringUtils; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.GroupPaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; @@ -27,6 +26,7 @@ import io.entgra.device.mgt.core.device.mgt.core.dao.GroupManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.dao.impl.AbstractGroupDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.dao.util.GroupManagementDAOUtil; +import org.apache.commons.lang.StringUtils; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java index 6039dee55f..2debb25a38 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java @@ -18,18 +18,16 @@ package io.entgra.device.mgt.core.device.mgt.core.dao.impl.tracker; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.TrackerDeviceInfo; import io.entgra.device.mgt.core.device.mgt.common.TrackerGroupInfo; import io.entgra.device.mgt.core.device.mgt.common.TrackerPermissionInfo; -import io.entgra.device.mgt.core.device.mgt.core.dao.TrackerManagementDAOFactory; -import io.entgra.device.mgt.core.device.mgt.core.dao.TrackerManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dao.TrackerDAO; -import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; +import io.entgra.device.mgt.core.device.mgt.core.dao.TrackerManagementDAOException; +import io.entgra.device.mgt.core.device.mgt.core.dao.TrackerManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.dao.util.TrackerManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.traccar.common.TraccarHandlerConstants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/util/DeviceManagementDAOUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/util/DeviceManagementDAOUtil.java index a8529398c7..3eebdccc9d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/util/DeviceManagementDAOUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/util/DeviceManagementDAOUtil.java @@ -17,34 +17,38 @@ */ package io.entgra.device.mgt.core.device.mgt.core.dao.util; -import java.sql.*; -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.*; -import java.util.Date; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.el.lang.ELSupport; -import org.wso2.carbon.context.CarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.DeviceBilling; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceInfo; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceLocationHistorySnapshot; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceMonitoringData; -import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceStatus; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import javax.naming.InitialContext; import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Date; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.List; +import java.util.ArrayList; +import java.util.Map; public final class DeviceManagementDAOUtil { @@ -143,6 +147,10 @@ public final class DeviceManagementDAOUtil { }*/ public static EnrolmentInfo loadEnrolment(ResultSet rs) throws SQLException { + return loadEnrolment(rs, false); + } + + public static EnrolmentInfo loadEnrolment(ResultSet rs, boolean isTagsProvided) throws SQLException { EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); enrolmentInfo.setId(rs.getInt("ENROLMENT_ID")); enrolmentInfo.setOwner(rs.getString("OWNER")); @@ -151,6 +159,16 @@ public final class DeviceManagementDAOUtil { enrolmentInfo.setDateOfEnrolment(rs.getTimestamp("DATE_OF_ENROLMENT").getTime()); enrolmentInfo.setDateOfLastUpdate(rs.getTimestamp("DATE_OF_LAST_UPDATE").getTime()); enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(rs.getString("STATUS"))); + if (isTagsProvided) { + List tags = new ArrayList<>(); + String tagColumn = rs.getString("TAGS"); + if (tagColumn != null) { + for (String tag : tagColumn.split(",")) { + tags.add(tag.trim()); + } + } + enrolmentInfo.setTags(tags); + } return enrolmentInfo; } @@ -224,6 +242,10 @@ public final class DeviceManagementDAOUtil { } public static Device loadDevice(ResultSet rs) throws SQLException { + return loadDevice(rs, false); + } + + public static Device loadDevice(ResultSet rs, boolean isTagsProvided) throws SQLException { Device device = new Device(); device.setId(rs.getInt("DEVICE_ID")); device.setName(rs.getString("DEVICE_NAME")); @@ -231,7 +253,7 @@ public final class DeviceManagementDAOUtil { device.setType(rs.getString("DEVICE_TYPE")); device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); device.setLastUpdatedTimeStamp(rs.getTimestamp("LAST_UPDATED_TIMESTAMP").getTime()); - device.setEnrolmentInfo(loadEnrolment(rs)); + device.setEnrolmentInfo(loadEnrolment(rs, isTagsProvided)); return device; } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/util/GroupManagementDAOUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/util/GroupManagementDAOUtil.java index 82f3c05cc6..42307e6b74 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/util/GroupManagementDAOUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/util/GroupManagementDAOUtil.java @@ -18,9 +18,9 @@ package io.entgra.device.mgt.core.device.mgt.core.dao.util; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; import javax.naming.InitialContext; import javax.sql.DataSource; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/util/TagManagementDAOUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/util/TagManagementDAOUtil.java new file mode 100644 index 0000000000..71b79e013f --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/util/TagManagementDAOUtil.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.core.dao.util; + +import io.entgra.device.mgt.core.device.mgt.common.tag.mgt.DeviceTag; +import io.entgra.device.mgt.core.device.mgt.common.tag.mgt.Tag; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.naming.InitialContext; +import javax.sql.DataSource; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Hashtable; + +/** + * This class represents utilities required to work with tag management data + */ +public final class TagManagementDAOUtil { + + private static final Log log = LogFactory.getLog(TagManagementDAOUtil.class); + + /** + * Cleanup resources used to transaction + * + * @param stmt Prepared statement used + * @param rs Obtained results set + */ + public static void cleanupResources(PreparedStatement stmt, ResultSet rs) { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing result set", e); + } + } + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing prepared statement", e); + } + } + } + + /** + * Lookup datasource using name and jndi properties + * + * @param dataSourceName Name of datasource to lookup + * @param jndiProperties Hash table of JNDI Properties + * @return datasource looked + */ + public static DataSource lookupDataSource(String dataSourceName, + final Hashtable jndiProperties) { + try { + if (jndiProperties == null || jndiProperties.isEmpty()) { + return (DataSource) InitialContext.doLookup(dataSourceName); + } + final InitialContext context = new InitialContext(jndiProperties); + return (DataSource) context.lookup(dataSourceName); + } catch (Exception e) { + throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); + } + } + + public static Tag loadTag(ResultSet resultSet) throws SQLException { + Tag tag = new Tag(); + tag.setId(resultSet.getInt("ID")); + tag.setName(resultSet.getString("NAME")); + tag.setDescription(resultSet.getString("DESCRIPTION")); + return tag; + } + + public static DeviceTag loadDeviceTagMapping(ResultSet resultSet) throws SQLException { + DeviceTag deviceTag = new DeviceTag(); + deviceTag.setEnrolmentId(resultSet.getInt("ENROLMENT_ID")); + deviceTag.setTagId(resultSet.getInt("TAG_ID")); + return deviceTag; + } + +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/util/TrackerManagementDAOUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/util/TrackerManagementDAOUtil.java index f7404d37b2..8bbaed0959 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/util/TrackerManagementDAOUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/util/TrackerManagementDAOUtil.java @@ -18,12 +18,12 @@ package io.entgra.device.mgt.core.device.mgt.core.dao.util; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.TrackerDeviceInfo; import io.entgra.device.mgt.core.device.mgt.common.TrackerGroupInfo; import io.entgra.device.mgt.core.device.mgt.common.TrackerPermissionInfo; import io.entgra.device.mgt.core.device.mgt.core.dao.TrackerManagementDAOException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.naming.InitialContext; import javax.sql.DataSource; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/DeviceInformationManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/DeviceInformationManager.java index fdf98a86a5..4dc7fb1931 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/DeviceInformationManager.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/DeviceInformationManager.java @@ -21,10 +21,8 @@ package io.entgra.device.mgt.core.device.mgt.core.device.details.mgt; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceInfo; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceLocation; -import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/dao/DeviceDetailsDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/dao/DeviceDetailsDAO.java index bba9c7b037..13a9c038d2 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/dao/DeviceDetailsDAO.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/dao/DeviceDetailsDAO.java @@ -20,7 +20,6 @@ package io.entgra.device.mgt.core.device.mgt.core.device.details.mgt.dao; import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceInfo; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceLocation; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java index e81a98ba35..c53d9526cc 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java @@ -19,18 +19,17 @@ package io.entgra.device.mgt.core.device.mgt.core.device.details.mgt.dao.impl; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceInfo; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceLocation; -import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.device.details.mgt.dao.DeviceDetailsDAO; import io.entgra.device.mgt.core.device.mgt.core.device.details.mgt.dao.DeviceDetailsMgtDAOException; import io.entgra.device.mgt.core.device.mgt.core.geo.geoHash.GeoHashGenerator; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dto/DeviceType.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dto/DeviceType.java index d25706c35f..b2a3c205d6 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dto/DeviceType.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dto/DeviceType.java @@ -18,9 +18,9 @@ package io.entgra.device.mgt.core.device.mgt.core.dto; +import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; import java.io.Serializable; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/event/config/EventConfigurationProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/event/config/EventConfigurationProviderServiceImpl.java index 6de751af8e..881586d9d5 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/event/config/EventConfigurationProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/event/config/EventConfigurationProviderServiceImpl.java @@ -19,27 +19,23 @@ package io.entgra.device.mgt.core.device.mgt.core.event.config; import com.google.common.collect.Lists; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfig; import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfigurationException; import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfigurationProviderService; import io.entgra.device.mgt.core.device.mgt.common.event.config.EventMetaData; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; -import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; -import io.entgra.device.mgt.core.device.mgt.core.dao.*; +import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; +import io.entgra.device.mgt.core.device.mgt.core.dao.EventConfigDAO; +import io.entgra.device.mgt.core.device.mgt.core.dao.EventManagementDAOException; +import io.entgra.device.mgt.core.device.mgt.core.dao.EventManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.geo.task.GeoFenceEventOperationManager; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; +import java.util.*; public class EventConfigurationProviderServiceImpl implements EventConfigurationProviderService { private static final Log log = LogFactory.getLog(EventConfigurationProviderServiceImpl.class); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/event/config/EventOperationExecutor.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/event/config/EventOperationExecutor.java index 7151eaeef7..bc0a51b548 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/event/config/EventOperationExecutor.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/event/config/EventOperationExecutor.java @@ -19,17 +19,10 @@ package io.entgra.device.mgt.core.device.mgt.core.event.config; import com.google.gson.Gson; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; -import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfig; -import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfigurationException; -import io.entgra.device.mgt.core.device.mgt.common.event.config.EventMetaData; -import io.entgra.device.mgt.core.device.mgt.common.event.config.EventOperation; -import io.entgra.device.mgt.core.device.mgt.common.event.config.EventRevokeOperation; +import io.entgra.device.mgt.core.device.mgt.common.event.config.*; import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidDeviceException; import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoFenceEventMeta; import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoLocationBasedServiceException; @@ -43,12 +36,11 @@ import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationMgtConst import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.ProfileOperation; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; /** * Event create/revoke operation creation task. diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/event/config/GroupAssignmentEventOperationExecutor.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/event/config/GroupAssignmentEventOperationExecutor.java index 37a80ef7e5..e6f292d166 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/event/config/GroupAssignmentEventOperationExecutor.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/event/config/GroupAssignmentEventOperationExecutor.java @@ -19,9 +19,6 @@ package io.entgra.device.mgt.core.device.mgt.core.event.config; import com.google.gson.Gson; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfigurationException; @@ -40,6 +37,9 @@ import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHo import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationMgtConstants; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.ProfileOperation; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.util.ArrayList; import java.util.Arrays; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java index f11914d5ea..7cc550730e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java @@ -20,21 +20,6 @@ package io.entgra.device.mgt.core.device.mgt.core.geo.service; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; -import org.apache.axis2.AxisFault; -import org.apache.axis2.client.Options; -import org.apache.axis2.client.Stub; -import org.apache.axis2.java.security.SSLProtocolSocketFactory; -import org.apache.axis2.transport.http.HTTPConstants; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.protocol.Protocol; -import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; -import org.apache.commons.io.IOUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.base.ServerConfiguration; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.core.util.Utils; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants.GeoServices; @@ -43,13 +28,7 @@ import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfig; import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfigurationException; import io.entgra.device.mgt.core.device.mgt.common.event.config.EventConfigurationProviderService; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.Alert; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.AlertAlreadyExistException; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoFence; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoFenceEventMeta; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoLocationBasedServiceException; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoLocationProviderService; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeofenceData; +import io.entgra.device.mgt.core.device.mgt.common.geo.service.*; import io.entgra.device.mgt.core.device.mgt.core.cache.impl.GeoCacheManagerImpl; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; @@ -59,11 +38,26 @@ import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUti import io.entgra.device.mgt.core.device.mgt.core.dto.event.config.GeoFenceGroupMap; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationMgtConstants; -import org.wso2.carbon.event.processor.stub.EventProcessorAdminServiceStub; -import org.wso2.carbon.event.processor.stub.types.ExecutionPlanConfigurationDto; import io.entgra.device.mgt.core.identity.jwt.client.extension.JWTClient; import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; +import org.apache.axis2.AxisFault; +import org.apache.axis2.client.Options; +import org.apache.axis2.client.Stub; +import org.apache.axis2.java.security.SSLProtocolSocketFactory; +import org.apache.axis2.transport.http.HTTPConstants; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.protocol.Protocol; +import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; +import org.apache.commons.io.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.base.ServerConfiguration; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.core.util.Utils; +import org.wso2.carbon.event.processor.stub.EventProcessorAdminServiceStub; +import org.wso2.carbon.event.processor.stub.types.ExecutionPlanConfigurationDto; import org.wso2.carbon.registry.api.Registry; import org.wso2.carbon.registry.api.RegistryException; import org.wso2.carbon.registry.api.Resource; @@ -78,20 +72,10 @@ import java.io.InputStream; import java.io.StringWriter; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; +import java.security.*; import java.security.cert.CertificateException; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; +import java.util.*; import static io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants.GeoServices.DAS_PORT; import static io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants.GeoServices.DEFAULT_HTTP_PROTOCOL; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/geo/task/GeoFenceEventOperationManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/geo/task/GeoFenceEventOperationManager.java index 5dbca35d38..2ec79e54e6 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/geo/task/GeoFenceEventOperationManager.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/geo/task/GeoFenceEventOperationManager.java @@ -18,14 +18,14 @@ package io.entgra.device.mgt.core.device.mgt.core.geo.task; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.event.config.EventMetaData; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.event.config.EventOperationExecutor; import io.entgra.device.mgt.core.device.mgt.core.event.config.GroupAssignmentEventOperationExecutor; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/ActivityDataPurgingServiceComponent.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/ActivityDataPurgingServiceComponent.java index 233b1f80bf..6b70a2dc6a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/ActivityDataPurgingServiceComponent.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/ActivityDataPurgingServiceComponent.java @@ -18,9 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.internal; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; import io.entgra.device.mgt.core.device.mgt.core.archival.dao.ArchivalDestinationDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.archival.dao.ArchivalSourceDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; @@ -29,26 +26,19 @@ import io.entgra.device.mgt.core.device.mgt.core.config.datasource.DataSourceCon import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.task.ArchivalTaskManager; import io.entgra.device.mgt.core.device.mgt.core.task.impl.ArchivalTaskManagerImpl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.ntask.core.service.TaskService; -/** - * @scr.component name="org.wso2.carbon.activity.data.archival" immediate="true" - * @scr.reference name="device.ntask.component" - * interface="org.wso2.carbon.ntask.core.service.TaskService" - * cardinality="1..1" - * policy="dynamic" - * bind="setTaskService" - * unbind="unsetTaskService" - * @scr.reference name="org.wso2.carbon.device.manager" - * interface="io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDeviceManagementService" - * unbind="unsetDeviceManagementService" - */ +@Component( + name = "io.entgra.device.mgt.core.device.mgt.core.internal.ActivityDataPurgingServiceComponent", + immediate = true) public class ActivityDataPurgingServiceComponent { private static Log log = LogFactory.getLog(ActivityDataPurgingServiceComponent.class); + @Activate protected void activate(ComponentContext componentContext) { try { if (log.isDebugEnabled()) { @@ -99,6 +89,12 @@ public class ActivityDataPurgingServiceComponent { } } + @Reference( + name = "task.service", + service = org.wso2.carbon.ntask.core.service.TaskService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetTaskService") protected void setTaskService(TaskService taskService) { if (log.isDebugEnabled()) { log.debug("Setting the task service."); @@ -113,6 +109,12 @@ public class ActivityDataPurgingServiceComponent { DeviceManagementDataHolder.getInstance().setTaskService(null); } + @Reference( + name = "device.mgt.provider.service", + service = io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDeviceManagementService") protected void setDeviceManagementService(DeviceManagementProviderService deviceManagementService){ } @@ -122,6 +124,7 @@ public class ActivityDataPurgingServiceComponent { } @SuppressWarnings("unused") + @Deactivate protected void deactivate(ComponentContext componentContext) { } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementDataHolder.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementDataHolder.java index 48d573a5fa..c9ae912a70 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementDataHolder.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementDataHolder.java @@ -100,6 +100,7 @@ public class DeviceManagementDataHolder { private DeviceStatusManagementService deviceStatusManagementService; private APIApplicationServices apiApplicationServices; private PublisherRESTAPIServices publisherRESTAPIServices; + private DeviceManagementStartupHandler deviceManagementStartupHandler; private final Map deviceStatusTaskPluginConfigs = Collections.synchronizedMap( new HashMap<>()); @@ -126,18 +127,18 @@ public class DeviceManagementDataHolder { public void setRealmService(RealmService realmService) { this.realmService = realmService; - this.setTenantManager(realmService); + setTenantManager(realmService != null ? + realmService.getTenantManager() : null); } public TenantManager getTenantManager() { - return tenantManager; - } - - private void setTenantManager(RealmService realmService) { - if (realmService == null) { - throw new IllegalStateException("Realm service is not initialized properly"); + if (tenantManager == null) { + throw new IllegalStateException("Tenant manager is not initialized properly"); } - this.tenantManager = realmService.getTenantManager(); + return tenantManager; } + + private void setTenantManager(TenantManager tenantManager) { + this.tenantManager = tenantManager; } public DeviceManagementProviderService getDeviceManagementProvider() { @@ -457,4 +458,12 @@ public class DeviceManagementDataHolder { public void setGroupAccessAuthorizationService(GroupAccessAuthorizationService groupAccessAuthorizationService) { this.groupAccessAuthorizationService = groupAccessAuthorizationService; } + + public DeviceManagementStartupHandler getDeviceManagementStartupHandler() { + return deviceManagementStartupHandler; + } + + public void setDeviceManagementStartupHandler(DeviceManagementStartupHandler deviceManagementStartupHandler) { + this.deviceManagementStartupHandler = deviceManagementStartupHandler; + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementServiceComponent.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementServiceComponent.java index b2e1529f40..c648965773 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementServiceComponent.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementServiceComponent.java @@ -21,6 +21,8 @@ import io.entgra.device.mgt.core.device.mgt.common.authorization.GroupAccessAuth import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.DeviceStatusManagementService; import io.entgra.device.mgt.core.device.mgt.core.authorization.GroupAccessAuthorizationServiceImpl; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.DeviceStatusManagementServiceImpl; +import io.entgra.device.mgt.core.device.mgt.core.service.TagManagementProviderService; +import io.entgra.device.mgt.core.device.mgt.core.service.TagManagementProviderServiceImpl; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -91,6 +93,7 @@ import io.entgra.device.mgt.core.device.mgt.core.traccar.api.service.impl.Device import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagementSchemaInitializer; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; import io.entgra.device.mgt.core.transport.mgt.email.sender.core.service.EmailSenderService; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.user.core.service.RealmService; @@ -104,57 +107,9 @@ import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -/** - * @scr.component name="org.wso2.carbon.device.manager" immediate="true" - * @scr.reference name="user.realmservice.default" - * interface="org.wso2.carbon.user.core.service.RealmService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRealmService" - * unbind="unsetRealmService" - * @scr.reference name="device.manager.service" - * interface="io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService" - * cardinality="0..n" - * policy="dynamic" - * bind="setDeviceManagementService" - * unbind="unsetDeviceManagementService" - * @scr.reference name="registry.service" - * interface="org.wso2.carbon.registry.core.service.RegistryService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRegistryService" - * unbind="unsetRegistryService" - * @scr.reference name="org.wso2.carbon.ndatasource" - * interface="org.wso2.carbon.ndatasource.core.DataSourceService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDataSourceService" - * unbind="unsetDataSourceService" - * @scr.reference name="config.context.service" - * interface="org.wso2.carbon.utils.ConfigurationContextService" - * cardinality="0..1" - * policy="dynamic" - * bind="setConfigurationContextService" - * unbind="unsetConfigurationContextService" - * @scr.reference name="email.sender.service" - * interface="io.entgra.device.mgt.core.transport.mgt.email.sender.core.service.EmailSenderService" - * cardinality="0..1" - * policy="dynamic" - * bind="setEmailSenderService" - * unbind="unsetEmailSenderService" - * @scr.reference name="device.type.generator.service" - * interface="io.entgra.device.mgt.core.device.mgt.common.spi.DeviceTypeGeneratorService" - * cardinality="0..1" - * policy="dynamic" - * bind="setDeviceTypeGeneratorService" - * unbind="unsetDeviceTypeGeneratorService" - * @scr.reference name="entgra.heart.beat.service" - * interface="io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService" - * cardinality="0..1" - * policy="dynamic" - * bind="setHeartBeatService" - * unbind="unsetHeartBeatService" - */ +@Component( + name = "io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementServiceComponent", + immediate = true) public class DeviceManagementServiceComponent { private static final Object LOCK = new Object(); @@ -183,6 +138,7 @@ public class DeviceManagementServiceComponent { } @SuppressWarnings("unused") + @Activate protected void activate(ComponentContext componentContext) { try { if (log.isDebugEnabled()) { @@ -282,6 +238,7 @@ public class DeviceManagementServiceComponent { } @SuppressWarnings("unused") + @Deactivate protected void deactivate(ComponentContext componentContext) { //do nothing } @@ -302,8 +259,10 @@ public class DeviceManagementServiceComponent { TenantCreateObserver listener = new TenantCreateObserver(); bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(), listener, null); - UserRoleCreateObserver userRoleCreateObserver = new UserRoleCreateObserver(); - bundleContext.registerService(ServerStartupObserver.class.getName(), userRoleCreateObserver, null); + /* Registering Device Management Startup Handler */ + DeviceManagementStartupHandler deviceManagementStartupHandler = new DeviceManagementStartupHandler(); + DeviceManagementDataHolder.getInstance().setDeviceManagementStartupHandler(deviceManagementStartupHandler); + bundleContext.registerService(ServerStartupObserver.class.getName(), deviceManagementStartupHandler, null); /* Registering Device Management Service */ DeviceManagementProviderService deviceManagementProvider = new DeviceManagementProviderServiceImpl(); @@ -349,6 +308,10 @@ public class DeviceManagementServiceComponent { ReportManagementService reportManagementService = new ReportManagementServiceImpl(); bundleContext.registerService(ReportManagementService.class.getName(), reportManagementService, null); + /* Registering Tag Management Service */ + TagManagementProviderService tagManagementProviderService = new TagManagementProviderServiceImpl(); + bundleContext.registerService(TagManagementProviderService.class.getName(), tagManagementProviderService, null); + /* Registering DeviceAccessAuthorization Service */ DeviceAccessAuthorizationService deviceAccessAuthorizationService = new DeviceAccessAuthorizationServiceImpl(); DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService(deviceAccessAuthorizationService); @@ -383,15 +346,15 @@ public class DeviceManagementServiceComponent { bundleContext.registerService(WhiteLabelManagementService.class.getName(), whiteLabelManagementService, null); /* Registering DeviceState Filter Service */ - DeviceStatusManagementService deviceStatusManagemntService = new DeviceStatusManagementServiceImpl(); - DeviceManagementDataHolder.getInstance().setDeviceStatusManagementService(deviceStatusManagemntService); + DeviceStatusManagementService deviceStatusManagementService = new DeviceStatusManagementServiceImpl(); + DeviceManagementDataHolder.getInstance().setDeviceStatusManagementService(deviceStatusManagementService); try { - deviceStatusManagemntService.addDefaultDeviceStatusFilterIfNotExist(tenantId); + deviceStatusManagementService.addDefaultDeviceStatusFilterIfNotExist(tenantId); } catch (Throwable e) { log.error("Error occurred while adding default tenant device status", e); } - bundleContext.registerService(DeviceStatusManagementService.class.getName(), deviceStatusManagemntService, null); + bundleContext.registerService(DeviceStatusManagementService.class.getName(), deviceStatusManagementService, null); /* Registering Event Configuration Service */ EventConfigurationProviderService eventConfigurationService = new EventConfigurationProviderServiceImpl(); @@ -463,6 +426,12 @@ public class DeviceManagementServiceComponent { * * @param deviceManagementService An instance of DeviceManagementService */ + @Reference( + name = "device.mgt.service", + service = io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService.class, + cardinality = ReferenceCardinality.MULTIPLE, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDeviceManagementService") protected void setDeviceManagementService(DeviceManagementService deviceManagementService) { try { if (log.isDebugEnabled()) { @@ -503,6 +472,12 @@ public class DeviceManagementServiceComponent { * * @param realmService An instance of RealmService */ + @Reference( + name = "realm.service", + service = org.wso2.carbon.user.core.service.RealmService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRealmService") protected void setRealmService(RealmService realmService) { if (log.isDebugEnabled()) { log.debug("Setting Realm Service"); @@ -527,6 +502,12 @@ public class DeviceManagementServiceComponent { * * @param registryService An instance of RegistryService */ + @Reference( + name = "registry.service", + service = org.wso2.carbon.registry.core.service.RegistryService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRegistryService") protected void setRegistryService(RegistryService registryService) { if (log.isDebugEnabled()) { log.debug("Setting Registry Service"); @@ -551,6 +532,12 @@ public class DeviceManagementServiceComponent { * * @param heartBeatService An instance of HeartBeatManagementService */ + @Reference( + name = "heart.beat.service", + service = io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetHeartBeatService") protected void setHeartBeatService(HeartBeatManagementService heartBeatService) { if (log.isDebugEnabled()) { log.debug("Setting Heart Beat Service"); @@ -568,6 +555,12 @@ public class DeviceManagementServiceComponent { DeviceManagementDataHolder.getInstance().setHeartBeatService(null); } + @Reference( + name = "datasource.service", + service = org.wso2.carbon.ndatasource.core.DataSourceService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDataSourceService") protected void setDataSourceService(DataSourceService dataSourceService) { /* This is to avoid mobile device management component getting initialized before the underlying datasources are registered */ @@ -580,6 +573,12 @@ public class DeviceManagementServiceComponent { //do nothing } + @Reference( + name = "configuration.context.service", + service = org.wso2.carbon.utils.ConfigurationContextService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetConfigurationContextService") protected void setConfigurationContextService(ConfigurationContextService configurationContextService) { if (log.isDebugEnabled()) { log.debug("Setting ConfigurationContextService"); @@ -594,6 +593,12 @@ public class DeviceManagementServiceComponent { DeviceManagementDataHolder.getInstance().setConfigurationContextService(null); } + @Reference( + name = "email.sender.service", + service = io.entgra.device.mgt.core.transport.mgt.email.sender.core.service.EmailSenderService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetEmailSenderService") protected void setEmailSenderService(EmailSenderService emailSenderService) { if (log.isDebugEnabled()) { log.debug("Setting Email Sender Service"); @@ -609,6 +614,12 @@ public class DeviceManagementServiceComponent { } + @Reference( + name = "device.task.service", + service = io.entgra.device.mgt.core.device.mgt.core.task.DeviceTaskManagerService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDeviceTaskManagerService") protected void setDeviceTaskManagerService(DeviceTaskManagerService deviceTaskManagerService) { if (log.isDebugEnabled()) { } @@ -626,6 +637,12 @@ public class DeviceManagementServiceComponent { * * @param deviceTypeGeneratorService An Instance of DeviceTypeGeneratorService */ + @Reference( + name = "device.type.generator.service", + service = io.entgra.device.mgt.core.device.mgt.common.spi.DeviceTypeGeneratorService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDeviceTypeGeneratorService") protected void setDeviceTypeGeneratorService(DeviceTypeGeneratorService deviceTypeGeneratorService) { if (log.isDebugEnabled()) { log.debug("Un setting Device DeviceTypeGeneratorService"); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementStartupHandler.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementStartupHandler.java new file mode 100644 index 0000000000..56fabedf6c --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementStartupHandler.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.core.internal; + +import com.google.gson.Gson; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; +import io.entgra.device.mgt.core.device.mgt.core.DeviceManagementConstants; +import io.entgra.device.mgt.core.device.mgt.core.operation.change.status.task.dto.OperationConfig; +import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationDAO; +import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; +import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.core.ServerStartupObserver; +import org.wso2.carbon.user.api.AuthorizationManager; +import org.wso2.carbon.user.api.Permission; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.api.UserStoreManager; +import org.wso2.carbon.utils.multitenancy.MultitenantConstants; + +public class DeviceManagementStartupHandler implements ServerStartupObserver { + private static final Log log = LogFactory.getLog(DeviceManagementStartupHandler.class); + private static final Gson gson = new Gson(); + private static final String OPERATION_CONFIG = "OPERATION_CONFIG"; + private static final String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; + + @Override + public void completingServerStartup() { + + } + + @Override + public void completedServerStartup() { + userRoleCreateObserver(); + operationStatusChangeObserver(); + } + + private void userRoleCreateObserver() { + try { + UserStoreManager userStoreManager = + DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm( + MultitenantConstants.SUPER_TENANT_ID).getUserStoreManager(); + String tenantAdminName = + DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm( + MultitenantConstants.SUPER_TENANT_ID).getRealmConfiguration().getAdminUserName(); + AuthorizationManager authorizationManager = DeviceManagementDataHolder.getInstance().getRealmService() + .getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).getAuthorizationManager(); + + if (!userStoreManager.isExistingRole(DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN)) { + userStoreManager.addRole( + DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN, + null, + DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_ADMIN); + } else { + for (Permission permission : DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_ADMIN) { + authorizationManager.authorizeRole(DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN, + permission.getResourceId(), permission.getAction()); + } + } + if (!userStoreManager.isExistingRole(DeviceManagementConstants.User.DEFAULT_DEVICE_USER)) { + userStoreManager.addRole( + DeviceManagementConstants.User.DEFAULT_DEVICE_USER, + null, + DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_USER); + } else { + for (Permission permission : DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_USER) { + authorizationManager.authorizeRole(DeviceManagementConstants.User.DEFAULT_DEVICE_USER, + permission.getResourceId(), permission.getAction()); + } + } + userStoreManager.updateRoleListOfUser(tenantAdminName, null, + new String[]{DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN, + DeviceManagementConstants.User.DEFAULT_DEVICE_USER}); + + if (log.isDebugEnabled()) { + log.debug("Device management roles: " + DeviceManagementConstants.User.DEFAULT_DEVICE_USER + ", " + + DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN + " created for the tenant:" + tenantDomain + "." + ); + log.debug("Tenant administrator: " + tenantAdminName + "@" + tenantDomain + + " is assigned to the role:" + DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN + "." + ); + } + } catch (UserStoreException e) { + log.error("Error occurred while creating roles for the tenant: " + tenantDomain + "."); + } + } + + private void operationStatusChangeObserver () { + MetadataManagementService metadataManagementService = DeviceManagementDataHolder + .getInstance().getMetadataManagementService(); + OperationDAO operationDAO = OperationManagementDAOFactory.getOperationDAO(); + Metadata metadata; + int numOfRecordsUpdated; + try { + metadata = metadataManagementService.retrieveMetadata(OPERATION_CONFIG); + if (metadata != null) { + OperationConfig operationConfiguration = gson.fromJson(metadata.getMetaValue(), OperationConfig.class); + String[] deviceTypes = operationConfiguration.getDeviceTypes(); + String initialOperationStatus = operationConfiguration.getInitialOperationStatus(); + String requiredStatusChange = operationConfiguration.getRequiredStatusChange(); + + for (String deviceType : deviceTypes) { + try { + OperationManagementDAOFactory.beginTransaction(); + try { + numOfRecordsUpdated = operationDAO.updateOperationByDeviceTypeAndInitialStatus(deviceType, + initialOperationStatus, requiredStatusChange); + log.info(numOfRecordsUpdated + " operations updated successfully for the" + deviceType); + OperationManagementDAOFactory.commitTransaction(); + } catch (OperationManagementDAOException e) { + OperationManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while updating operation status. DeviceType : " + deviceType + ", " + + "Initial operation status: " + initialOperationStatus + ", Required status:" + requiredStatusChange; + log.error(msg, e); + } + } catch (TransactionManagementException e) { + String msg = "Transactional error occurred while updating the operation status"; + log.error(msg, e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } + } + } else { + log.info("Operation configuration not provided"); + } + } catch (MetadataManagementException e) { + String msg = "Error occurred while retrieving the operation configuration"; + log.error(msg, e); + } + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceTaskManagerServiceComponent.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceTaskManagerServiceComponent.java index 602e0700a1..ac1c1af740 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceTaskManagerServiceComponent.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceTaskManagerServiceComponent.java @@ -18,10 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.internal; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.framework.BundleContext; -import org.osgi.service.component.ComponentContext; import io.entgra.device.mgt.core.device.mgt.common.DeviceStatusTaskPluginConfig; import io.entgra.device.mgt.core.device.mgt.common.OperationMonitoringTaskConfig; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; @@ -38,20 +34,17 @@ import io.entgra.device.mgt.core.device.mgt.core.status.task.impl.DeviceStatusTa import io.entgra.device.mgt.core.device.mgt.core.task.DeviceMgtTaskException; import io.entgra.device.mgt.core.device.mgt.core.task.DeviceTaskManagerService; import io.entgra.device.mgt.core.device.mgt.core.task.impl.DeviceTaskManagerServiceImpl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.framework.BundleContext; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.ntask.core.service.TaskService; import java.util.Map; - -/** - * @scr.component name="org.wso2.carbon.device.task.manager" immediate="true" - * @scr.reference name="device.ntask.component" - * interface="org.wso2.carbon.ntask.core.service.TaskService" - * cardinality="1..1" - * policy="dynamic" - * bind="setTaskService" - * unbind="unsetTaskService" - */ - +@Component( + name = "io.entgra.device.mgt.core.device.mgt.core.internal.DeviceTaskManagerServiceComponent", + immediate = true) @SuppressWarnings("unused") public class DeviceTaskManagerServiceComponent { @@ -59,6 +52,7 @@ public class DeviceTaskManagerServiceComponent { private DeviceManagementConfig deviceManagementConfig; @SuppressWarnings("unused") + @Activate protected void activate(ComponentContext componentContext) { try { if (log.isDebugEnabled()) { @@ -133,6 +127,7 @@ public class DeviceTaskManagerServiceComponent { } @SuppressWarnings("unused") + @Deactivate protected void deactivate(ComponentContext componentContext) { try { stopOperationMonitoringTask(); @@ -192,6 +187,12 @@ public class DeviceTaskManagerServiceComponent { } } + @Reference( + name = "task.service", + service = org.wso2.carbon.ntask.core.service.TaskService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetTaskService") protected void setTaskService(TaskService taskService) { if (log.isDebugEnabled()) { log.debug("Setting the task service."); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/TenantCreateObserver.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/TenantCreateObserver.java index eb5fe919d2..9f1ce69d12 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/TenantCreateObserver.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/TenantCreateObserver.java @@ -46,7 +46,6 @@ import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.utils.AbstractAxis2ConfigurationContextObserver; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import java.util.ArrayList; import java.util.Arrays; @@ -143,26 +142,6 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser */ private void publishScopesToTenant(String tenantDomain) throws TenantManagementException { if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { - - MetadataManagementService metadataManagementService = DeviceManagementDataHolder.getInstance().getMetadataManagementService(); - - Map superTenantPermScopeMapping = getPermScopeMapping(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - Map subTenantPermScopeMapping = getPermScopeMapping(tenantDomain); - - if (superTenantPermScopeMapping == null) { - msg = "Error occurred while retrieving meta key '" + Constants.PERM_SCOPE_MAPPING_META_KEY + "' for tenant '" + - MultitenantConstants.SUPER_TENANT_DOMAIN_NAME + "'. Hence aborting publishing scopes to tenant: '" + - tenantDomain + "'."; - log.error(msg); - throw new TenantManagementException(msg); - } - if (superTenantPermScopeMapping.equals(subTenantPermScopeMapping)) { - if (log.isDebugEnabled()) { - log.debug( "Scopes in '" + tenantDomain + "' are up to date with super tenant scopes."); - } - return; - } - APIApplicationServices apiApplicationServices = DeviceManagementDataHolder.getInstance().getApiApplicationServices(); APIApplicationKey apiApplicationKey; AccessTokenInfo accessTokenInfo; @@ -172,7 +151,9 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); - apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); + apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials( + "ClientForScopePublish", + "client_credentials password refresh_token"); accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); } catch (APIServicesException e) { @@ -268,10 +249,6 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser } } } - - if (missingScopes.size() > 0 || deletedScopes.size() > 0) { - updatePermScopeMetaData(superTenantPermScopeMapping, metadataManagementService); - } } else { if (log.isDebugEnabled()) { log.debug("Starting to publish shared scopes to newly created tenant: '" + tenantDomain + "'."); @@ -279,7 +256,6 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser publishSharedScopes(Arrays.asList(superTenantScopes), publisherRESTAPIServices, apiApplicationKey, accessTokenInfo); - updatePermScopeMetaData(superTenantPermScopeMapping, metadataManagementService); } } else { msg = "Unable to publish scopes to sub tenants due to super tenant scopes list being empty."; @@ -298,15 +274,6 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser msg = "Error occurred while publishing scopes to '" + tenantDomain + "' tenant space."; log.error(msg, e); throw new TenantManagementException(msg, e); - } catch (MetadataManagementException e) { - msg = "Error occurred trying to create metadata entry '" + Constants.PERM_SCOPE_MAPPING_META_KEY + "'."; - log.error(msg); - throw new TenantManagementException(msg); - } catch (MetadataKeyAlreadyExistsException e) { - msg = "Error occurred trying to create metadata entry '" + Constants.PERM_SCOPE_MAPPING_META_KEY + "'. The meta key " + - "already exists."; - log.error(msg); - throw new TenantManagementException(msg); } finally { APIPublisherUtils.removeScopePublishUserIfExists(tenantDomain); PrivilegedCarbonContext.endTenantFlow(); @@ -383,7 +350,9 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser // in order to see if any new scopes were added or deleted PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); - APIApplicationKey superTenantApiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); + APIApplicationKey superTenantApiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials( + "ClientForScopePublish", + "client_credentials password refresh_token"); AccessTokenInfo superTenantAccessToken = apiApplicationServices.generateAccessTokenFromRegisteredApplication( superTenantApiApplicationKey.getClientId(), superTenantApiApplicationKey.getClientSecret()); return publisherRESTAPIServices.getScopes(superTenantApiApplicationKey, superTenantAccessToken); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/UserRoleCreateObserver.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/UserRoleCreateObserver.java deleted file mode 100644 index adcb5ed597..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/UserRoleCreateObserver.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.core.internal; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.core.ServerStartupObserver; -import io.entgra.device.mgt.core.device.mgt.core.DeviceManagementConstants; -import org.wso2.carbon.user.api.AuthorizationManager; -import org.wso2.carbon.user.api.Permission; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.api.UserStoreManager; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; - -public class UserRoleCreateObserver implements ServerStartupObserver { - private static final Log log = LogFactory.getLog(UserRoleCreateObserver.class); - @Override - public void completingServerStartup() { - - } - - @Override - public void completedServerStartup() { - String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; - - try { - UserStoreManager userStoreManager = - DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm( - MultitenantConstants.SUPER_TENANT_ID).getUserStoreManager(); - String tenantAdminName = - DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm( - MultitenantConstants.SUPER_TENANT_ID).getRealmConfiguration().getAdminUserName(); - AuthorizationManager authorizationManager = DeviceManagementDataHolder.getInstance().getRealmService() - .getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).getAuthorizationManager(); - - if (!userStoreManager.isExistingRole(DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN)) { - userStoreManager.addRole( - DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN, - null, - DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_ADMIN); - } else { - for (Permission permission : DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_ADMIN) { - authorizationManager.authorizeRole(DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN, - permission.getResourceId(), permission.getAction()); - } - } - if (!userStoreManager.isExistingRole(DeviceManagementConstants.User.DEFAULT_DEVICE_USER)) { - userStoreManager.addRole( - DeviceManagementConstants.User.DEFAULT_DEVICE_USER, - null, - DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_USER); - } else { - for (Permission permission : DeviceManagementConstants.User.PERMISSIONS_FOR_DEVICE_USER) { - authorizationManager.authorizeRole(DeviceManagementConstants.User.DEFAULT_DEVICE_USER, - permission.getResourceId(), permission.getAction()); - } - } - userStoreManager.updateRoleListOfUser(tenantAdminName, null, - new String[] {DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN, - DeviceManagementConstants.User.DEFAULT_DEVICE_USER}); - - if (log.isDebugEnabled()) { - log.debug("Device management roles: " + DeviceManagementConstants.User.DEFAULT_DEVICE_USER + ", " + - DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN + " created for the tenant:" + tenantDomain + "." - ); - log.debug("Tenant administrator: " + tenantAdminName + "@" + tenantDomain + - " is assigned to the role:" + DeviceManagementConstants.User.DEFAULT_DEVICE_ADMIN + "." - ); - } - } catch (UserStoreException e) { - log.error("Error occurred while creating roles for the tenant: " + tenantDomain + "."); - } - } -} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/DeviceStatusManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/DeviceStatusManagementServiceImpl.java index 1daea9fd24..42c0966da5 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/DeviceStatusManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/DeviceStatusManagementServiceImpl.java @@ -21,6 +21,7 @@ package io.entgra.device.mgt.core.device.mgt.core.metadata.mgt; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataKeyNotFoundException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.AllowedDeviceStatus; @@ -42,12 +43,12 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; - public class DeviceStatusManagementServiceImpl implements DeviceStatusManagementService { private static final Log log = LogFactory.getLog(DeviceStatusManagementServiceImpl.class); private final MetadataDAO metadataDAO; + private static final Gson gson = new Gson(); public DeviceStatusManagementServiceImpl() { this.metadataDAO = MetadataManagementDAOFactory.getMetadataDAO(); @@ -57,12 +58,11 @@ public class DeviceStatusManagementServiceImpl implements DeviceStatusManagement public void addDefaultDeviceStatusFilterIfNotExist(int tenantId) throws MetadataManagementException { try { MetadataManagementDAOFactory.beginTransaction(); - if (!metadataDAO.isExist(tenantId, MetadataConstants.ALLOWED_DEVICE_STATUS_META_KEY) && !metadataDAO.isExist(tenantId, MetadataConstants.IS_DEVICE_STATUS_CHECK_META_KEY)) { - Metadata defaultDeviceStatusMetadata = constructDeviceStatusMetadata(getDefaultDeviceStatus()); - Metadata defaultDeviceStatusCheckMetadata = constructDeviceStatusCheckMetadata(getDefaultDeviceStatusCheck()); - // Add default device status and device status check metadata entries - addMetadataEntry(tenantId, defaultDeviceStatusMetadata, MetadataConstants.ALLOWED_DEVICE_STATUS_META_KEY); - addMetadataEntry(tenantId, defaultDeviceStatusCheckMetadata, MetadataConstants.IS_DEVICE_STATUS_CHECK_META_KEY); + if (!metadataDAO.isExist(tenantId, MetadataConstants.ALLOWED_DEVICE_STATUS_META_KEY)) { + metadataDAO.addMetadata(tenantId, constructDeviceStatusMetadata(getDefaultDeviceStatus())); + } + if (!metadataDAO.isExist(tenantId, MetadataConstants.IS_DEVICE_STATUS_CHECK_META_KEY)) { + metadataDAO.addMetadata(tenantId, constructDeviceStatusCheckMetadata(getDefaultDeviceStatusCheck())); } MetadataManagementDAOFactory.commitTransaction(); } catch (MetadataManagementDAOException e) { @@ -80,8 +80,27 @@ public class DeviceStatusManagementServiceImpl implements DeviceStatusManagement } @Override - public void resetToDefaultDeviceStausFilter() throws MetadataManagementException { - + public void resetToDefaultDeviceStatusFilter(int tenantId) throws MetadataManagementException { + try { + MetadataManagementDAOFactory.beginTransaction(); + Metadata defaultDeviceStatusMetadata = constructDeviceStatusMetadata(getDefaultDeviceStatus()); + Metadata defaultDeviceStatusCheckMetadata = constructDeviceStatusCheckMetadata(getDefaultDeviceStatusCheck()); + // Add default device status and device status check metadata entries + metadataDAO.addMetadata(tenantId, defaultDeviceStatusMetadata); + metadataDAO.addMetadata(tenantId, defaultDeviceStatusCheckMetadata); + MetadataManagementDAOFactory.commitTransaction(); + } catch (MetadataManagementDAOException e) { + MetadataManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while inserting default device status metadata entries."; + log.error(msg, e); + throw new MetadataManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while starting the transaction to reset default device status filters."; + log.error(msg, e); + throw new MetadataManagementException(msg, e); + } finally { + MetadataManagementDAOFactory.closeConnection(); + } } @Override @@ -91,7 +110,6 @@ public class DeviceStatusManagementServiceImpl implements DeviceStatusManagement // Retrieve the current device status metadata Metadata metadata = metadataDAO.getMetadata(tenantId, MetadataConstants.ALLOWED_DEVICE_STATUS_META_KEY); if (metadata != null) { - Gson gson = new Gson(); Type listType = new TypeToken>() { }.getType(); List currentStatusList = gson.fromJson(metadata.getMetaValue(), listType); @@ -105,7 +123,7 @@ public class DeviceStatusManagementServiceImpl implements DeviceStatusManagement } } metadata.setMetaValue(gson.toJson(currentStatusList)); - updateMetadataEntry(tenantId, metadata, MetadataConstants.ALLOWED_DEVICE_STATUS_META_KEY); + metadataDAO.updateMetadata(tenantId, metadata); } MetadataManagementDAOFactory.commitTransaction(); } catch (MetadataManagementDAOException e) { @@ -124,14 +142,12 @@ public class DeviceStatusManagementServiceImpl implements DeviceStatusManagement @Override public boolean updateDefaultDeviceStatusCheck(int tenantId, boolean isChecked) throws MetadataManagementException { - boolean success = false; try { MetadataManagementDAOFactory.beginTransaction(); if (metadataDAO.isExist(tenantId, MetadataConstants.IS_DEVICE_STATUS_CHECK_META_KEY)) { - Metadata isDeviceStatusChecked = constructDeviceStatusCheckMetadata(isChecked); // Add default device status check metadata entries - updateMetadataEntry(tenantId, isDeviceStatusChecked, MetadataConstants.IS_DEVICE_STATUS_CHECK_META_KEY); - success = true; + metadataDAO.updateMetadata(tenantId, constructDeviceStatusCheckMetadata(isChecked)); + return true; } MetadataManagementDAOFactory.commitTransaction(); } catch (MetadataManagementDAOException e) { @@ -146,7 +162,7 @@ public class DeviceStatusManagementServiceImpl implements DeviceStatusManagement } finally { MetadataManagementDAOFactory.closeConnection(); } - return success; + return false; } @Override @@ -154,11 +170,15 @@ public class DeviceStatusManagementServiceImpl implements DeviceStatusManagement try { MetadataManagementDAOFactory.openConnection(); Metadata metadata = metadataDAO.getMetadata(tenantId, MetadataConstants.ALLOWED_DEVICE_STATUS_META_KEY); - Gson gson = new Gson(); - Type listType = new TypeToken>() {}.getType(); - List statusList = gson.fromJson(metadata.getMetaValue(), listType); - - return statusList; + if (metadata == null) { + String msg = + "Couldn't find the meta data value for meta key: " + MetadataConstants.ALLOWED_DEVICE_STATUS_META_KEY; + log.error(msg); + throw new MetadataKeyNotFoundException(msg); + } + Type listType = new TypeToken>() { + }.getType(); + return gson.fromJson(metadata.getMetaValue(), listType); } catch (MetadataManagementDAOException e) { String msg = "Error occurred while retrieving device status meta data for tenant:" + tenantId; log.error(msg, e); @@ -177,8 +197,14 @@ public class DeviceStatusManagementServiceImpl implements DeviceStatusManagement try { MetadataManagementDAOFactory.openConnection(); Metadata metadata = metadataDAO.getMetadata(tenantId, MetadataConstants.ALLOWED_DEVICE_STATUS_META_KEY); - Gson gson = new Gson(); - Type listType = new TypeToken>() {}.getType(); + if (metadata == null) { + String msg = "Couldn't find the meta details of meta Key: " + + MetadataConstants.ALLOWED_DEVICE_STATUS_META_KEY + " and tenant Id: " + tenantId; + log.error(msg); + throw new MetadataKeyNotFoundException(msg); + } + Type listType = new TypeToken>() { + }.getType(); List statusList = gson.fromJson(metadata.getMetaValue(), listType); for (AllowedDeviceStatus status : statusList) { @@ -207,6 +233,12 @@ public class DeviceStatusManagementServiceImpl implements DeviceStatusManagement try { MetadataManagementDAOFactory.openConnection(); Metadata metadata = metadataDAO.getMetadata(tenantId, MetadataConstants.IS_DEVICE_STATUS_CHECK_META_KEY); + if (metadata == null) { + String msg = "Couldn't find the meta data value for meta key: " + + MetadataConstants.IS_DEVICE_STATUS_CHECK_META_KEY + " and tenant Id: " + tenantId; + log.error(msg); + throw new MetadataKeyNotFoundException(msg); + } String metaValue = metadata.getMetaValue(); return Boolean.parseBoolean(metaValue); } catch (MetadataManagementDAOException e) { @@ -227,8 +259,13 @@ public class DeviceStatusManagementServiceImpl implements DeviceStatusManagement try { MetadataManagementDAOFactory.openConnection(); Metadata metadata = metadataDAO.getMetadata(tenantId, MetadataConstants.ALLOWED_DEVICE_STATUS_META_KEY); + if (metadata == null) { + String msg = "Couldn't find the meta data value for meta key: " + + MetadataConstants.ALLOWED_DEVICE_STATUS_META_KEY + " and tenant Id: " + tenantId; + log.error(msg); + throw new MetadataKeyNotFoundException(msg); + } - Gson gson = new Gson(); Type listType = new TypeToken>() { }.getType(); List statusList = gson.fromJson(metadata.getMetaValue(), listType); @@ -254,22 +291,13 @@ public class DeviceStatusManagementServiceImpl implements DeviceStatusManagement } } - private void addMetadataEntry(int tenantId, Metadata metadata, String key) throws MetadataManagementDAOException { - metadataDAO.addMetadata(tenantId, metadata); - if (log.isDebugEnabled()) { - log.debug(key + " metadata entry has been inserted successfully"); - } - } - - private void updateMetadataEntry(int tenantId, Metadata metadata, String key) throws MetadataManagementDAOException { - metadataDAO.updateMetadata(tenantId, metadata); - if (log.isDebugEnabled()) { - log.debug(key + " metadata entry has been updated successfully"); - } - } - + /** + * To construct device status Meta data by using received device status items + * + * @param deviceStatusItems {@link List} + * @return {@link Metadata} + */ private Metadata constructDeviceStatusMetadata(List deviceStatusItems) { - Gson gson = new Gson(); String deviceStatusItemsJsonString = gson.toJson(deviceStatusItems); Metadata metadata = new Metadata(); @@ -279,6 +307,12 @@ public class DeviceStatusManagementServiceImpl implements DeviceStatusManagement return metadata; } + /** + * To construct device status check Meta data to either enable it or disable it. + * + * @param deviceStatusCheck True or False + * @return {@link Metadata} + */ private Metadata constructDeviceStatusCheckMetadata(boolean deviceStatusCheck) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("deviceStatusCheck", String.valueOf(deviceStatusCheck)); @@ -289,6 +323,11 @@ public class DeviceStatusManagementServiceImpl implements DeviceStatusManagement return metadata; } + /** + * Get default list of device status items from the configuration. + * + * @return List of device status items + */ private List getDefaultDeviceStatus() { DeviceStatusConfigurations deviceStatusConfigurations = UIConfigurationManager.getInstance().getUIConfig().getDeviceStatusConfigurations(); List deviceStatusItems = new ArrayList<>(); @@ -305,6 +344,11 @@ public class DeviceStatusManagementServiceImpl implements DeviceStatusManagement return deviceStatusItems; } + /** + * Get Default device status check from the configuration. + * + * @return default status check value, it will be either 'True' or 'False' + */ private boolean getDefaultDeviceStatusCheck() { DeviceStatusConfigurations deviceStatusConfigurations = UIConfigurationManager.getInstance().getUIConfig().getDeviceStatusConfigurations(); boolean deviceStatusCheck = false; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/MetadataManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/MetadataManagementServiceImpl.java index 121caf5ba3..407ecef1bc 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/MetadataManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/MetadataManagementServiceImpl.java @@ -18,10 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.metadata.mgt; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataKeyAlreadyExistsException; @@ -34,6 +30,11 @@ import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.MetadataDAO; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; + import java.sql.SQLException; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/WhiteLabelManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/WhiteLabelManagementServiceImpl.java index ff6bdf1c19..4ade3adc82 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/WhiteLabelManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/WhiteLabelManagementServiceImpl.java @@ -19,26 +19,13 @@ package io.entgra.device.mgt.core.device.mgt.core.metadata.mgt; import com.google.gson.Gson; -import org.apache.commons.io.IOUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Base64File; import io.entgra.device.mgt.core.device.mgt.common.FileResponse; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.NotFoundException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.WhiteLabelImage; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.WhiteLabelImageRequestPayload; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.WhiteLabelManagementService; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.WhiteLabelTheme; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.WhiteLabelThemeCreateRequest; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.*; import io.entgra.device.mgt.core.device.mgt.core.common.util.HttpUtil; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.config.metadata.mgt.MetaDataConfiguration; @@ -50,6 +37,14 @@ import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.MetadataManage import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.util.MetadataConstants; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.util.WhiteLabelStorageUtil; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; +import org.apache.commons.io.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.io.File; import java.io.IOException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/MetadataManagementDAOFactory.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/MetadataManagementDAOFactory.java index 6ff2336340..bb0a5c79f5 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/MetadataManagementDAOFactory.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/MetadataManagementDAOFactory.java @@ -18,8 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; @@ -30,12 +28,14 @@ import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUti import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.impl.GenericMetadataDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.impl.OracleMetadataDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.impl.SQLServerMetadataDAOImpl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.Hashtable; import java.util.List; -import javax.sql.DataSource; /** * DAO factory class to be used in MetadataManagement related functionalities. diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/impl/AbstractMetadataDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/impl/AbstractMetadataDAOImpl.java index 6ea47bdd40..aadb508de5 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/impl/AbstractMetadataDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/impl/AbstractMetadataDAOImpl.java @@ -18,19 +18,15 @@ package io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.MetadataDAO; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.util.MetadataDAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; +import java.sql.*; /** * Implementation of MetadataDAO which includes the methods to do CRUD operations on metadata. diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/impl/GenericMetadataDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/impl/GenericMetadataDAOImpl.java index 775785087f..6fb8cfa1e6 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/impl/GenericMetadataDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/impl/GenericMetadataDAOImpl.java @@ -18,13 +18,13 @@ package io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.util.MetadataDAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/impl/OracleMetadataDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/impl/OracleMetadataDAOImpl.java index 36b4ef593f..4a7dce786d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/impl/OracleMetadataDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/impl/OracleMetadataDAOImpl.java @@ -18,13 +18,13 @@ package io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.util.MetadataDAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/impl/SQLServerMetadataDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/impl/SQLServerMetadataDAOImpl.java index 6ffc3cc1be..70880a1a9d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/impl/SQLServerMetadataDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/impl/SQLServerMetadataDAOImpl.java @@ -18,13 +18,13 @@ package io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.util.MetadataDAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/util/MetadataDAOUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/util/MetadataDAOUtil.java index a03a95f5bc..a0837f406b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/util/MetadataDAOUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/dao/util/MetadataDAOUtil.java @@ -18,9 +18,9 @@ package io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.util; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; import java.sql.ResultSet; import java.sql.SQLException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/util/WhiteLabelStorageUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/util/WhiteLabelStorageUtil.java index d67483be0a..07d34e71e8 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/util/WhiteLabelStorageUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/metadata/mgt/util/WhiteLabelStorageUtil.java @@ -18,10 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.util; -import org.apache.commons.io.IOUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Base64File; import io.entgra.device.mgt.core.device.mgt.common.FileResponse; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; @@ -34,6 +30,9 @@ import io.entgra.device.mgt.core.device.mgt.core.common.util.StorageManagementUt import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.config.metadata.mgt.MetaDataConfiguration; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; +import org.apache.commons.io.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.io.File; import java.io.IOException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java index 4aba354fe4..b63426bdf9 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java @@ -18,15 +18,12 @@ package io.entgra.device.mgt.core.device.mgt.core.notification.mgt; -import io.entgra.device.mgt.core.device.mgt.extensions.logger.spi.EntgraLogger; -import io.entgra.device.mgt.core.notification.logger.DeviceLogContext; -import io.entgra.device.mgt.core.notification.logger.impl.EntgraDeviceLoggerImpl; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.EntityDoesNotExistException; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.EntityDoesNotExistException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.Notification; import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.NotificationManagementException; @@ -36,6 +33,9 @@ import io.entgra.device.mgt.core.device.mgt.core.notification.mgt.dao.Notificati import io.entgra.device.mgt.core.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; +import io.entgra.device.mgt.core.device.mgt.extensions.logger.spi.EntgraLogger; +import io.entgra.device.mgt.core.notification.logger.DeviceLogContext; +import io.entgra.device.mgt.core.notification.logger.impl.EntgraDeviceLoggerImpl; import java.sql.SQLException; import java.util.ArrayList; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/dao/NotificationManagementDAOFactory.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/dao/NotificationManagementDAOFactory.java index 4b213dafab..671f6de0a5 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/dao/NotificationManagementDAOFactory.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/dao/NotificationManagementDAOFactory.java @@ -18,16 +18,19 @@ package io.entgra.device.mgt.core.device.mgt.core.notification.mgt.dao; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.UnsupportedDatabaseEngineException; import io.entgra.device.mgt.core.device.mgt.core.config.datasource.DataSourceConfig; import io.entgra.device.mgt.core.device.mgt.core.config.datasource.JNDILookupDefinition; -import io.entgra.device.mgt.core.device.mgt.core.notification.mgt.dao.impl.*; +import io.entgra.device.mgt.core.device.mgt.core.notification.mgt.dao.impl.GenericNotificationDAOImpl; +import io.entgra.device.mgt.core.device.mgt.core.notification.mgt.dao.impl.OracleNotificationDAOImpl; +import io.entgra.device.mgt.core.device.mgt.core.notification.mgt.dao.impl.PostgreSQLNotificationDAOImpl; +import io.entgra.device.mgt.core.device.mgt.core.notification.mgt.dao.impl.SQLServerNotificationDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.sql.DataSource; import java.sql.Connection; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/dao/impl/AbstractNotificationDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/dao/impl/AbstractNotificationDAOImpl.java index d7bcccf373..de56840f4a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/dao/impl/AbstractNotificationDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/dao/impl/AbstractNotificationDAOImpl.java @@ -24,12 +24,7 @@ import io.entgra.device.mgt.core.device.mgt.core.notification.mgt.dao.Notificati import io.entgra.device.mgt.core.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; +import java.sql.*; import java.util.ArrayList; import java.util.Date; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/dao/impl/OracleNotificationDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/dao/impl/OracleNotificationDAOImpl.java index 3a457a6de2..466828a66a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/dao/impl/OracleNotificationDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/dao/impl/OracleNotificationDAOImpl.java @@ -24,11 +24,7 @@ import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.Notification import io.entgra.device.mgt.core.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; +import java.sql.*; import java.util.ArrayList; import java.util.Date; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/dao/util/NotificationDAOUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/dao/util/NotificationDAOUtil.java index 4f4d61def6..68b095f1de 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/dao/util/NotificationDAOUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/dao/util/NotificationDAOUtil.java @@ -18,12 +18,12 @@ package io.entgra.device.mgt.core.device.mgt.core.notification.mgt.dao.util; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.Notification; import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.NotificationManagementException; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/change/status/task/OperationConfigurationService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/change/status/task/OperationConfigurationService.java new file mode 100644 index 0000000000..522f406a7b --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/change/status/task/OperationConfigurationService.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.core.operation.change.status.task; + +import com.google.gson.Gson; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataKeyAlreadyExistsException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataKeyNotFoundException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; +import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; +import io.entgra.device.mgt.core.device.mgt.core.operation.change.status.task.dto.OperationConfig; +import io.entgra.device.mgt.core.device.mgt.core.operation.change.status.task.exceptions.OperationConfigAlreadyExistsException; +import io.entgra.device.mgt.core.device.mgt.core.operation.change.status.task.exceptions.OperationConfigException; +import io.entgra.device.mgt.core.device.mgt.core.operation.change.status.task.exceptions.OperationConfigNotFoundException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class OperationConfigurationService { + + private static final Log log = LogFactory.getLog(OperationConfigurationService.class); + private static final Gson gson = new Gson(); + private static final String STRING = "STRING"; + private static final String OPERATION_CONFIG = "OPERATION_CONFIG"; + static MetadataManagementService metadataManagementService = DeviceManagementDataHolder.getInstance().getMetadataManagementService(); + + + public static OperationConfig getOperationConfig() throws OperationConfigException { + + Metadata metadata; + try { + metadata = metadataManagementService.retrieveMetadata(OPERATION_CONFIG); + } catch (MetadataManagementException e) { + String msg = "Error occurred while retrieving operation configuration"; + log.error(msg, e); + throw new OperationConfigException(msg, e); + } + if (metadata != null) { + return gson.fromJson(metadata.getMetaValue(), OperationConfig.class); + } else { + return null; + } + } + + public static void addOperationConfiguration(OperationConfig config) throws OperationConfigException, + OperationConfigAlreadyExistsException { + + Metadata metadata = new Metadata(); + metadata.setDataType(STRING); + metadata.setMetaKey(OPERATION_CONFIG); + metadata.setMetaValue(gson.toJson(config)); + + try { + metadataManagementService.createMetadata(metadata); + } catch (MetadataKeyAlreadyExistsException e) { + String msg = "Operation configuration already exists"; + log.error(msg, e); + throw new OperationConfigAlreadyExistsException(msg, e); + } catch (MetadataManagementException e) { + String msg = "Error occurred while adding operation configuration"; + log.error(msg, e); + throw new OperationConfigException(msg, e); + } + } + + public static void updateOperationConfiguration(OperationConfig config) throws OperationConfigException { + + Metadata metadata = new Metadata(); + metadata.setDataType(STRING); + metadata.setMetaKey(OPERATION_CONFIG); + metadata.setMetaValue(gson.toJson(config)); + + try { + metadataManagementService.updateMetadata(metadata); + } catch (MetadataManagementException e) { + String msg = "Error occurred while updating operation configuration"; + log.error(msg, e); + throw new OperationConfigException(msg, e); + } + } + + public static void deleteOperationConfiguration() throws OperationConfigException, OperationConfigNotFoundException { + + try { + metadataManagementService.deleteMetadata(OPERATION_CONFIG); + } catch (MetadataKeyNotFoundException e) { + String msg = "Operation configuration already exists"; + log.error(msg, e); + throw new OperationConfigNotFoundException(msg, e); + } catch (MetadataManagementException e) { + String msg = "Error occurred while deleting operation configuration"; + log.error(msg, e); + throw new OperationConfigException(msg, e); + } + } + +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/change/status/task/dto/OperationConfig.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/change/status/task/dto/OperationConfig.java new file mode 100644 index 0000000000..5e54e5f062 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/change/status/task/dto/OperationConfig.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.core.operation.change.status.task.dto; + +/** + * DTO for Operation configuration. + */ + +public class OperationConfig { + + private String[] deviceTypes; + private String initialOperationStatus; + private String requiredStatusChange; + + public String[] getDeviceTypes() { + return deviceTypes; + } + + public void setDeviceTypes(String[] deviceTypes) { + this.deviceTypes = deviceTypes; + } + + public String getInitialOperationStatus() { + return initialOperationStatus; + } + + public void setInitialOperationStatus(String initialOperationStatus) { + this.initialOperationStatus = initialOperationStatus; + } + + public String getRequiredStatusChange() { + return requiredStatusChange; + } + + public void setRequiredStatusChange(String requiredStatusChange) { + this.requiredStatusChange = requiredStatusChange; + } + +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/change/status/task/exceptions/OperationConfigAlreadyExistsException.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/change/status/task/exceptions/OperationConfigAlreadyExistsException.java new file mode 100644 index 0000000000..7bcc3b5f1b --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/change/status/task/exceptions/OperationConfigAlreadyExistsException.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.core.operation.change.status.task.exceptions; + +/** + * Custom exception class to be used in operation configuration service related functionalities. + */ +public class OperationConfigAlreadyExistsException extends Exception { + + private static final long serialVersionUID = -1814347544027733436L; + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public OperationConfigAlreadyExistsException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public OperationConfigAlreadyExistsException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public OperationConfigAlreadyExistsException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public OperationConfigAlreadyExistsException() { + super(); + } + + public OperationConfigAlreadyExistsException(Throwable cause) { + super(cause); + } + +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/change/status/task/exceptions/OperationConfigException.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/change/status/task/exceptions/OperationConfigException.java new file mode 100644 index 0000000000..863de5d48a --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/change/status/task/exceptions/OperationConfigException.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.core.operation.change.status.task.exceptions; + +/** + * Custom exception class to be used in operation configuration related functionalities. + */ +public class OperationConfigException extends Exception { + + private static final long serialVersionUID = -8933146283800122661L; + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public OperationConfigException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public OperationConfigException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public OperationConfigException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public OperationConfigException() { + super(); + } + + public OperationConfigException(Throwable cause) { + super(cause); + } + +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/change/status/task/exceptions/OperationConfigNotFoundException.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/change/status/task/exceptions/OperationConfigNotFoundException.java new file mode 100644 index 0000000000..c3e5cd0dc3 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/change/status/task/exceptions/OperationConfigNotFoundException.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.core.operation.change.status.task.exceptions; + +/** + * Custom exception class to be used in Operation configuration related functionalities. + */ +public class OperationConfigNotFoundException extends Exception { + + private static final long serialVersionUID = 5260831982626354815L; + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public OperationConfigNotFoundException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public OperationConfigNotFoundException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public OperationConfigNotFoundException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public OperationConfigNotFoundException() { + super(); + } + + public OperationConfigNotFoundException(Throwable cause) { + super(cause); + } + +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/OperationManagerImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/OperationManagerImpl.java index 658dc64545..2776e59aec 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/OperationManagerImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/OperationManagerImpl.java @@ -52,6 +52,8 @@ import io.entgra.device.mgt.core.device.mgt.common.push.notification.Notificatio import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationConfig; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationExecutionFailedException; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationProvider; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.*; +import io.entgra.device.mgt.core.device.mgt.common.push.notification.*; import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService; import io.entgra.device.mgt.core.device.mgt.core.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.core.cache.impl.DeviceCacheManagerImpl; @@ -73,6 +75,12 @@ import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProvide import io.entgra.device.mgt.core.device.mgt.core.task.DeviceTaskManager; import io.entgra.device.mgt.core.device.mgt.core.task.impl.DeviceTaskManagerImpl; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; +import io.entgra.device.mgt.core.device.mgt.extensions.logger.spi.EntgraLogger; +import io.entgra.device.mgt.core.notification.logger.DeviceConnectivityLogContext; +import io.entgra.device.mgt.core.notification.logger.impl.EntgraDeviceConnectivityLoggerImpl; +import org.apache.commons.lang.StringUtils; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.sql.SQLException; import java.sql.Timestamp; @@ -745,7 +753,14 @@ public class OperationManagerImpl implements OperationManager { DeviceCacheManagerImpl.getInstance().removeDeviceFromCache(deviceId, tenantId); break; } - log.info("Device Connected", deviceConnectivityLogContextBuilder.setDeviceId(deviceId.getId()).setDeviceType(deviceId.getType()).setActionTag("PENDING_OPERATION").setTenantDomain(tenantDomain).setTenantId(String.valueOf(tenantId)).setUserName(userName).build()); + log.info("Device Connected", deviceConnectivityLogContextBuilder + .setDeviceId(deviceId.getId()) + .setDeviceType(deviceId.getType()) + .setActionTag("PENDING_OPERATION") + .setTenantDomain(tenantDomain) + .setTenantId(String.valueOf(tenantId)) + .setUserName(userName) + .build()); return getOperations(deviceId, Operation.Status.PENDING, enrolmentId); } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/OperationManagerRepository.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/OperationManagerRepository.java index f670d149ed..6f1464eb14 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/OperationManagerRepository.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/OperationManagerRepository.java @@ -17,8 +17,8 @@ */ package io.entgra.device.mgt.core.device.mgt.core.operation.mgt; -import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceTypeServiceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManager; +import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceTypeServiceIdentifier; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/OperationDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/OperationDAO.java index c874283a76..60a64a0521 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/OperationDAO.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/OperationDAO.java @@ -61,6 +61,9 @@ public interface OperationDAO { boolean updateOperationStatus(int enrolmentId, int operationId,Operation.Status status) throws OperationManagementDAOException; + int updateOperationByDeviceTypeAndInitialStatus(String deiceType, String initialStatus, String requiredStatus) + throws OperationManagementDAOException; + void updateEnrollmentOperationsStatus(int enrolmentId, String operationCode, Operation.Status existingStatus, Operation.Status newStatus) throws OperationManagementDAOException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/OperationManagementDAOFactory.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/OperationManagementDAOFactory.java index 33a13cb5b9..a0ebadb328 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/OperationManagementDAOFactory.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/OperationManagementDAOFactory.java @@ -18,8 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; @@ -32,6 +30,8 @@ import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl.operatio import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl.operation.OracleOperationDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl.operation.PostgreSQLOperationDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl.operation.SQLServerOperationDAOImpl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.sql.DataSource; import java.sql.Connection; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/CommandOperationDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/CommandOperationDAOImpl.java index cfef55c428..f47f796674 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/CommandOperationDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/CommandOperationDAOImpl.java @@ -32,9 +32,7 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.sql.Timestamp; import java.util.ArrayList; -import java.util.Date; import java.util.List; public class CommandOperationDAOImpl extends GenericOperationDAOImpl { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationDAOImpl.java index 3d7ceeaa18..d493a9ef9d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationDAOImpl.java @@ -28,12 +28,10 @@ import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationMana import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; -import java.io.*; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.sql.*; import java.util.ArrayList; import java.util.Date; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationMSSQLDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationMSSQLDAOImpl.java index c09a2d5685..a1abfa987e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationMSSQLDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationMSSQLDAOImpl.java @@ -19,14 +19,14 @@ package io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.ConfigOperation; import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationPostgresDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationPostgresDAOImpl.java index f51ad488d8..b50536571b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationPostgresDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationPostgresDAOImpl.java @@ -19,25 +19,16 @@ package io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.ConfigOperation; import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; +import java.io.*; +import java.sql.*; import java.util.ArrayList; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java index 50ec3f1071..3df2f41aac 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java @@ -128,6 +128,38 @@ public class GenericOperationDAOImpl implements OperationDAO { return isUpdated; } + public int updateOperationByDeviceTypeAndInitialStatus(String deiceType, String initialStatus, String requiredStatus) + throws OperationManagementDAOException { + int numOfRecordsUpdated; + long time = DeviceManagementDAOUtil.getCurrentUTCTime(); + + String sql = "UPDATE DM_ENROLMENT_OP_MAPPING SET STATUS=?, UPDATED_TIMESTAMP=? WHERE DEVICE_TYPE=?"; + + if (initialStatus == null) { + sql += " AND STATUS IS NULL"; + } else { + sql += " AND STATUS=?"; + } + + try ( + Connection connection = OperationManagementDAOFactory.getConnection(); + PreparedStatement stmt = connection.prepareStatement(sql) + ) { + stmt.setString(1, requiredStatus); + stmt.setLong(2, time); + stmt.setString(3, deiceType); + + if (initialStatus != null) { + stmt.setString(4, initialStatus); + } + numOfRecordsUpdated = stmt.executeUpdate(); + } catch (SQLException e) { + throw new OperationManagementDAOException("Error occurred while update device mapping operation status " + + e.getMessage(), e); + } + return numOfRecordsUpdated; + } + @Override public void updateEnrollmentOperationsStatus(int enrolmentId, String operationCode, Operation.Status existingStatus, Operation.Status newStatus) throws OperationManagementDAOException { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java index 75cbe51b0e..1cb14e18f2 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java @@ -17,10 +17,7 @@ */ package io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationEnrolmentMapping; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationMapping; @@ -28,15 +25,14 @@ import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationMana import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationMappingDAO; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; public class OperationMappingDAOImpl implements OperationMappingDAO { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/operation/MySQLOperationDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/operation/MySQLOperationDAOImpl.java index 37545d4408..7279a65d7c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/operation/MySQLOperationDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/operation/MySQLOperationDAOImpl.java @@ -18,9 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl.operation; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.ActivityHolder; @@ -31,6 +28,9 @@ import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationMana import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl.GenericOperationDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.util.OperationDAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java index 9a53353a2e..756e76c444 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java @@ -18,9 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl.operation; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; @@ -32,6 +29,9 @@ import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationMana import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl.GenericOperationDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.util.OperationDAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.sql.Connection; import java.sql.PreparedStatement; @@ -39,11 +39,7 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.ArrayList; -import java.util.LinkedList; +import java.util.*; /** * This class holds the implementation of OperationDAO which can be used to support Oracle db syntax. diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java index ede11203d3..59819bb98c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java @@ -27,16 +27,12 @@ import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationMana import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl.GenericOperationDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.util.OperationDAOUtil; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; +import java.sql.*; import java.text.DateFormat; import java.text.SimpleDateFormat; +import java.util.ArrayList; import java.util.Date; import java.util.List; -import java.util.ArrayList; /** * This class holds the implementation of OperationDAO which can be used to support PostgreSQL db syntax. diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java index c6d29acd78..ee4274a006 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java @@ -18,15 +18,10 @@ package io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl.operation; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.ActivityHolder; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.ActivityStatus; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationResponse; import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationMapping; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; @@ -34,19 +29,14 @@ import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationMana import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl.GenericOperationDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.util.OperationDAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; +import java.sql.*; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; +import java.util.*; /** * This class holds the implementation of OperationDAO which can be used to support SQLServer db syntax. diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java index 3aef7ea447..4e20be0ae2 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java @@ -17,8 +17,6 @@ */ package io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.util; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.DeviceActivity; @@ -27,12 +25,11 @@ import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.ActivityMapper; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.ActivityStatus; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationResponse; import io.entgra.device.mgt.core.device.mgt.core.DeviceManagementConstants; -import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.CommandOperation; -import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.ConfigOperation; import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation; -import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.PolicyOperation; -import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.ProfileOperation; +import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.*; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.json.JSONObject; import java.io.ByteArrayInputStream; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTaskManagerServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTaskManagerServiceImpl.java index e18507df3e..6875b62125 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTaskManagerServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTaskManagerServiceImpl.java @@ -18,13 +18,13 @@ package io.entgra.device.mgt.core.device.mgt.core.operation.timeout.task.impl; import com.google.gson.Gson; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.core.config.operation.timeout.OperationTimeout; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import io.entgra.device.mgt.core.device.mgt.core.operation.timeout.task.OperationTimeoutTaskException; import io.entgra.device.mgt.core.device.mgt.core.operation.timeout.task.OperationTimeoutTaskManagerService; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.ntask.common.TaskException; import org.wso2.carbon.ntask.core.TaskInfo; import org.wso2.carbon.ntask.core.TaskManager; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/dao/OTPManagementDAOFactory.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/dao/OTPManagementDAOFactory.java index 5dcc519711..15842ae225 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/dao/OTPManagementDAOFactory.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/dao/OTPManagementDAOFactory.java @@ -17,8 +17,6 @@ */ package io.entgra.device.mgt.core.device.mgt.core.otp.mgt.dao; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.exceptions.UnsupportedDatabaseEngineException; import io.entgra.device.mgt.core.device.mgt.core.otp.mgt.dao.impl.GenericOTPManagementDAOImpl; @@ -26,6 +24,8 @@ import io.entgra.device.mgt.core.device.mgt.core.otp.mgt.dao.impl.OracleOTPManag import io.entgra.device.mgt.core.device.mgt.core.otp.mgt.dao.impl.PostgreSQLOTPManagementDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.otp.mgt.dao.impl.SQLServerOTPManagementDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.otp.mgt.util.ConnectionManagerUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.sql.DataSource; import java.sql.Connection; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/dao/impl/GenericOTPManagementDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/dao/impl/GenericOTPManagementDAOImpl.java index e5755cd999..52151cdfd9 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/dao/impl/GenericOTPManagementDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/dao/impl/GenericOTPManagementDAOImpl.java @@ -19,19 +19,17 @@ package io.entgra.device.mgt.core.device.mgt.core.otp.mgt.dao.impl; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DBConnectionException; import io.entgra.device.mgt.core.device.mgt.common.otp.mgt.dto.OneTimePinDTO; import io.entgra.device.mgt.core.device.mgt.core.otp.mgt.dao.AbstractDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.otp.mgt.dao.OTPManagementDAO; -import io.entgra.device.mgt.core.device.mgt.core.otp.mgt.exception.OTPManagementDAOException; +import io.entgra.device.mgt.core.device.mgt.core.otp.mgt.exception.OTPManagementDAOException;import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.sql.Statement; import java.sql.Timestamp; import java.util.Calendar; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java index 55e4fe46d8..a20152ee11 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java @@ -37,6 +37,7 @@ import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.user.api.Tenant; import org.wso2.carbon.user.api.UserStoreException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/util/ConnectionManagerUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/util/ConnectionManagerUtil.java index 852f93eff9..ea5034b1d0 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/util/ConnectionManagerUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/util/ConnectionManagerUtil.java @@ -17,11 +17,11 @@ */ package io.entgra.device.mgt.core.device.mgt.core.otp.mgt.util; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DBConnectionException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.naming.InitialContext; import javax.sql.DataSource; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/permission/mgt/PermissionNode.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/permission/mgt/PermissionNode.java index 984fbd142c..872bbaa763 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/permission/mgt/PermissionNode.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/permission/mgt/PermissionNode.java @@ -20,11 +20,7 @@ package io.entgra.device.mgt.core.device.mgt.core.permission.mgt; import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.Permission; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; /** * This class represents the node of a permission tree. diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/permission/mgt/PermissionTree.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/permission/mgt/PermissionTree.java index 725ab61e5e..3897f83532 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/permission/mgt/PermissionTree.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/permission/mgt/PermissionTree.java @@ -18,9 +18,9 @@ package io.entgra.device.mgt.core.device.mgt.core.permission.mgt; +import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.Permission; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.Permission; import java.util.StringTokenizer; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/permission/mgt/PermissionUtils.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/permission/mgt/PermissionUtils.java index 11eebb1c33..ba0c1c5e45 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/permission/mgt/PermissionUtils.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/permission/mgt/PermissionUtils.java @@ -18,11 +18,11 @@ package io.entgra.device.mgt.core.device.mgt.core.permission.mgt; -import org.w3c.dom.Document; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.Permission; import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; +import org.w3c.dom.Document; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.registry.api.RegistryException; import org.wso2.carbon.registry.api.Resource; import org.wso2.carbon.registry.core.Registry; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/privacy/dao/impl/PrivacyComplianceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/privacy/dao/impl/PrivacyComplianceDAOImpl.java index 7f88c7b76a..4e52f6233b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/privacy/dao/impl/PrivacyComplianceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/privacy/dao/impl/PrivacyComplianceDAOImpl.java @@ -19,13 +19,13 @@ package io.entgra.device.mgt.core.device.mgt.core.privacy.dao.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.privacy.dao.PrivacyComplianceDAO; import io.entgra.device.mgt.core.device.mgt.core.privacy.dao.PrivacyComplianceDAOException; import io.entgra.device.mgt.core.device.mgt.core.privacy.impl.DeviceEnrollmentMapping; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/privacy/impl/PrivacyComplianceProviderImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/privacy/impl/PrivacyComplianceProviderImpl.java index 59d53811a3..b85c82f279 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/privacy/impl/PrivacyComplianceProviderImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/privacy/impl/PrivacyComplianceProviderImpl.java @@ -19,9 +19,6 @@ package io.entgra.device.mgt.core.device.mgt.core.privacy.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; @@ -32,6 +29,9 @@ import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHo import io.entgra.device.mgt.core.device.mgt.core.privacy.PrivacyComplianceProvider; import io.entgra.device.mgt.core.device.mgt.core.privacy.dao.PrivacyComplianceDAO; import io.entgra.device.mgt.core.device.mgt.core.privacy.dao.PrivacyComplianceDAOException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.util.ArrayList; import java.util.HashMap; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/push/notification/mgt/PushNotificationConfigRepository.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/push/notification/mgt/PushNotificationConfigRepository.java index f8ffe50205..9bf8b054e4 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/push/notification/mgt/PushNotificationConfigRepository.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/push/notification/mgt/PushNotificationConfigRepository.java @@ -17,8 +17,8 @@ */ package io.entgra.device.mgt.core.device.mgt.core.push.notification.mgt; -import org.wso2.carbon.context.CarbonContext; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationConfig; +import org.wso2.carbon.context.CarbonContext; import java.util.HashMap; import java.util.Map; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/push/notification/mgt/PushNotificationProviderRepository.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/push/notification/mgt/PushNotificationProviderRepository.java index 36f7b867b1..e396202982 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/push/notification/mgt/PushNotificationProviderRepository.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/push/notification/mgt/PushNotificationProviderRepository.java @@ -17,9 +17,9 @@ */ package io.entgra.device.mgt.core.device.mgt.core.push.notification.mgt; +import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationProvider; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationProvider; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/report/mgt/ReportManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/report/mgt/ReportManagementServiceImpl.java index fdd2cf31b9..a567c7f9f1 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/report/mgt/ReportManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/report/mgt/ReportManagementServiceImpl.java @@ -18,34 +18,29 @@ package io.entgra.device.mgt.core.device.mgt.core.report.mgt; import com.google.gson.JsonObject; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.Count; import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.BadRequestException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.BadRequestException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceTypeNotFoundException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.ReportManagementException; import io.entgra.device.mgt.core.device.mgt.common.report.mgt.ReportManagementService; -import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceDAO; -import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; -import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; -import io.entgra.device.mgt.core.device.mgt.core.dao.GroupDAO; -import io.entgra.device.mgt.core.device.mgt.core.dao.GroupManagementDAOException; -import io.entgra.device.mgt.core.device.mgt.core.dao.GroupManagementDAOFactory; +import io.entgra.device.mgt.core.device.mgt.core.dao.*; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; +import java.util.Calendar; import java.util.Date; import java.util.List; -import java.util.Calendar; import java.util.concurrent.TimeUnit; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/report/mgt/config/ReportMgtConfigurationManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/report/mgt/config/ReportMgtConfigurationManager.java index 48ae7a5e28..bf7632a964 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/report/mgt/config/ReportMgtConfigurationManager.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/report/mgt/config/ReportMgtConfigurationManager.java @@ -17,11 +17,11 @@ */ package io.entgra.device.mgt.core.device.mgt.core.report.mgt.config; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidConfigurationException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.ReportManagementException; import io.entgra.device.mgt.core.device.mgt.core.report.mgt.Constants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/report/mgt/dao/common/ReportMgtConnectionManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/report/mgt/dao/common/ReportMgtConnectionManager.java index e2d1df5b66..f6330b0683 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/report/mgt/dao/common/ReportMgtConnectionManager.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/report/mgt/dao/common/ReportMgtConnectionManager.java @@ -17,11 +17,11 @@ */ package io.entgra.device.mgt.core.device.mgt.core.report.mgt.dao.common; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DBConnectionException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; import io.entgra.device.mgt.core.device.mgt.core.report.mgt.config.ReportMgtConfigurationManager; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.naming.InitialContext; import javax.sql.DataSource; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/search/mgt/impl/ProcessorImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/search/mgt/impl/ProcessorImpl.java index 3f71e45dec..43735628df 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/search/mgt/impl/ProcessorImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/search/mgt/impl/ProcessorImpl.java @@ -19,9 +19,6 @@ package io.entgra.device.mgt.core.device.mgt.core.search.mgt.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; @@ -33,21 +30,13 @@ import io.entgra.device.mgt.core.device.mgt.core.dao.ApplicationDAO; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; -import io.entgra.device.mgt.core.device.mgt.core.search.mgt.Constants; -import io.entgra.device.mgt.core.device.mgt.core.search.mgt.InvalidOperatorException; -import io.entgra.device.mgt.core.device.mgt.core.search.mgt.Processor; -import io.entgra.device.mgt.core.device.mgt.core.search.mgt.QueryBuilder; -import io.entgra.device.mgt.core.device.mgt.core.search.mgt.QueryHolder; -import io.entgra.device.mgt.core.device.mgt.core.search.mgt.ResultSetAggregator; -import io.entgra.device.mgt.core.device.mgt.core.search.mgt.SearchMgtException; -import io.entgra.device.mgt.core.device.mgt.core.search.mgt.ValueType; +import io.entgra.device.mgt.core.device.mgt.core.search.mgt.*; import io.entgra.device.mgt.core.device.mgt.core.search.mgt.dao.SearchDAOException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; -import java.sql.Array; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java index fd6f75e801..a900682ffe 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java @@ -19,15 +19,11 @@ package io.entgra.device.mgt.core.device.mgt.core.search.mgt.impl; +import io.entgra.device.mgt.core.device.mgt.common.search.Condition; +import io.entgra.device.mgt.core.device.mgt.core.search.mgt.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.search.Condition; -import io.entgra.device.mgt.core.device.mgt.core.search.mgt.Constants; -import io.entgra.device.mgt.core.device.mgt.core.search.mgt.InvalidOperatorException; -import io.entgra.device.mgt.core.device.mgt.core.search.mgt.QueryBuilder; -import io.entgra.device.mgt.core.device.mgt.core.search.mgt.QueryHolder; -import io.entgra.device.mgt.core.device.mgt.core.search.mgt.ValueType; import java.util.ArrayList; import java.util.HashMap; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/search/mgt/impl/ResultSetAggregatorImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/search/mgt/impl/ResultSetAggregatorImpl.java index c80ee563aa..b887fdab37 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/search/mgt/impl/ResultSetAggregatorImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/search/mgt/impl/ResultSetAggregatorImpl.java @@ -19,14 +19,14 @@ package io.entgra.device.mgt.core.device.mgt.core.search.mgt.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionUtils; import io.entgra.device.mgt.core.device.mgt.core.search.mgt.Constants; import io.entgra.device.mgt.core.device.mgt.core.search.mgt.ResultSetAggregator; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderService.java index 682e4e5aac..ee8c5b5871 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderService.java @@ -26,19 +26,11 @@ import io.entgra.device.mgt.core.device.mgt.core.dto.OwnerWithDeviceDTO; import org.apache.commons.collections.map.SingletonMap; import io.entgra.device.mgt.core.device.mgt.common.*; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ApplicationManagementException; -import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.AmbiguousConfigurationException; -import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationManagementException; -import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.DeviceConfiguration; -import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; +import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.*; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceData; -import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationEntry; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceLocationHistorySnapshot; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceNotFoundException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceTypeNotFoundException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidDeviceException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.UnauthorizedDeviceAccessException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.UserNotFoundException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.*; +import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoCluster; import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoQuery; import io.entgra.device.mgt.core.device.mgt.common.invitation.mgt.DeviceEnrollmentInvitationDetails; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.License; @@ -54,7 +46,6 @@ import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceStatus; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceTypeVersion; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoCluster; import java.sql.SQLException; import java.sql.Timestamp; @@ -1075,7 +1066,14 @@ public interface DeviceManagementProviderService { List getInstalledApplicationsOnDevice(Device device) throws DeviceManagementException; List getEnrolledDevicesSince(Date since) throws DeviceManagementException; List getEnrolledDevicesPriorTo(Date before) throws DeviceManagementException; - void deleteDeviceDataByTenantDomain(String tenantDomain) throws DeviceManagementException; + + /** + * Delete all the device related data for a given Tenant by Tenant Id + * + * @param tenantId Id of the Tenant + * @throws DeviceManagementException if error occurs when deleting device data by using tenant Id + */ + void deleteDeviceDataByTenantId(int tenantId) throws DeviceManagementException; /** * Get owner details and device IDs for a given owner and tenant. diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 737a14177b..9949cc24b1 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -22,7 +22,15 @@ import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import io.entgra.device.mgt.core.device.mgt.common.exceptions.ConflictException; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.DeviceStatusManagementService; +import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceDAO; +import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceTypeDAO; +import io.entgra.device.mgt.core.device.mgt.core.dao.EnrollmentDAO; +import io.entgra.device.mgt.core.device.mgt.core.dao.ApplicationDAO; +import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceStatusDAO; +import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; +import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dao.TenantDAO; +import io.entgra.device.mgt.core.device.mgt.core.dao.TagDAO; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceDetailsDTO; import io.entgra.device.mgt.core.device.mgt.core.dto.OwnerWithDeviceDTO; import io.entgra.device.mgt.core.device.mgt.core.dto.OperationDTO; @@ -119,13 +127,6 @@ import io.entgra.device.mgt.core.device.mgt.core.cache.impl.DeviceCacheManagerIm import io.entgra.device.mgt.core.device.mgt.core.common.Constants; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; -import io.entgra.device.mgt.core.device.mgt.core.dao.ApplicationDAO; -import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceDAO; -import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; -import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; -import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceStatusDAO; -import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceTypeDAO; -import io.entgra.device.mgt.core.device.mgt.core.dao.EnrollmentDAO; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationDAO; import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil; import io.entgra.device.mgt.core.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; @@ -165,7 +166,18 @@ import java.sql.SQLException; import java.sql.Timestamp; import java.time.LocalDateTime; import java.time.LocalTime; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; import java.util.stream.Collectors; public class DeviceManagementProviderServiceImpl implements DeviceManagementProviderService, @@ -185,6 +197,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv private MetadataDAO metadataDAO; private final DeviceStatusDAO deviceStatusDAO; private final TenantDAO tenantDao; + private final TagDAO tagDAO; int count = 0; public DeviceManagementProviderServiceImpl() { @@ -197,6 +210,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv this.metadataDAO = MetadataManagementDAOFactory.getMetadataDAO(); this.deviceStatusDAO = DeviceManagementDAOFactory.getDeviceStatusDAO(); this.tenantDao = DeviceManagementDAOFactory.getTenantDAO(); + this.tagDAO = DeviceManagementDAOFactory.getTagDAO(); /* Registering a listener to retrieve events when some device management service plugin is installed after * the component is done getting initialized */ @@ -354,7 +368,15 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv device.getType() + " upon the user '" + device.getEnrolmentInfo().getOwner() + "'"); } - log.info("Device enrolled successfully", deviceEnrolmentLogContextBuilder.setDeviceId(String.valueOf(existingDevice.getId())).setDeviceType(String.valueOf(existingDevice.getType())).setOwner(newEnrolmentInfo.getOwner()).setOwnership(String.valueOf(newEnrolmentInfo.getOwnership())).setTenantID(String.valueOf(tenantId)).setTenantDomain(tenantDomain).setUserName(userName).build()); + log.info("Device enrolled successfully", deviceEnrolmentLogContextBuilder + .setDeviceId(String.valueOf(existingDevice.getId())) + .setDeviceType(String.valueOf(existingDevice.getType())) + .setOwner(newEnrolmentInfo.getOwner()) + .setOwnership(String.valueOf(newEnrolmentInfo.getOwnership())) + .setTenantID(String.valueOf(tenantId)) + .setTenantDomain(tenantDomain) + .setUserName(userName) + .build()); status = true; } else { log.warn("Unable to update device enrollment for device : " + device.getDeviceIdentifier() + @@ -5249,20 +5271,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public void deleteDeviceDataByTenantDomain(String tenantDomain) throws DeviceManagementException { - int tenantId; - try{ - TenantMgtAdminService tenantMgtAdminService = new TenantMgtAdminService(); - TenantInfoBean tenantInfoBean = tenantMgtAdminService.getTenant(tenantDomain); - tenantId = tenantInfoBean.getTenantId(); - - } catch (Exception e) { - String msg = "Error getting tenant ID from domain: " - + tenantDomain; - log.error(msg); - throw new DeviceManagementException(msg, e); - } - + public void deleteDeviceDataByTenantId(int tenantId) throws DeviceManagementException { try { DeviceManagementDAOFactory.beginTransaction(); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java index 36b79f150f..1549b3c7b7 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -18,6 +18,19 @@ package io.entgra.device.mgt.core.device.mgt.core.service; +import io.entgra.device.mgt.core.device.mgt.common.Device; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; +import io.entgra.device.mgt.core.device.mgt.common.GroupPaginationRequest; +import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceNotFoundException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; +import io.entgra.device.mgt.core.device.mgt.core.event.config.GroupAssignmentEventOperationExecutor; +import io.entgra.device.mgt.core.device.mgt.core.geo.task.GeoFenceEventOperationManager; +import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; +import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationMgtConstants; +import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroupConstants; @@ -40,26 +53,20 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceNotFoundException; -import io.entgra.device.mgt.core.device.mgt.common.GroupPaginationRequest; -import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; -import io.entgra.device.mgt.core.device.mgt.core.event.config.GroupAssignmentEventOperationExecutor; -import io.entgra.device.mgt.core.device.mgt.core.geo.task.GeoFenceEventOperationManager; -import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; -import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationMgtConstants; -import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.user.api.AuthorizationManager; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import java.sql.SQLException; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; import java.util.concurrent.ExecutorService; import java.util.stream.Collectors; @@ -308,7 +315,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid newParentPath = DeviceGroupConstants.HierarchicalGroup.SEPERATOR; } childrenGroup.setParentPath(newParentPath); - if (!newParentPath.equals(DeviceGroupConstants.HierarchicalGroup.SEPERATOR)) { + if (!DeviceGroupConstants.HierarchicalGroup.SEPERATOR.equals(newParentPath)) { String[] groupIds = newParentPath.split(DeviceGroupConstants.HierarchicalGroup.SEPERATOR); int latestGroupId = Integer.parseInt(groupIds[groupIds.length - 1]); childrenGroup.setParentGroupId(latestGroupId); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/TagManagementProviderService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/TagManagementProviderService.java new file mode 100644 index 0000000000..2b31ca8a31 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/TagManagementProviderService.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.core.service; + +import io.entgra.device.mgt.core.device.mgt.common.exceptions.BadRequestException; +import io.entgra.device.mgt.core.device.mgt.common.tag.mgt.*; + +import java.util.List; + +/** + * Defines the contract of TagManagementService. + */ +public interface TagManagementProviderService { + + /** + * Method to add a tag to the database. + * + * @param tag - Tag to be added to the database. + * @throws TagManagementException if something goes wrong while adding the Tag. + */ + void addTags(List tag) throws TagManagementException, BadRequestException; + + /** + * Method to fetch all tags. + * + * @return List of all Tags. + * @throws TagManagementException if something goes wrong while fetching the Tags. + */ + List getAllTags() throws TagManagementException; + + /** + * Method to update a tag in the database. + * + * @param tag - Tag to be updated in the database. + * @throws TagManagementException if something goes wrong while updating the Tag. + */ + void updateTag(Tag tag) throws TagManagementException, TagNotFoundException, BadRequestException; + + /** + * Method to delete a tag from the database. + * + * @param tagId - ID of the tag to be deleted. + * @throws TagManagementException if something goes wrong while deleting the Tag. + */ + void deleteTag(int tagId) throws TagManagementException, TagNotFoundException; + + /** + * Method to retrieve a tag by its ID. + * + * @param tagId - ID of the tag to be retrieved. + * @return Tag object retrieved from the database. + * @throws TagManagementException if something goes wrong while retrieving the Tag. + */ + Tag getTagById(int tagId) throws TagManagementException, TagNotFoundException; + + /** + * Method to retrieve a tag by its name. + * + * @param tagName - Name of the tag to be retrieved. + * @return Tag object retrieved from the database. + * @throws TagManagementException if something goes wrong while retrieving the Tag. + * @throws TagNotFoundException if the Tag with the given name is not found. + */ + Tag getTagByName(String tagName) throws TagManagementException, TagNotFoundException, BadRequestException; + + /** + * Method to add a device-tag mapping. + * + * @param deviceIdentifiers - List of device ids to map. + * @param deviceType - Device Type of that specific devices. + * @param tags - List of tags you want to attach. + * @throws TagManagementException if something goes wrong while adding the device-tag mapping. + */ + void addDeviceTagMapping(List deviceIdentifiers, String deviceType, List tags) + throws TagManagementException, BadRequestException; + + /** + * Method to delete a device-tag mapping. + * + * @param deviceIdentifiers - List of device ids to map. + * @param deviceType - Device Type of that specific devices. + * @param tags - List of tags you want to attach. + * @throws TagManagementException if something goes wrong while deleting the device-tag mapping. + */ + void deleteDeviceTagMapping(List deviceIdentifiers, String deviceType, List tags) + throws TagManagementException, BadRequestException; +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/TagManagementProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/TagManagementProviderServiceImpl.java new file mode 100644 index 0000000000..822c3b6497 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/TagManagementProviderServiceImpl.java @@ -0,0 +1,284 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.core.service; + +import io.entgra.device.mgt.core.device.mgt.common.exceptions.BadRequestException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; +import io.entgra.device.mgt.core.device.mgt.common.tag.mgt.*; +import io.entgra.device.mgt.core.device.mgt.core.dao.*; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +public class TagManagementProviderServiceImpl implements TagManagementProviderService { + private static final Log log = LogFactory.getLog(TagManagementProviderServiceImpl.class); + + private final TagDAO tagDAO; + + public TagManagementProviderServiceImpl() { + this.tagDAO = DeviceManagementDAOFactory.getTagDAO(); + } + + @Override + public void addTags(List tags) throws TagManagementException, BadRequestException { + if (tags == null || tags.isEmpty()) { + String msg = "Received incomplete data for tags"; + log.error(msg); + throw new BadRequestException(msg); + } + try { + DeviceManagementDAOFactory.beginTransaction(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + for (Tag tag : tags) { + if (tag.getName() == null) { + String msg = "Tag name cannot be null"; + log.error(msg); + throw new BadRequestException(msg); + } + } + if (log.isDebugEnabled()) { + log.debug("Starting creating Tags."); + } + tagDAO.addTags(tags, tenantId); + DeviceManagementDAOFactory.commitTransaction(); + } catch (TransactionManagementException e) { + String msg = "Error occurred while initiating transaction."; + log.error(msg, e); + throw new TagManagementException(msg, e); + } catch (TagManagementDAOException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while adding tags to database."; + log.error(msg, e); + throw new TagManagementException(msg, e); + } catch (Exception e) { + String msg = "Error occurred in creating tags."; + log.error(msg, e); + throw new TagManagementException(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Override + public List getAllTags() throws TagManagementException { + try { + DeviceManagementDAOFactory.beginTransaction(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + List tags = tagDAO.getTags(tenantId); + DeviceManagementDAOFactory.commitTransaction(); + return tags; + } catch (TransactionManagementException e) { + String msg = "Error occurred while initiating transaction."; + log.error(msg, e); + throw new TagManagementException(msg, e); + } catch (TagManagementDAOException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while retrieving tags."; + log.error(msg, e); + throw new TagManagementException(msg, e); + } catch (Exception e) { + String msg = "Error occurred in retrieving tags."; + log.error(msg, e); + throw new TagManagementException(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Override + public Tag getTagById(int tagId) throws TagManagementException, TagNotFoundException { + try { + DeviceManagementDAOFactory.beginTransaction(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + Tag tag = tagDAO.getTagById(tagId, tenantId); + DeviceManagementDAOFactory.commitTransaction(); + if (tag == null) { + String msg = "Tag with ID " + tagId + " not found."; + throw new TagNotFoundException(msg); + } + return tag; + } catch (TransactionManagementException | TagManagementDAOException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while retrieving the tag with ID: " + tagId; + log.error(msg, e); + throw new TagManagementException(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Override + public Tag getTagByName(String tagName) throws TagManagementException, TagNotFoundException, BadRequestException { + if (tagName == null || tagName.trim().isEmpty()) { + String msg = "Tag name cannot be null or empty."; + log.error(msg); + throw new BadRequestException(msg); + } + + try { + DeviceManagementDAOFactory.beginTransaction(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + Tag tag = tagDAO.getTagByName(tagName, tenantId); + DeviceManagementDAOFactory.commitTransaction(); + if (tag == null) { + String msg = "Tag with name " + tagName + " not found."; + throw new TagNotFoundException(msg); + } + return tag; + } catch (TransactionManagementException | TagManagementDAOException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while retrieving the tag with name: " + tagName; + log.error(msg, e); + throw new TagManagementException(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + + @Override + public void updateTag(Tag tag) throws TagManagementException, TagNotFoundException, BadRequestException { + if (tag == null || tag.getName() == null) { + String msg = "Received incomplete data for tag update"; + log.error(msg); + throw new BadRequestException(msg); + } + try { + DeviceManagementDAOFactory.beginTransaction(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + Tag existingTag = tagDAO.getTagById(tag.getId(), tenantId); + if (existingTag == null) { + String msg = "Tag with ID: " + tag.getId() + " does not exist."; + log.error(msg); + throw new TagNotFoundException(msg); + } + Tag tagWithName = tagDAO.getTagByName(tag.getName(), tenantId); + if (tagWithName != null && tagWithName.getId() != tag.getId()) { + String msg = "Tag with name: " + tag.getName() + " already exists."; + log.error(msg); + throw new BadRequestException(msg); + } + tagDAO.updateTag(tag, tenantId); + DeviceManagementDAOFactory.commitTransaction(); + } catch (TagManagementDAOException | TransactionManagementException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while updating the tag with ID: " + tag.getId(); + log.error(msg, e); + throw new TagManagementException(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + + @Override + public void deleteTag(int tagId) throws TagManagementException, TagNotFoundException { + try { + DeviceManagementDAOFactory.beginTransaction(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + Tag existingTag = tagDAO.getTagById(tagId, tenantId); + if (existingTag == null) { + String msg = "Tag with ID: " + tagId + " does not exist."; + log.error(msg); + throw new TagNotFoundException(msg); + } + tagDAO.deleteTag(tagId, tenantId); + DeviceManagementDAOFactory.commitTransaction(); + } catch (TagManagementDAOException | TransactionManagementException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while deleting the tag with ID: " + tagId; + log.error(msg, e); + throw new TagManagementException(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Override + public void addDeviceTagMapping(List deviceIdentifiers, String deviceType, List tags) + throws TagManagementException, BadRequestException { + if (deviceIdentifiers == null || deviceType == null || tags == null) { + String msg = "Received incomplete data for device tag mapping."; + log.error(msg); + throw new BadRequestException(msg); + } + try { + DeviceManagementDAOFactory.beginTransaction(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + TagMappingDTO tagMappingDto = new TagMappingDTO(deviceIdentifiers, deviceType, tags); + List tagList = new ArrayList<>(); + for (String tagName : tagMappingDto.getTags()) { + Tag tag = new Tag(); + tag.setName(tagName); + tagList.add(tag); + } + + tagDAO.addTags(tagList, tenantId); + tagDAO.addDeviceTagMapping(tagMappingDto.getDeviceIdentifiers(), tagMappingDto.getDeviceType(), + tagMappingDto.getTags(), tenantId); + DeviceManagementDAOFactory.commitTransaction(); + } catch (TagManagementDAOException e) { + if (e.isUniqueConstraintViolation()) { + String msg = "Tag is already mapped to this device."; + log.info(msg, e); + throw new BadRequestException(msg); + } else { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while adding device tag mapping."; + log.error(msg, e); + throw new TagManagementException(msg, e); + } + } catch (TransactionManagementException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while adding device tag mapping."; + log.error(msg, e); + throw new TagManagementException(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Override + public void deleteDeviceTagMapping(List deviceIdentifiers, String deviceType, List tags) throws TagManagementException, BadRequestException { + if (deviceIdentifiers == null || deviceType == null || tags == null) { + String msg = "Received incomplete data for device tag mapping."; + log.error(msg); + throw new BadRequestException(msg); + } + try { + DeviceManagementDAOFactory.beginTransaction(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + TagMappingDTO tagMappingDto = new TagMappingDTO(deviceIdentifiers, deviceType, tags); + tagDAO.deleteDeviceTagMapping(tagMappingDto.getDeviceIdentifiers(), tagMappingDto.getDeviceType(), + tagMappingDto.getTags(), tenantId); + DeviceManagementDAOFactory.commitTransaction(); + } catch (TagManagementDAOException | TransactionManagementException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while deleting device tag mappings."; + log.error(msg, e); + throw new TagManagementException(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/status/task/impl/DeviceStatusTaskManagerServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/status/task/impl/DeviceStatusTaskManagerServiceImpl.java index 39fec3926a..181d72c9a6 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/status/task/impl/DeviceStatusTaskManagerServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/status/task/impl/DeviceStatusTaskManagerServiceImpl.java @@ -19,13 +19,13 @@ package io.entgra.device.mgt.core.device.mgt.core.status.task.impl; import com.google.gson.Gson; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceStatusTaskPluginConfig; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import io.entgra.device.mgt.core.device.mgt.core.status.task.DeviceStatusTaskException; import io.entgra.device.mgt.core.device.mgt.core.status.task.DeviceStatusTaskManagerService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.ntask.common.TaskException; import org.wso2.carbon.ntask.core.TaskInfo; import org.wso2.carbon.ntask.core.TaskManager; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/ArchivalTaskManagerImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/ArchivalTaskManagerImpl.java index 55cdbd7688..e81fb6999b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/ArchivalTaskManagerImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/ArchivalTaskManagerImpl.java @@ -19,13 +19,13 @@ package io.entgra.device.mgt.core.device.mgt.core.task.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import io.entgra.device.mgt.core.device.mgt.core.task.ArchivalTaskException; import io.entgra.device.mgt.core.device.mgt.core.task.ArchivalTaskManager; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.ntask.common.TaskException; import org.wso2.carbon.ntask.core.TaskInfo; import org.wso2.carbon.ntask.core.TaskManager; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/ArchivedDataDeletionTask.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/ArchivedDataDeletionTask.java index ce507ed52b..e4de14b47b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/ArchivedDataDeletionTask.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/ArchivedDataDeletionTask.java @@ -18,11 +18,11 @@ package io.entgra.device.mgt.core.device.mgt.core.task.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.core.archival.ArchivalException; import io.entgra.device.mgt.core.device.mgt.core.archival.ArchivalService; import io.entgra.device.mgt.core.device.mgt.core.archival.ArchivalServiceImpl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.ntask.core.Task; import java.text.SimpleDateFormat; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java index 9ddeea4e7a..ac374a77f7 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java @@ -18,10 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.task.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.OperationMonitoringTaskConfig; import io.entgra.device.mgt.core.device.mgt.common.StartupOperationConfig; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; @@ -29,6 +25,10 @@ import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHo import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.task.DeviceMgtTaskException; import io.entgra.device.mgt.core.device.mgt.core.task.DeviceTaskManager; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DeviceTaskManagerImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DeviceTaskManagerImpl.java index cce42b48a0..56417e61db 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DeviceTaskManagerImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DeviceTaskManagerImpl.java @@ -18,17 +18,10 @@ package io.entgra.device.mgt.core.device.mgt.core.task.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.base.ServerConfiguration; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.MonitoringOperation; -import io.entgra.device.mgt.core.device.mgt.common.OperationMonitoringTaskConfig; -import io.entgra.device.mgt.core.device.mgt.common.StartupOperationConfig; +import io.entgra.device.mgt.core.device.mgt.common.*; import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidDeviceException; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManagementException; -import io.entgra.device.mgt.core.device.mgt.common.DynamicTaskContext; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.CommandOperation; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.ProfileOperation; @@ -36,12 +29,11 @@ import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProvide import io.entgra.device.mgt.core.device.mgt.core.task.DeviceMgtTaskException; import io.entgra.device.mgt.core.device.mgt.core.task.DeviceTaskManager; import io.entgra.device.mgt.core.device.mgt.core.task.Utils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.base.ServerConfiguration; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; public class DeviceTaskManagerImpl implements DeviceTaskManager { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DeviceTaskManagerServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DeviceTaskManagerServiceImpl.java index 03e5932423..5f7c256532 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DeviceTaskManagerServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DeviceTaskManagerServiceImpl.java @@ -20,13 +20,13 @@ package io.entgra.device.mgt.core.device.mgt.core.task.impl; import com.google.gson.Gson; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.OperationMonitoringTaskConfig; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import io.entgra.device.mgt.core.device.mgt.core.task.DeviceMgtTaskException; import io.entgra.device.mgt.core.device.mgt.core.task.DeviceTaskManagerService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.ntask.common.TaskException; import org.wso2.carbon.ntask.core.TaskInfo; import org.wso2.carbon.ntask.core.TaskManager; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java index 65379945e4..cf0faa9391 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java @@ -18,13 +18,13 @@ package io.entgra.device.mgt.core.device.mgt.core.task.impl; +import io.entgra.device.mgt.core.device.mgt.common.DynamicTaskContext; +import io.entgra.device.mgt.core.device.mgt.common.ServerCtxInfo; +import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; import io.entgra.device.mgt.core.task.mgt.common.constant.TaskMgtConstants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.DynamicTaskContext; -import io.entgra.device.mgt.core.device.mgt.common.ServerCtxInfo; -import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.ntask.core.Task; import java.util.Map; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/RandomlyAssignedScheduleTask.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/RandomlyAssignedScheduleTask.java index 93c52d8fd0..3ebebda810 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/RandomlyAssignedScheduleTask.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/RandomlyAssignedScheduleTask.java @@ -18,10 +18,10 @@ package io.entgra.device.mgt.core.device.mgt.core.task.impl; +import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.ntask.core.Task; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/api/service/TraccarClientFactory.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/api/service/TraccarClientFactory.java index fdcbc5e4ad..cbc3c92c81 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/api/service/TraccarClientFactory.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/api/service/TraccarClientFactory.java @@ -18,27 +18,14 @@ package io.entgra.device.mgt.core.device.mgt.core.traccar.api.service; -import okhttp3.ConnectionPool; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONArray; -import org.json.JSONObject; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.TrackerDeviceInfo; import io.entgra.device.mgt.core.device.mgt.common.TrackerGroupInfo; import io.entgra.device.mgt.core.device.mgt.common.TrackerPermissionInfo; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TrackerAlreadyExistException; -import io.entgra.device.mgt.core.device.mgt.core.dao.TrackerManagementDAOException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; import io.entgra.device.mgt.core.device.mgt.core.dao.TrackerDAO; +import io.entgra.device.mgt.core.device.mgt.core.dao.TrackerManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dao.TrackerManagementDAOFactory; -import io.entgra.device.mgt.core.device.mgt.core.traccar.api.service.TraccarClient; import io.entgra.device.mgt.core.device.mgt.core.traccar.api.service.impl.DeviceAPIClientServiceImpl; import io.entgra.device.mgt.core.device.mgt.core.traccar.common.TraccarHandlerConstants; import io.entgra.device.mgt.core.device.mgt.core.traccar.common.beans.TraccarDevice; @@ -49,6 +36,13 @@ import io.entgra.device.mgt.core.device.mgt.core.traccar.common.config.TraccarGa import io.entgra.device.mgt.core.device.mgt.core.traccar.common.util.TraccarUtil; import io.entgra.device.mgt.core.device.mgt.core.traccar.core.config.TraccarConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.util.HttpReportingUtil; +import okhttp3.*; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONArray; +import org.json.JSONObject; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.io.IOException; import java.sql.SQLException; @@ -58,12 +52,7 @@ import java.util.Date; import java.util.List; import java.util.Objects; import java.util.Random; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; +import java.util.concurrent.*; import java.util.stream.Collectors; import java.util.stream.IntStream; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java index 2276b0117e..030128a76e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java @@ -18,25 +18,13 @@ package io.entgra.device.mgt.core.device.mgt.core.traccar.api.service.addons; -import okhttp3.ConnectionPool; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONArray; -import org.json.JSONObject; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.TrackerDeviceInfo; import io.entgra.device.mgt.core.device.mgt.common.TrackerGroupInfo; import io.entgra.device.mgt.core.device.mgt.common.TrackerPermissionInfo; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TrackerAlreadyExistException; -import io.entgra.device.mgt.core.device.mgt.core.dao.TrackerManagementDAOException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; import io.entgra.device.mgt.core.device.mgt.core.dao.TrackerDAO; +import io.entgra.device.mgt.core.device.mgt.core.dao.TrackerManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dao.TrackerManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.traccar.api.service.TraccarClient; import io.entgra.device.mgt.core.device.mgt.core.traccar.api.service.impl.DeviceAPIClientServiceImpl; @@ -49,6 +37,13 @@ import io.entgra.device.mgt.core.device.mgt.core.traccar.common.config.TraccarGa import io.entgra.device.mgt.core.device.mgt.core.traccar.common.util.TraccarUtil; import io.entgra.device.mgt.core.device.mgt.core.traccar.core.config.TraccarConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.util.HttpReportingUtil; +import okhttp3.*; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONArray; +import org.json.JSONObject; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.sql.SQLException; import java.time.LocalDateTime; @@ -57,12 +52,7 @@ import java.util.Date; import java.util.List; import java.util.Objects; import java.util.Random; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; +import java.util.concurrent.*; public class TraccarClientImpl implements TraccarClient { private static final Log log = LogFactory.getLog(TraccarClientImpl.class); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java index d7127e627b..e3c14f058e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java @@ -18,15 +18,12 @@ package io.entgra.device.mgt.core.device.mgt.core.traccar.api.service.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONObject; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.TrackerDeviceInfo; import io.entgra.device.mgt.core.device.mgt.common.TrackerPermissionInfo; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceLocation; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TrackerAlreadyExistException; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; import io.entgra.device.mgt.core.device.mgt.core.dao.TrackerManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.traccar.api.service.DeviceAPIClientService; import io.entgra.device.mgt.core.device.mgt.core.traccar.api.service.TraccarClientFactory; @@ -34,6 +31,9 @@ import io.entgra.device.mgt.core.device.mgt.core.traccar.common.beans.TraccarDev import io.entgra.device.mgt.core.device.mgt.core.traccar.common.beans.TraccarGroups; import io.entgra.device.mgt.core.device.mgt.core.traccar.common.beans.TraccarPosition; import io.entgra.device.mgt.core.device.mgt.core.traccar.common.beans.TraccarUser; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONObject; import java.util.Date; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/common/util/TraccarUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/common/util/TraccarUtil.java index 620339819b..c883aabcc1 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/common/util/TraccarUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/common/util/TraccarUtil.java @@ -18,9 +18,9 @@ package io.entgra.device.mgt.core.device.mgt.core.traccar.common.util; -import org.json.JSONObject; import io.entgra.device.mgt.core.device.mgt.core.traccar.common.beans.TraccarDevice; import io.entgra.device.mgt.core.device.mgt.core.traccar.common.beans.TraccarUser; +import org.json.JSONObject; import java.util.ArrayList; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/core/config/TraccarConfigurationManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/core/config/TraccarConfigurationManager.java index a4467a5c06..9e9949b245 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/core/config/TraccarConfigurationManager.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/traccar/core/config/TraccarConfigurationManager.java @@ -18,13 +18,13 @@ package io.entgra.device.mgt.core.device.mgt.core.traccar.core.config; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.core.traccar.common.TraccarHandlerConstants; import io.entgra.device.mgt.core.device.mgt.core.traccar.common.config.TraccarConfiguration; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; import org.wso2.carbon.utils.CarbonUtils; import javax.xml.bind.JAXBContext; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/DeviceManagementSchemaInitializer.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/DeviceManagementSchemaInitializer.java index 08261627cb..af6bea400d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/DeviceManagementSchemaInitializer.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/DeviceManagementSchemaInitializer.java @@ -18,9 +18,9 @@ package io.entgra.device.mgt.core.device.mgt.core.util; +import io.entgra.device.mgt.core.device.mgt.core.config.datasource.DataSourceConfig; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.dbcreator.DatabaseCreator; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/DeviceManagerUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/DeviceManagerUtil.java index 3e04ada25f..5ff2c15b6d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/DeviceManagerUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/DeviceManagerUtil.java @@ -83,11 +83,21 @@ import io.entgra.device.mgt.core.identity.jwt.client.extension.JWTClient; import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.AccessTokenInfo; import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; -import org.wso2.carbon.user.api.RealmConfiguration; -import org.wso2.carbon.user.api.TenantManager; -import org.wso2.carbon.user.api.UserRealm; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.api.UserStoreManager; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.protocol.HTTP; +import org.w3c.dom.Document; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.caching.impl.CacheImpl; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.user.api.*; import org.wso2.carbon.user.core.config.RealmConfigXMLProcessor; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.ConfigurationContextService; @@ -106,13 +116,7 @@ import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Base64; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; -import java.util.StringJoiner; +import java.util.*; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/HttpReportingUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/HttpReportingUtil.java index ad7a7bf67d..5f9200fa80 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/HttpReportingUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/HttpReportingUtil.java @@ -18,6 +18,8 @@ package io.entgra.device.mgt.core.device.mgt.core.util; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.EventPublishingException; +import io.entgra.device.mgt.core.device.mgt.core.DeviceManagementConstants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpResponse; @@ -30,8 +32,7 @@ import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.protocol.HTTP; import org.json.JSONObject; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.EventPublishingException; -import io.entgra.device.mgt.core.device.mgt.core.DeviceManagementConstants; + import java.io.IOException; import java.net.ConnectException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/MDMAndroidOperationUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/MDMAndroidOperationUtil.java index 4485df61a1..bdc4a4eb36 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/MDMAndroidOperationUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/MDMAndroidOperationUtil.java @@ -19,13 +19,13 @@ package io.entgra.device.mgt.core.device.mgt.core.util; import io.entgra.device.mgt.core.device.mgt.common.MDMAppConstants; +import io.entgra.device.mgt.core.device.mgt.common.app.mgt.App; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.android.AppStoreApplication; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.android.EnterpriseApplication; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.android.WebApplication; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.UnknownApplicationTypeException; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.ProfileOperation; -import io.entgra.device.mgt.core.device.mgt.common.app.mgt.App; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.UnknownApplicationTypeException; /** * diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/MDMIOSOperationUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/MDMIOSOperationUtil.java index ee25842794..3056f3a958 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/MDMIOSOperationUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/MDMIOSOperationUtil.java @@ -19,11 +19,11 @@ package io.entgra.device.mgt.core.device.mgt.core.util; import io.entgra.device.mgt.core.device.mgt.common.MDMAppConstants; +import io.entgra.device.mgt.core.device.mgt.common.app.mgt.App; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ios.AppStoreApplication; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ios.EnterpriseApplication; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ios.RemoveApplication; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ios.WebClip; -import io.entgra.device.mgt.core.device.mgt.common.app.mgt.App; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.ProfileOperation; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/MDMWindowsOperationUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/MDMWindowsOperationUtil.java index 14050b6ea4..a4a3680b64 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/MDMWindowsOperationUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/MDMWindowsOperationUtil.java @@ -23,8 +23,6 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.MDMAppConstants; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.App; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.windows.AppStoreApplication; @@ -35,6 +33,8 @@ import io.entgra.device.mgt.core.device.mgt.common.app.mgt.windows.WebClipApplic import io.entgra.device.mgt.core.device.mgt.common.exceptions.UnknownApplicationTypeException; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.ProfileOperation; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.util.ArrayList; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementConfigTests.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementConfigTests.java index d71e8f7c67..f8e8135beb 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementConfigTests.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementConfigTests.java @@ -17,12 +17,12 @@ */ package io.entgra.device.mgt.core.device.mgt.core; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementRepositoryTests.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementRepositoryTests.java index b14a258382..808d021f9e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementRepositoryTests.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementRepositoryTests.java @@ -17,14 +17,14 @@ */ package io.entgra.device.mgt.core.device.mgt.core; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService; import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import io.entgra.device.mgt.core.device.mgt.core.task.impl.DeviceTaskManagerServiceImpl; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; public class DeviceManagementRepositoryTests{ diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestDeviceManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestDeviceManager.java index fff624bc13..1f75299e50 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestDeviceManager.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestDeviceManager.java @@ -17,12 +17,7 @@ */ package io.entgra.device.mgt.core.device.mgt.core; -import io.entgra.device.mgt.core.device.mgt.common.DeviceManager; -import io.entgra.device.mgt.core.device.mgt.common.FeatureManager; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; -import io.entgra.device.mgt.core.device.mgt.common.Feature; +import io.entgra.device.mgt.core.device.mgt.common.*; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.License; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestHeartBeatManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestHeartBeatManagementService.java index 8d5924709c..9cda4c3a74 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestHeartBeatManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestHeartBeatManagementService.java @@ -18,11 +18,11 @@ package io.entgra.device.mgt.core.device.mgt.core; +import io.entgra.device.mgt.core.device.mgt.common.ServerCtxInfo; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.dto.ServerContext; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; -import io.entgra.device.mgt.core.device.mgt.common.ServerCtxInfo; import java.util.Map; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestTaskServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestTaskServiceImpl.java index b4975e233b..f1debd39ec 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestTaskServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestTaskServiceImpl.java @@ -19,11 +19,9 @@ package io.entgra.device.mgt.core.device.mgt.core; import io.entgra.device.mgt.core.device.mgt.core.task.TestTaskManagerImpl; import org.wso2.carbon.ntask.common.TaskException; -import org.wso2.carbon.ntask.core.TaskInfo; import org.wso2.carbon.ntask.core.TaskManager; import org.wso2.carbon.ntask.core.service.TaskService; -import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestUtils.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestUtils.java index 4d8e11064d..0618b7d94b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestUtils.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestUtils.java @@ -17,13 +17,14 @@ */ package io.entgra.device.mgt.core.device.mgt.core; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.GroupPaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; +import io.entgra.device.mgt.core.device.mgt.common.tag.mgt.Tag; import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.registry.core.config.RegistryContext; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.internal.RegistryDataHolder; @@ -100,6 +101,45 @@ public class TestUtils { return group; } + public static Tag getTag1() { + return new Tag(1,"tag1", "This is tag1"); + } + + public static Tag getTag2() { + return new Tag( 2, "tag2", "This is tag2"); + } + + public static Tag getTag1Dao() { + return new Tag("tag1", "This is tag1"); + } + + public static Tag getTag2Dao() { + return new Tag( "tag2", "This is tag2"); + } + + public static Tag getTag3() { + return new Tag("tag3", "This is tag3"); + } + + public static List createTagList1() { + List tagList = new ArrayList<>(); + tagList.add(new Tag(null, "This is tag1")); + return tagList; + } + + public static List createTagList2() { + List tagList = new ArrayList<>(); + tagList.add(getTag1()); + tagList.add(getTag2()); + return tagList; + } + + public static List createTagList3() { + List tagList = new ArrayList<>(); + tagList.add(getTag1Dao()); + tagList.add(getTag2Dao()); + return tagList; + } public static GroupPaginationRequest createPaginationRequest(){ GroupPaginationRequest request = new GroupPaginationRequest(0, 5); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/AppManagementConfigurationManagerTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/AppManagementConfigurationManagerTest.java index 6db3fc98de..4a9daf3b27 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/AppManagementConfigurationManagerTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/AppManagementConfigurationManagerTest.java @@ -18,12 +18,12 @@ package io.entgra.device.mgt.core.device.mgt.core.app.mgt; +import io.entgra.device.mgt.core.device.mgt.core.app.mgt.config.AppManagementConfig; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import io.entgra.device.mgt.core.device.mgt.core.app.mgt.config.AppManagementConfig; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/ApplicationManagementProviderServiceTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/ApplicationManagementProviderServiceTest.java index bac36561e4..21e0652a98 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/ApplicationManagementProviderServiceTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/ApplicationManagementProviderServiceTest.java @@ -17,18 +17,18 @@ */ package io.entgra.device.mgt.core.device.mgt.core.app.mgt; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.Application; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.core.DeviceManagementPluginRepository; import io.entgra.device.mgt.core.device.mgt.core.TestDeviceManagementService; import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/authorization/DeviceAccessAuthorizationServiceTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/authorization/DeviceAccessAuthorizationServiceTest.java index 0e31232a03..10c81e2755 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/authorization/DeviceAccessAuthorizationServiceTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/authorization/DeviceAccessAuthorizationServiceTest.java @@ -18,23 +18,13 @@ package io.entgra.device.mgt.core.device.mgt.core.authorization; -import org.apache.commons.dbcp.BasicDataSource; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.CarbonConstants; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceNotFoundException; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationException; import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAuthorizationResult; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceNotFoundException; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupManagementException; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.RoleDoesNotExistException; import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException; @@ -47,23 +37,30 @@ import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProvide import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderServiceImpl; +import org.apache.commons.dbcp.BasicDataSource; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.mockito.Mockito; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.CarbonConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.registry.core.config.RegistryContext; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.internal.RegistryDataHolder; import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService; import org.wso2.carbon.registry.core.service.RegistryService; +import org.wso2.carbon.user.api.Permission; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; -import org.wso2.carbon.user.api.Permission; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.tenant.JDBCTenantManager; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; + import java.io.InputStream; -import java.util.ArrayList; -import java.util.Map; -import java.util.List; -import java.util.HashMap; -import java.util.Arrays; +import java.util.*; /** * Unit tests for DeviceAccessAuthorizationServiceTest diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/cache/DeviceCacheManagerImplTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/cache/DeviceCacheManagerImplTest.java index afe3d20299..dbd947cc02 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/cache/DeviceCacheManagerImplTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/cache/DeviceCacheManagerImplTest.java @@ -18,11 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.cache; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; @@ -32,7 +27,13 @@ import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; import io.entgra.device.mgt.core.device.mgt.core.config.cache.DeviceCacheConfiguration; +import org.mockito.Mockito; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; + import java.io.File; import java.io.IOException; import java.util.ArrayList; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/common/BaseDeviceManagementTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/common/BaseDeviceManagementTest.java index 993a83a046..d1e87b7b66 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/common/BaseDeviceManagementTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/common/BaseDeviceManagementTest.java @@ -17,17 +17,6 @@ */ package io.entgra.device.mgt.core.device.mgt.core.common; -import org.apache.axis2.AxisFault; -import org.apache.axis2.context.ConfigurationContext; -import org.apache.axis2.context.ConfigurationContextFactory; -import org.apache.tomcat.jdbc.pool.PoolProperties; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Optional; -import org.testng.annotations.Parameters; -import org.w3c.dom.Document; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.core.TestUtils; import io.entgra.device.mgt.core.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl; @@ -44,6 +33,17 @@ import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProvide import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderServiceImpl; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; +import org.apache.axis2.AxisFault; +import org.apache.axis2.context.ConfigurationContext; +import org.apache.axis2.context.ConfigurationContextFactory; +import org.apache.tomcat.jdbc.pool.PoolProperties; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Optional; +import org.testng.annotations.Parameters; +import org.w3c.dom.Document; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.registry.core.config.RegistryContext; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.internal.RegistryDataHolder; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/common/TestDataHolder.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/common/TestDataHolder.java index 322b2b449d..91ed4aaef4 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/common/TestDataHolder.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/common/TestDataHolder.java @@ -17,16 +17,13 @@ */ package io.entgra.device.mgt.core.device.mgt.core.common; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; -import io.entgra.device.mgt.core.device.mgt.common.MonitoringOperation; -import io.entgra.device.mgt.core.device.mgt.common.OperationMonitoringTaskConfig; +import io.entgra.device.mgt.core.device.mgt.common.*; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.Application; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceData; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceInfo; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.Notification; +import io.entgra.device.mgt.core.device.mgt.common.tag.mgt.Tag; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import java.util.ArrayList; @@ -34,11 +31,14 @@ import java.util.Date; import java.util.List; import java.util.Properties; import java.util.Calendar; +import java.util.Arrays; public class TestDataHolder { public final static String TEST_DEVICE_TYPE = "TEST-DEVICE-TYPE"; public final static Integer SUPER_TENANT_ID = -1234; + public final static Integer ALTERNATE_TENANT_ID = 1234; + public final static Integer ALTERNATE_TENANT_ID_1 = 1235; public final static String SUPER_TENANT_DOMAIN = "carbon.super"; public final static String initialDeviceIdentifier = "12345"; public final static String initialDeviceName = "TEST-DEVICE"; @@ -46,6 +46,7 @@ public class TestDataHolder { public static final String OPERATION_CONFIG = "TEST-OPERATION-"; public static Device initialTestDevice; public static DeviceType initialTestDeviceType; + public static List TAGS = Arrays.asList("tag1", "tag2", "tag3"); public static Date getTimeBefore(int minutes) { Calendar calendar = Calendar.getInstance(); @@ -56,7 +57,7 @@ public class TestDataHolder { public static Device generateDummyDeviceData(String deviceType) { Device device = new Device(); device.setEnrolmentInfo(generateEnrollmentInfo(new Date().getTime(), new Date().getTime(), OWNER, EnrolmentInfo - .OwnerShip.BYOD, EnrolmentInfo.Status.ACTIVE)); + .OwnerShip.BYOD, EnrolmentInfo.Status.ACTIVE, TAGS)); device.setDescription("Test Description"); device.setDeviceIdentifier(initialDeviceIdentifier); device.setType(deviceType); @@ -65,16 +66,26 @@ public class TestDataHolder { public static EnrolmentInfo generateEnrollmentInfo(long dateOfEnrollment, long dateOfLastUpdate, String owner, EnrolmentInfo.OwnerShip ownership, - EnrolmentInfo.Status status) { + EnrolmentInfo.Status status, List tags) { EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); enrolmentInfo.setDateOfEnrolment(dateOfEnrollment); enrolmentInfo.setDateOfLastUpdate(dateOfLastUpdate); enrolmentInfo.setOwner(owner); enrolmentInfo.setOwnership(ownership); enrolmentInfo.setStatus(status); + enrolmentInfo.setTags(tags); return enrolmentInfo; } + public static List getTagList() { + List tagList = new ArrayList<>(); + for (int i = 1; i <= 3; i++) { + Tag tag = new Tag("tag" + i, "This is tag" + i); + tagList.add(tag); + } + return tagList; + } + public static DeviceInfo generateDummyDeviceInfo() { DeviceInfo deviceInfo = new DeviceInfo(); deviceInfo.setDeviceModel("DUMMY_MODEL"); @@ -141,8 +152,12 @@ public class TestDataHolder { public static Device generateDummyDeviceData(DeviceIdentifier deviceIdentifier) { Device device = new Device(); + List tags = new ArrayList<>(); + tags.add("tag1"); + tags.add("tag2"); + tags.add("tag3"); device.setEnrolmentInfo(generateEnrollmentInfo(new Date().getTime(), new Date().getTime(), OWNER, EnrolmentInfo - .OwnerShip.BYOD, EnrolmentInfo.Status.ACTIVE)); + .OwnerShip.BYOD, EnrolmentInfo.Status.ACTIVE, tags)); device.setDescription("Test Description"); device.setDeviceIdentifier(deviceIdentifier.getId()); device.setType(deviceIdentifier.getType()); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/dao/DevicePersistTests.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/dao/DevicePersistTests.java index a8bc1b6924..045634b4e9 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/dao/DevicePersistTests.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/dao/DevicePersistTests.java @@ -18,28 +18,31 @@ package io.entgra.device.mgt.core.device.mgt.core.dao; +import io.entgra.device.mgt.core.device.mgt.common.Device; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; -import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; +import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo.Status; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceData; -import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoCluster; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; +import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoCoordinate; import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoQuery; +import io.entgra.device.mgt.core.device.mgt.common.geo.service.GeoCluster; +import io.entgra.device.mgt.core.device.mgt.core.TestUtils; +import io.entgra.device.mgt.core.device.mgt.core.common.BaseDeviceManagementTest; +import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder; +import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import org.apache.commons.collections.map.SingletonMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo.Status; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; -import io.entgra.device.mgt.core.device.mgt.core.TestUtils; -import io.entgra.device.mgt.core.device.mgt.core.common.BaseDeviceManagementTest; -import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder; -import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; -import java.sql.*; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -47,6 +50,7 @@ import java.util.List; public class DevicePersistTests extends BaseDeviceManagementTest { DeviceDAO deviceDAO; + TagDAO tagDAO; DeviceTypeDAO deviceTypeDAO; private static final Log log = LogFactory.getLog(DevicePersistTests.class); @@ -56,6 +60,7 @@ public class DevicePersistTests extends BaseDeviceManagementTest { public void init() throws Exception { initDataSource(); deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); + tagDAO = DeviceManagementDAOFactory.getTagDAO(); deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); } @@ -103,6 +108,8 @@ public class DevicePersistTests extends BaseDeviceManagementTest { int deviceId = deviceDAO.addDevice(TestDataHolder.initialTestDeviceType.getId(), device, tenantId); device.setId(deviceId); deviceDAO.addEnrollment(device, tenantId); + tagDAO.addTags(TestDataHolder.getTagList(), tenantId); + tagDAO.addDeviceTagMapping(Collections.singletonList(device.getDeviceIdentifier()), TestDataHolder.TEST_DEVICE_TYPE, TestDataHolder.TAGS, tenantId); DeviceManagementDAOFactory.commitTransaction(); TestDataHolder.initialTestDevice = device; } catch (DeviceManagementDAOException e) { @@ -115,6 +122,10 @@ public class DevicePersistTests extends BaseDeviceManagementTest { String msg = "Error occurred while initiating transaction"; log.error(msg, e); Assert.fail(msg, e); + } catch (TagManagementDAOException e) { + String msg = "Error occurred while adding tag mappings"; + log.error(msg, e); + Assert.fail(msg, e); } finally { DeviceManagementDAOFactory.closeConnection(); } @@ -508,6 +519,223 @@ public class DevicePersistTests extends BaseDeviceManagementTest { } } + @Test(dependsOnMethods = "testAddDeviceTest") + public void getDevicesWithTag() throws DeviceManagementDAOException, TransactionManagementException { + try { + PaginationRequest pr = new PaginationRequest(0, 10); + pr.setTags(Collections.singletonList("tag1")); + DeviceManagementDAOFactory.beginTransaction(); + List results = deviceDAO.getDevices(pr, TestDataHolder.SUPER_TENANT_ID); + Assert.assertEquals(1, results.size(), "No device returned"); + DeviceManagementDAOFactory.commitTransaction(); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving the device" + e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = "testAddDeviceTest") + public void getDevicesWithTags() throws DeviceManagementDAOException, TransactionManagementException { + try { + PaginationRequest pr = new PaginationRequest(0, 10); + pr.setTags(TestDataHolder.TAGS); + DeviceManagementDAOFactory.beginTransaction(); + List results = deviceDAO.getDevices(pr, TestDataHolder.SUPER_TENANT_ID); + Assert.assertEquals(1, results.size(), "No device returned"); + DeviceManagementDAOFactory.commitTransaction(); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving the device" + e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = "testAddDeviceTest") + public void getDevicesWithNonExistingTags() throws DeviceManagementDAOException, TransactionManagementException { + try { + PaginationRequest pr = new PaginationRequest(0, 10); + pr.setTags(Collections.singletonList("tag10")); + DeviceManagementDAOFactory.beginTransaction(); + List results = deviceDAO.getDevices(pr, TestDataHolder.SUPER_TENANT_ID); + Assert.assertEquals(0, results.size(), "No device returned"); + DeviceManagementDAOFactory.commitTransaction(); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving the device" + e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = "testAddDeviceTest") + public void getDevicesWithTagAndStatus() throws DeviceManagementDAOException, TransactionManagementException { + try { + PaginationRequest pr = new PaginationRequest(0, 10); + pr.setStatusList(Collections.singletonList(Status.ACTIVE.name())); + pr.setTags(Collections.singletonList("tag1")); + DeviceManagementDAOFactory.beginTransaction(); + List results = deviceDAO.getDevices(pr, TestDataHolder.SUPER_TENANT_ID); + Assert.assertEquals(1, results.size(), "No device returned"); + DeviceManagementDAOFactory.commitTransaction(); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving the device" + e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = "testAddDeviceTest") + public void getDevicesWithTagsAndStatus() throws DeviceManagementDAOException, TransactionManagementException { + List tags = new ArrayList<>() ; + try { + PaginationRequest pr = new PaginationRequest(0, 10); + pr.setStatusList(Collections.singletonList(Status.ACTIVE.name())); + pr.setTags(tags); + DeviceManagementDAOFactory.beginTransaction(); + List results = deviceDAO.getDevices(pr, TestDataHolder.SUPER_TENANT_ID); + Assert.assertEquals(1, results.size(), "No device returned"); + DeviceManagementDAOFactory.commitTransaction(); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving the device" + e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = "testAddDeviceTest") + public void getDeviceCountWithTag() throws DeviceManagementDAOException, TransactionManagementException { + try { + PaginationRequest pr = new PaginationRequest(0, 10); + pr.setTags(Collections.singletonList("tag1")); + DeviceManagementDAOFactory.beginTransaction(); + int result = deviceDAO.getDeviceCount(pr, TestDataHolder.SUPER_TENANT_ID); + Assert.assertEquals(1, result, "No device returned"); + DeviceManagementDAOFactory.commitTransaction(); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving the device" + e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = "testAddDeviceTest") + public void getDeviceCountWithTags() throws DeviceManagementDAOException, TransactionManagementException { + try { + PaginationRequest pr = new PaginationRequest(0, 10); + pr.setTags(TestDataHolder.TAGS); + DeviceManagementDAOFactory.beginTransaction(); + int result = deviceDAO.getDeviceCount(pr, TestDataHolder.SUPER_TENANT_ID); + Assert.assertEquals(1, result, "No device returned"); + DeviceManagementDAOFactory.commitTransaction(); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving the device" + e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = "testAddDeviceTest") + public void getDeviceCountWithTagAndStatus() throws DeviceManagementDAOException, TransactionManagementException { + try { + PaginationRequest pr = new PaginationRequest(0, 10); + pr.setStatusList(Collections.singletonList(Status.ACTIVE.name())); + pr.setTags(Collections.singletonList("tag1")); + DeviceManagementDAOFactory.beginTransaction(); + int result = deviceDAO.getDeviceCount(pr, TestDataHolder.SUPER_TENANT_ID); + Assert.assertEquals(1, result, "No device returned"); + DeviceManagementDAOFactory.commitTransaction(); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving the device" + e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = "testAddDeviceTest") + public void getDeviceCountWithTagsAndStatus() throws DeviceManagementDAOException, TransactionManagementException { + try { + PaginationRequest pr = new PaginationRequest(0, 10); + pr.setStatusList(Collections.singletonList(Status.ACTIVE.name())); + pr.setTags(TestDataHolder.TAGS); + DeviceManagementDAOFactory.beginTransaction(); + int result = deviceDAO.getDeviceCount(pr, TestDataHolder.SUPER_TENANT_ID); + Assert.assertEquals(1, result, "No device returned"); + DeviceManagementDAOFactory.commitTransaction(); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving the device" + e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = "testAddDeviceTest") + public void getDevicesWithTagAndGroupId() throws DeviceManagementDAOException, TransactionManagementException { + try { + PaginationRequest pr = new PaginationRequest(0, 10); + pr.setTags(Collections.singletonList("tag1")); + pr.setGroupId(1); + DeviceManagementDAOFactory.beginTransaction(); + List results = deviceDAO.searchDevicesInGroup(pr, TestDataHolder.SUPER_TENANT_ID); + Assert.assertEquals(0, results.size(), "No device returned"); + DeviceManagementDAOFactory.commitTransaction(); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving the device" + e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = "testAddDeviceTest") + public void getDevicesWithTagsAndGroupId() throws DeviceManagementDAOException, TransactionManagementException { + try { + PaginationRequest pr = new PaginationRequest(0, 10); + pr.setTags(TestDataHolder.TAGS); + pr.setGroupId(1); + DeviceManagementDAOFactory.beginTransaction(); + List results = deviceDAO.searchDevicesInGroup(pr, TestDataHolder.SUPER_TENANT_ID); + Assert.assertEquals(0, results.size(), "No device returned"); + DeviceManagementDAOFactory.commitTransaction(); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving the device" + e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = "testAddDeviceTest") + public void getDeviceCountWithTagAndGroupId() throws DeviceManagementDAOException, TransactionManagementException { + try { + PaginationRequest pr = new PaginationRequest(0, 10); + pr.setTags(Collections.singletonList("tag1")); + pr.setGroupId(1); + DeviceManagementDAOFactory.beginTransaction(); + int result = deviceDAO.getCountOfDevicesInGroup(pr, TestDataHolder.SUPER_TENANT_ID); + Assert.assertEquals(0, result, "No device returned"); + DeviceManagementDAOFactory.commitTransaction(); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving the device" + e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = "testAddDeviceTest") + public void getDeviceCountWithTagsAndGroupId() throws DeviceManagementDAOException, TransactionManagementException { + try { + PaginationRequest pr = new PaginationRequest(0, 10); + pr.setTags(TestDataHolder.TAGS); + pr.setGroupId(1); + DeviceManagementDAOFactory.beginTransaction(); + int result = deviceDAO.getCountOfDevicesInGroup(pr, TestDataHolder.SUPER_TENANT_ID); + Assert.assertEquals(0, result, "No device returned"); + DeviceManagementDAOFactory.commitTransaction(); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving the device" + e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + @Test(dependsOnMethods = "testAddDeviceTest") public void getCountOfDevicesInGroup() throws DeviceManagementDAOException, TransactionManagementException { PaginationRequest pr = new PaginationRequest(0, 10); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceStatusPersistenceTests.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceStatusPersistenceTests.java index 6375f5b9da..d26e2e292b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceStatusPersistenceTests.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceStatusPersistenceTests.java @@ -17,21 +17,25 @@ */ package io.entgra.device.mgt.core.device.mgt.core.dao; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.testng.Assert; -import org.testng.annotations.Test; -import org.testng.annotations.BeforeClass; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceStatus; import io.entgra.device.mgt.core.device.mgt.core.common.BaseDeviceManagementTest; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import java.sql.SQLException; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; import java.util.List; +import java.util.Map; +import java.util.TreeSet; import java.util.stream.Stream; import static io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo.Status.*; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrolmentPersistenceTests.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrolmentPersistenceTests.java index c7b8de10b1..c693682ddf 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrolmentPersistenceTests.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrolmentPersistenceTests.java @@ -17,16 +17,16 @@ */ package io.entgra.device.mgt.core.device.mgt.core.dao; +import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; +import io.entgra.device.mgt.core.device.mgt.core.common.BaseDeviceManagementTest; +import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; -import io.entgra.device.mgt.core.device.mgt.core.common.BaseDeviceManagementTest; -import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder; import java.sql.SQLException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupPersistTests.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupPersistTests.java index e484bc4923..264caa0a6e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupPersistTests.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupPersistTests.java @@ -18,19 +18,19 @@ package io.entgra.device.mgt.core.device.mgt.core.dao; +import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; +import io.entgra.device.mgt.core.device.mgt.common.GroupPaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; +import io.entgra.device.mgt.core.device.mgt.core.common.BaseDeviceManagementTest; +import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.GroupPaginationRequest; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; -import io.entgra.device.mgt.core.device.mgt.core.common.BaseDeviceManagementTest; -import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder; import java.sql.SQLException; import java.util.ArrayList; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/dao/TagPersistTests.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/dao/TagPersistTests.java new file mode 100644 index 0000000000..a18049fa3f --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/dao/TagPersistTests.java @@ -0,0 +1,216 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.core.dao; + +import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; +import io.entgra.device.mgt.core.device.mgt.common.tag.mgt.Tag; +import io.entgra.device.mgt.core.device.mgt.core.TestUtils; +import io.entgra.device.mgt.core.device.mgt.core.common.BaseDeviceManagementTest; +import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.List; + +public class TagPersistTests extends BaseDeviceManagementTest { + + private TagDAO tagDAO; + private static final Log log = LogFactory.getLog(TagPersistTests.class); + + @BeforeClass + @Override + public void init() throws Exception { + initDataSource(); + tagDAO = DeviceManagementDAOFactory.getTagDAO(); + } + + @Test + public void addTag() { + try { + DeviceManagementDAOFactory.beginTransaction(); + tagDAO.addTags(TestUtils.createTagList3(), TestDataHolder.ALTERNATE_TENANT_ID); + log.debug("Tags added to the database"); + Tag tag = tagDAO.getTagByName("tag1", TestDataHolder.ALTERNATE_TENANT_ID); + DeviceManagementDAOFactory.commitTransaction(); + Assert.assertNotNull(tag, "Tag should be added and retrieved."); + Assert.assertEquals(tag.getName(), "tag1", "Tag name mismatch."); + } catch (TagManagementDAOException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while adding tag list type."; + log.error(msg, e); + Assert.fail(msg, e); + } catch (TransactionManagementException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while initiating transaction."; + log.error(msg, e); + Assert.fail(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = "addTag") + public void updateTag() { + try { + DeviceManagementDAOFactory.beginTransaction(); + String updatedDescription = "Updated Description"; + Tag tag = tagDAO.getTagByName("tag1", TestDataHolder.ALTERNATE_TENANT_ID); + Tag tagToUpdate = new Tag(tag.getId(), tag.getName(), updatedDescription); + tagDAO.updateTag(tagToUpdate, TestDataHolder.ALTERNATE_TENANT_ID); + log.debug("Tag updated in the database"); + tag = tagDAO.getTagByName("tag1", TestDataHolder.ALTERNATE_TENANT_ID); + DeviceManagementDAOFactory.commitTransaction(); + Assert.assertEquals(tag.getDescription(), updatedDescription, "Tag description mismatch."); + } catch (TagManagementDAOException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while updating tag."; + log.error(msg, e); + Assert.fail(msg, e); + } catch (TransactionManagementException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while initiating transaction."; + log.error(msg, e); + Assert.fail(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = "updateTag") + public void deleteTag() { + try { + DeviceManagementDAOFactory.beginTransaction(); + tagDAO.deleteTag(1, TestDataHolder.ALTERNATE_TENANT_ID); + log.debug("Tag deleted from the database"); + Tag deletedTag = tagDAO.getTagById(1, TestDataHolder.ALTERNATE_TENANT_ID); + DeviceManagementDAOFactory.commitTransaction(); + Assert.assertNull(deletedTag, "Tag should be deleted."); + } catch (TagManagementDAOException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while deleting tag."; + log.error(msg, e); + Assert.fail(msg, e); + } catch (TransactionManagementException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while initiating transaction."; + log.error(msg, e); + Assert.fail(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = {"deleteTag"}) + public void getTags() { + try { + DeviceManagementDAOFactory.beginTransaction(); + List tags = tagDAO.getTags(TestDataHolder.ALTERNATE_TENANT_ID); + DeviceManagementDAOFactory.commitTransaction(); + log.debug("Tags retrieved successfully."); + Assert.assertEquals(tags.size(), 2); + } catch (TagManagementDAOException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while retrieving tags."; + log.error(msg, e); + Assert.fail(msg, e); + } catch (TransactionManagementException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while initiating transaction."; + log.error(msg, e); + Assert.fail(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = {"getTags"}) + public void getTagByName() { + try { + String tagName = "tag2"; + DeviceManagementDAOFactory.beginTransaction(); + Tag tag = tagDAO.getTagByName(tagName, TestDataHolder.ALTERNATE_TENANT_ID); + DeviceManagementDAOFactory.commitTransaction(); + log.debug("Tag " + tagName + " retrieved successfully."); + Assert.assertEquals(tag.getName(), "tag2"); + } catch (TagManagementDAOException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while retrieving tag by Id."; + log.error(msg, e); + Assert.fail(msg, e); + } catch (TransactionManagementException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while initiating transaction."; + log.error(msg, e); + Assert.fail(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = "getTagByName") + public void addTagsForAlternateTenant() { + try { + DeviceManagementDAOFactory.beginTransaction(); + //Here, adding a same tag name for a separate tenant is tested. + tagDAO.addTags(TestUtils.createTagList3(), TestDataHolder.ALTERNATE_TENANT_ID_1); + log.debug("Tags added for a alternate tenant"); + List tagList = tagDAO.getTags(TestDataHolder.ALTERNATE_TENANT_ID_1); + DeviceManagementDAOFactory.commitTransaction(); + Assert.assertEquals(tagList.size(), 2, "Tag count mismatch."); + } catch (TagManagementDAOException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while adding tags for a different tenant."; + log.error(msg, e); + Assert.fail(msg, e); + } catch (TransactionManagementException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while initiating transaction."; + log.error(msg, e); + Assert.fail(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Test(dependsOnMethods = "addTagsForAlternateTenant") + public void getTagsOfAlternateTenant() { + try { + DeviceManagementDAOFactory.beginTransaction(); + List tagList = tagDAO.getTags(TestDataHolder.ALTERNATE_TENANT_ID_1); + log.debug("Tags retrieved for a alternate tenant " + TestDataHolder.ALTERNATE_TENANT_ID_1); + DeviceManagementDAOFactory.commitTransaction(); + Assert.assertEquals(tagList.size(), 2, "Tag count mismatch."); + } catch (TagManagementDAOException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while adding tags for a different tenant."; + log.error(msg, e); + Assert.fail(msg, e); + } catch (TransactionManagementException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while initiating transaction."; + log.error(msg, e); + Assert.fail(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/geo/service/GeoLocationProviderServiceTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/geo/service/GeoLocationProviderServiceTest.java index f6c5ac8cc3..7ebfa3df1f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/geo/service/GeoLocationProviderServiceTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/geo/service/GeoLocationProviderServiceTest.java @@ -18,10 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.geo.service; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; @@ -33,6 +29,10 @@ import io.entgra.device.mgt.core.device.mgt.core.TestDeviceManagementService; import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import org.mockito.Mockito; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import org.wso2.carbon.event.processor.stub.EventProcessorAdminServiceStub; import org.wso2.carbon.event.processor.stub.types.ExecutionPlanConfigurationDto; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockConnection.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockConnection.java index 6ed496af34..58f6de47ae 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockConnection.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockConnection.java @@ -17,23 +17,7 @@ */ package io.entgra.device.mgt.core.device.mgt.core.mock; -import java.sql.Array; -import java.sql.Blob; -import java.sql.CallableStatement; -import java.sql.Clob; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.NClob; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.RowIdLifetime; -import java.sql.SQLClientInfoException; -import java.sql.SQLException; -import java.sql.SQLWarning; -import java.sql.SQLXML; -import java.sql.Savepoint; -import java.sql.Statement; -import java.sql.Struct; +import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Map; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockDataSource.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockDataSource.java index 9abcac8e56..7fb19f0e64 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockDataSource.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockDataSource.java @@ -17,8 +17,7 @@ */ package io.entgra.device.mgt.core.device.mgt.core.mock; -import org.mockito.Mock; - +import javax.sql.DataSource; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; @@ -26,7 +25,6 @@ import java.sql.SQLFeatureNotSupportedException; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; -import javax.sql.DataSource; /** * This is the mock data source implementation that will be used in the test cases. diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockDatabaseMetaData.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockDatabaseMetaData.java index bfba37aaf7..c63ebb0d8d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockDatabaseMetaData.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockDatabaseMetaData.java @@ -19,11 +19,7 @@ package io.entgra.device.mgt.core.device.mgt.core.mock; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.ResultSet; -import java.sql.RowIdLifetime; -import java.sql.SQLException; +import java.sql.*; public class MockDatabaseMetaData implements DatabaseMetaData { private String url; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockJDBCDriver.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockJDBCDriver.java index 69326b5021..835a974c95 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockJDBCDriver.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockJDBCDriver.java @@ -17,11 +17,7 @@ */ package io.entgra.device.mgt.core.device.mgt.core.mock; -import java.sql.Connection; -import java.sql.Driver; -import java.sql.DriverPropertyInfo; -import java.sql.SQLException; -import java.sql.SQLFeatureNotSupportedException; +import java.sql.*; import java.util.Properties; import java.util.logging.Logger; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockResultSet.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockResultSet.java index 8b66d170b3..97153d485a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockResultSet.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockResultSet.java @@ -21,21 +21,7 @@ import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; -import java.sql.Array; -import java.sql.Blob; -import java.sql.Clob; -import java.sql.Date; -import java.sql.NClob; -import java.sql.Ref; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.RowId; -import java.sql.SQLException; -import java.sql.SQLWarning; -import java.sql.SQLXML; -import java.sql.Statement; -import java.sql.Time; -import java.sql.Timestamp; +import java.sql.*; import java.util.ArrayList; import java.util.Calendar; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockStatement.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockStatement.java index 3abd1d2e8d..e531e5fd1d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockStatement.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/mock/MockStatement.java @@ -21,24 +21,7 @@ import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; -import java.sql.Array; -import java.sql.Blob; -import java.sql.Clob; -import java.sql.Connection; -import java.sql.Date; -import java.sql.NClob; -import java.sql.ParameterMetaData; -import java.sql.PreparedStatement; -import java.sql.Ref; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.RowId; -import java.sql.SQLException; -import java.sql.SQLWarning; -import java.sql.SQLXML; -import java.sql.Statement; -import java.sql.Time; -import java.sql.Timestamp; +import java.sql.*; import java.util.ArrayList; import java.util.Calendar; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/NotificationManagementServiceImplTests.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/NotificationManagementServiceImplTests.java index 0642e6d8b5..3594a7872b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/NotificationManagementServiceImplTests.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/notification/mgt/NotificationManagementServiceImplTests.java @@ -17,16 +17,11 @@ */ package io.entgra.device.mgt.core.device.mgt.core.notification.mgt; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.EntityDoesNotExistException; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.EntityDoesNotExistException; import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.Notification; import io.entgra.device.mgt.core.device.mgt.common.notification.mgt.NotificationManagementException; import io.entgra.device.mgt.core.device.mgt.core.TestDeviceManagementService; @@ -38,6 +33,11 @@ import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementServic import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderServiceImpl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import org.wso2.carbon.registry.core.config.RegistryContext; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.internal.RegistryDataHolder; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/operation/OperationManagementNegativeDBOperationTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/operation/OperationManagementNegativeDBOperationTest.java index 04c82b5f80..d72fa2f28a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/operation/OperationManagementNegativeDBOperationTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/operation/OperationManagementNegativeDBOperationTest.java @@ -17,15 +17,10 @@ */ package io.entgra.device.mgt.core.device.mgt.core.operation; -import org.powermock.api.mockito.PowerMockito; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManagementException; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManager; @@ -38,6 +33,11 @@ import io.entgra.device.mgt.core.device.mgt.core.mock.MockDataSource; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationManagerImpl; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import org.powermock.api.mockito.PowerMockito; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import javax.sql.DataSource; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/operation/OperationManagementNoDBSchemaTests.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/operation/OperationManagementNoDBSchemaTests.java index 2025d6800b..f9f1485839 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/operation/OperationManagementNoDBSchemaTests.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/operation/OperationManagementNoDBSchemaTests.java @@ -18,16 +18,11 @@ package io.entgra.device.mgt.core.device.mgt.core.operation; -import org.powermock.api.mockito.PowerMockito; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidDeviceException; -import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManagementException; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManager; @@ -41,6 +36,11 @@ import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.CommandOperation; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationManagerImpl; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import org.powermock.api.mockito.PowerMockito; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import javax.sql.DataSource; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/operation/OperationManagementTests.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/operation/OperationManagementTests.java index dca9d7ebd6..10a522dd56 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/operation/OperationManagementTests.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/operation/OperationManagementTests.java @@ -18,37 +18,25 @@ package io.entgra.device.mgt.core.device.mgt.core.operation; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.powermock.api.mockito.PowerMockito; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.*; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidDeviceException; -import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; -import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.ActivityStatus; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManagementException; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManager; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.*; import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService; import io.entgra.device.mgt.core.device.mgt.core.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.core.TestDeviceManagementService; import io.entgra.device.mgt.core.device.mgt.core.common.BaseDeviceManagementTest; import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; -import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.CommandOperation; -import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.ConfigOperation; -import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationManagerImpl; -import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.PolicyOperation; -import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.ProfileOperation; +import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.*; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.powermock.api.mockito.PowerMockito; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import java.text.ParseException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/operation/ScheduledTaskOperationTests.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/operation/ScheduledTaskOperationTests.java index b447849c21..bcf0045faf 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/operation/ScheduledTaskOperationTests.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/operation/ScheduledTaskOperationTests.java @@ -17,11 +17,6 @@ */ package io.entgra.device.mgt.core.device.mgt.core.operation; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; @@ -42,6 +37,11 @@ import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationManagerI import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.task.DeviceTaskManagerService; import io.entgra.device.mgt.core.device.mgt.core.task.impl.DeviceTaskManagerServiceImpl; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import org.wso2.carbon.ntask.core.internal.TasksDSComponent; import org.wso2.carbon.ntask.core.service.TaskService; import org.wso2.carbon.ntask.core.service.impl.TaskServiceImpl; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/permission/mgt/PermissionManagerServiceTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/permission/mgt/PermissionManagerServiceTest.java index 1c8189374f..5b99437470 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/permission/mgt/PermissionManagerServiceTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/permission/mgt/PermissionManagerServiceTest.java @@ -17,23 +17,23 @@ */ package io.entgra.device.mgt.core.device.mgt.core.permission.mgt; +import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.Permission; +import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException; +import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagerService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.testng.Assert; import org.testng.IObjectFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; -import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.Permission; -import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException; -import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagerService; import org.wso2.carbon.registry.core.exceptions.RegistryException; import java.util.ArrayList; import java.util.List; -import java.util.Properties; import static org.mockito.MockitoAnnotations.initMocks; @@ -41,6 +41,9 @@ import static org.mockito.MockitoAnnotations.initMocks; * This contains unit tests for PermissionManagerService class. */ @PrepareForTest(PermissionUtils.class) +@PowerMockIgnore("org.mockito.*") + +//@PowerMockIgnore({"javax.management.*", "javax.script.*", "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*"}) public class PermissionManagerServiceTest { private static final Log log = LogFactory.getLog(PermissionManagerServiceTest.class);; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/search/ProcessorImplTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/search/ProcessorImplTest.java index 9201787541..1818bd1277 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/search/ProcessorImplTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/search/ProcessorImplTest.java @@ -17,9 +17,6 @@ */ package io.entgra.device.mgt.core.device.mgt.core.search; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.search.Condition; @@ -32,10 +29,12 @@ import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementServic import io.entgra.device.mgt.core.device.mgt.core.search.mgt.InvalidOperatorException; import io.entgra.device.mgt.core.device.mgt.core.search.mgt.SearchMgtException; import io.entgra.device.mgt.core.device.mgt.core.search.mgt.impl.ProcessorImpl; -import io.entgra.device.mgt.core.device.mgt.core.search.util.ChangeEnumValues; import io.entgra.device.mgt.core.device.mgt.core.search.util.Utils; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import java.util.ArrayList; @@ -131,8 +130,6 @@ public class ProcessorImplTest extends BaseDeviceManagementTest { public void testInvalidState() throws SearchMgtException { SearchContext context = new SearchContext(); List conditions = new ArrayList<>(); - ChangeEnumValues.addEnum(Condition.State.class, "BLA"); - Condition.State state = Condition.State.valueOf("BLA"); Condition cond = new Condition(); cond.setKey("batteryLevel"); @@ -152,7 +149,7 @@ public class ProcessorImplTest extends BaseDeviceManagementTest { cond3.setKey("batteryLevel"); cond3.setOperator("="); cond3.setValue("23.0"); - cond3.setState(state); + cond3.setState(Condition.State.AND); conditions.add(cond3); context.setConditions(conditions); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/search/SearchManagementServiceTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/search/SearchManagementServiceTest.java index ba75d0a964..be03fff69f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/search/SearchManagementServiceTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/search/SearchManagementServiceTest.java @@ -17,15 +17,10 @@ */ package io.entgra.device.mgt.core.device.mgt.core.search; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceInfo; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.search.Condition; import io.entgra.device.mgt.core.device.mgt.common.search.SearchContext; import io.entgra.device.mgt.core.device.mgt.core.TestDeviceManagementService; @@ -43,6 +38,11 @@ import io.entgra.device.mgt.core.device.mgt.core.search.mgt.impl.SearchManagerSe import io.entgra.device.mgt.core.device.mgt.core.search.util.Utils; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import java.util.ArrayList; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/search/SearchMgtUtilTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/search/SearchMgtUtilTest.java index 6a88dcc289..c641d2faeb 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/search/SearchMgtUtilTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/search/SearchMgtUtilTest.java @@ -17,13 +17,13 @@ */ package io.entgra.device.mgt.core.device.mgt.core.search; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder; import io.entgra.device.mgt.core.device.mgt.core.search.mgt.impl.Utils; +import org.junit.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import java.util.ArrayList; import java.util.HashMap; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/search/util/ChangeEnumValues.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/search/util/ChangeEnumValues.java deleted file mode 100644 index e5a9d3399e..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/search/util/ChangeEnumValues.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.core.search.util; - -import io.entgra.device.mgt.core.device.mgt.common.search.Condition; -import sun.reflect.ConstructorAccessor; -import sun.reflect.FieldAccessor; -import sun.reflect.ReflectionFactory; - -import java.lang.reflect.AccessibleObject; -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Changes the Enum values of a given class. - */ -public class ChangeEnumValues { - - private static ReflectionFactory reflectionFactory = ReflectionFactory.getReflectionFactory(); - - public ChangeEnumValues() {} - - private static void setFailSafeFieldValue(Field field, Object target, Object value) throws NoSuchFieldException, - IllegalAccessException { - field.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - int modifiers = modifiersField.getInt(field); - modifiers &= ~Modifier.FINAL; - modifiersField.setInt(field, modifiers); - FieldAccessor fa = reflectionFactory.newFieldAccessor(field, false); - fa.set(target, value); - } - - private static void blankField(Class enumClass, String fieldName) throws NoSuchFieldException, - IllegalAccessException { - for (Field field : Class.class.getDeclaredFields()) { - if (field.getName().contains(fieldName)) { - AccessibleObject.setAccessible(new Field[]{field}, true); - setFailSafeFieldValue(field, enumClass, null); - break; - } - } - } - - private static void cleanEnumCache(Class enumClass) throws NoSuchFieldException, IllegalAccessException { - blankField(enumClass, "enumConstantDirectory"); - blankField(enumClass, "enumConstants"); - } - - private static ConstructorAccessor getConstructorAccessor(Class enumClass, Class[] additionalParameterTypes) - throws NoSuchMethodException { - Class[] parameterTypes = new Class[additionalParameterTypes.length + 2]; - parameterTypes[0] = String.class; - parameterTypes[1] = int.class; - System.arraycopy(additionalParameterTypes, 0, parameterTypes, 2, additionalParameterTypes.length); - return reflectionFactory.newConstructorAccessor(enumClass.getDeclaredConstructor(parameterTypes)); - } - - private static Object makeEnum(Class enumClass, String value, int ordinal, Class[] additionalTypes, - Object[] additionalValues) throws Exception { - Object[] parms = new Object[additionalValues.length + 2]; - parms[0] = value; - parms[1] = ordinal; - System.arraycopy(additionalValues, 0, parms, 2, additionalValues.length); - return enumClass.cast(getConstructorAccessor(enumClass, additionalTypes).newInstance(parms)); - } - - /** - * Add an enum instance to the enum class given as argument - * - * @param the type of the enum - * @param enumType the class of the enum to be modified - * @param enumName the name of the new enum instance to be added to the class. - */ - public static > void addEnum(Class enumType, String enumName) { - - if (!Enum.class.isAssignableFrom(enumType)) { - throw new RuntimeException("class " + enumType + " is not an instance of Enum"); - } - - Field valuesField = null; - Field[] fields = Condition.State.class.getDeclaredFields(); - for (Field field : fields) { - if (field.getName().contains("$VALUES")) { - valuesField = field; - break; - } - } - AccessibleObject.setAccessible(new Field[]{valuesField}, true); - - try { - T[] previousValues = (T[]) valuesField.get(enumType); - List values = new ArrayList(Arrays.asList(previousValues)); - T newValue = (T) makeEnum(enumType, enumName, values.size(), new Class[]{}, new Object[]{}); - values.add(newValue); - setFailSafeFieldValue(valuesField, null, values.toArray((T[]) Array.newInstance(enumType, 0))); - cleanEnumCache(enumType); - } catch (Exception e) { - throw new RuntimeException(e.getMessage(), e); - } - } -} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceTest.java index 942cb2c8b0..afa19dc084 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceTest.java @@ -18,6 +18,8 @@ package io.entgra.device.mgt.core.device.mgt.core.service; +import io.entgra.device.mgt.core.device.mgt.common.*; +import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.DeviceStatusManagementService; import io.entgra.device.mgt.core.device.mgt.core.config.ui.UIConfigurationManager; @@ -31,11 +33,7 @@ import org.testng.annotations.Test; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; -import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; -import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; -import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationManagementException; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.License; import io.entgra.device.mgt.core.device.mgt.core.TestDeviceManagementService; import io.entgra.device.mgt.core.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl; @@ -68,12 +66,7 @@ import java.io.File; import java.io.InputStream; import java.lang.reflect.Field; import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Properties; +import java.util.*; public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTest { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceNegativeTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceNegativeTest.java index 5981065e8e..0e514dcfb9 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceNegativeTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceNegativeTest.java @@ -18,8 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.service; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceNotFoundException; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupManagementException; @@ -27,6 +25,8 @@ import io.entgra.device.mgt.core.device.mgt.common.group.mgt.RoleDoesNotExistExc import io.entgra.device.mgt.core.device.mgt.core.TestUtils; import io.entgra.device.mgt.core.device.mgt.core.common.BaseDeviceManagementTest; import io.entgra.device.mgt.core.device.mgt.core.dao.GroupManagementDAOFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import javax.sql.DataSource; import java.util.ArrayList; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceTest.java index cbf4301b14..ab905eea96 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceTest.java @@ -18,27 +18,23 @@ package io.entgra.device.mgt.core.device.mgt.core.service; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceNotFoundException; import io.entgra.device.mgt.core.device.mgt.common.GroupPaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceNotFoundException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupAlreadyExistException; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupManagementException; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupNotExistException; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.RoleDoesNotExistException; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.*; import io.entgra.device.mgt.core.device.mgt.core.TestUtils; import io.entgra.device.mgt.core.device.mgt.core.common.BaseDeviceManagementTest; import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.config.cache.DeviceCacheConfiguration; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService; import org.wso2.carbon.user.api.Permission; import org.wso2.carbon.user.api.UserStoreException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/service/TagManagementProviderServiceTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/service/TagManagementProviderServiceTest.java new file mode 100644 index 0000000000..16277c99a5 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/service/TagManagementProviderServiceTest.java @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.core.service; + +import io.entgra.device.mgt.core.device.mgt.common.exceptions.BadRequestException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.common.tag.mgt.Tag; +import io.entgra.device.mgt.core.device.mgt.common.tag.mgt.TagManagementException; +import io.entgra.device.mgt.core.device.mgt.common.tag.mgt.TagMappingDTO; +import io.entgra.device.mgt.core.device.mgt.common.tag.mgt.TagNotFoundException; +import io.entgra.device.mgt.core.device.mgt.core.TestUtils; +import io.entgra.device.mgt.core.device.mgt.core.common.BaseDeviceManagementTest; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; +import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService; +import org.wso2.carbon.user.core.service.RealmService; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + + +public class TagManagementProviderServiceTest extends BaseDeviceManagementTest { + + private TagManagementProviderService tagManagementProviderService; + + public static final String DEVICE_ID_1 = "100001"; + public static final String DEVICE_ID_2 = "100002"; + private static final String DEVICE_TYPE = "RANDOM_DEVICE_TYPE"; + + @BeforeClass + @Override + public void init() throws Exception { + tagManagementProviderService = new TagManagementProviderServiceImpl(); + RealmService realmService = new InMemoryRealmService(); + DeviceManagementDataHolder.getInstance().setRealmService(realmService); + realmService.getTenantManager().getSuperTenantDomain(); + DeviceConfigurationManager.getInstance().initConfig(); + } + + @Test(expectedExceptions = {TagManagementException.class, BadRequestException.class}) + public void createTagsNull() throws TagManagementException, BadRequestException { + tagManagementProviderService.addTags(null); + } + + @Test(expectedExceptions = {TagManagementException.class, BadRequestException.class}, dependsOnMethods = "createTagsNull") + public void createTagsNameNullError() throws TagManagementException, BadRequestException { + tagManagementProviderService.addTags(TestUtils.createTagList1()); + } + + @Test(dependsOnMethods = "createTagsNameNullError") + public void createTags() throws TagManagementException, BadRequestException { + tagManagementProviderService.addTags(TestUtils.createTagList2()); + } + + @Test(expectedExceptions = {TagNotFoundException.class, BadRequestException.class, TagManagementException.class}) + public void updateTagsNotFound() throws TagNotFoundException, TagManagementException, BadRequestException { + String updateDescString = "This tag is updated"; + tagManagementProviderService.updateTag(new Tag(10,"tag10", updateDescString)); + } + + @Test(dependsOnMethods = "updateTagsNotFound") + public void updateTags() throws TagNotFoundException, TagManagementException, BadRequestException { + String updateDescString = "This tag is updated"; + tagManagementProviderService.updateTag(new Tag(1,"tag1", updateDescString)); + Tag tag = tagManagementProviderService.getTagById(1); + Assert.assertEquals(tag.getDescription(), updateDescString); + } + + @Test(dependsOnMethods = "updateTags", expectedExceptions = {TagNotFoundException.class}) + public void getTagNotFoundById() throws TagManagementException, TagNotFoundException { + tagManagementProviderService.getTagById(10); + } + + @Test(dependsOnMethods = "getTagNotFoundById", expectedExceptions = {BadRequestException.class}) + public void getTagNotFoundByNameNull() throws TagManagementException, TagNotFoundException, BadRequestException { + tagManagementProviderService.getTagByName(null); + } + + @Test(dependsOnMethods = "getTagNotFoundByNameNull", expectedExceptions = {TagNotFoundException.class}) + public void getTagNotFoundByName() throws TagManagementException, TagNotFoundException, BadRequestException { + tagManagementProviderService.getTagByName("tag10"); + } + + @Test(dependsOnMethods = "getTagNotFoundByName") + public void getTagById() throws TagManagementException, TagNotFoundException { + Tag tag = tagManagementProviderService.getTagById(2); + Assert.assertEquals(tag.getName(), TestUtils.getTag2().getName()); + } + + @Test(dependsOnMethods = "getTagById") + public void getTagByName() throws TagManagementException, TagNotFoundException, BadRequestException { + Tag tag = tagManagementProviderService.getTagByName("tag2"); + Assert.assertEquals(tag.getName(), TestUtils.getTag2().getName()); + } + + @Test(dependsOnMethods = "getTagByName") + public void getTags() throws TagManagementException { + List tags = tagManagementProviderService.getAllTags(); + Assert.assertEquals(tags.size(), 3); + } + + @Test(expectedExceptions = {TagNotFoundException.class}, dependsOnMethods = "getTags") + public void deleteTagNotExists() throws TagManagementException, TagNotFoundException { + tagManagementProviderService.deleteTag(10); + } + + @Test(dependsOnMethods = "deleteTagNotExists") + public void deleteTag() throws TagManagementException, TagNotFoundException { + tagManagementProviderService.deleteTag(1); + List tags = tagManagementProviderService.getAllTags(); + Assert.assertEquals(tags.size(), 2); + } + + @Test(expectedExceptions = {BadRequestException.class}, dependsOnMethods = "deleteTag") + public void createTagMappingsNull() throws TagManagementException, BadRequestException { + tagManagementProviderService.addDeviceTagMapping(null, null, null); + } + + @Test(expectedExceptions = {BadRequestException.class}, dependsOnMethods = "createTagMappingsNull") + public void createTagsMappingsNullDeviceIdentifiers() throws TagManagementException, DeviceManagementException { + tagManagementProviderService.addDeviceTagMapping(null, DEVICE_TYPE, + new ArrayList<>(Arrays.asList("tag1", "tag2"))); + } + + @Test(expectedExceptions = {BadRequestException.class}, dependsOnMethods = "createTagsMappingsNullDeviceIdentifiers") + public void createTagsMappingsNullDeviceType() throws TagManagementException, DeviceManagementException { + tagManagementProviderService.addDeviceTagMapping(new ArrayList<>(Arrays.asList(DEVICE_ID_1, DEVICE_ID_2)), + null, new ArrayList<>(Arrays.asList("tag1", "tag2"))); + } + + @Test(expectedExceptions = {BadRequestException.class}, dependsOnMethods = "createTagsMappingsNullDeviceType") + public void createTagsMappingsNullTags() throws TagManagementException, DeviceManagementException { + tagManagementProviderService.addDeviceTagMapping(new ArrayList<>(Arrays.asList(DEVICE_ID_1, DEVICE_ID_2)), + DEVICE_TYPE, null); + } + + @Test(dependsOnMethods = "createTagsMappingsNullTags") + public void createTagsMappings() throws TagManagementException, DeviceManagementException { + tagManagementProviderService.addDeviceTagMapping(new ArrayList<>(Arrays.asList(DEVICE_ID_1, DEVICE_ID_2)), + DEVICE_TYPE, new ArrayList<>(Arrays.asList("tag1", "tag2"))); + } + + @Test(expectedExceptions = {BadRequestException.class}, dependsOnMethods = "createTagsMappings") + public void deleteTagMappingsNull() throws TagManagementException, BadRequestException { + tagManagementProviderService.deleteDeviceTagMapping(null, null, null); + } + + @Test(expectedExceptions = {BadRequestException.class}, dependsOnMethods = "deleteTagMappingsNull") + public void deleteTagsMappingsNullDeviceIdentifiers() throws TagManagementException, DeviceManagementException { + tagManagementProviderService.deleteDeviceTagMapping(null, DEVICE_TYPE, + new ArrayList<>(Arrays.asList("tag1", "tag2"))); + } + + @Test(expectedExceptions = {BadRequestException.class}, dependsOnMethods = "deleteTagsMappingsNullDeviceIdentifiers") + public void deleteTagsMappingsNullDeviceType() throws TagManagementException, DeviceManagementException { + tagManagementProviderService.deleteDeviceTagMapping(new ArrayList<>(Arrays.asList(DEVICE_ID_1, DEVICE_ID_2)), + null, new ArrayList<>(Arrays.asList("tag1", "tag2"))); + } + + @Test(expectedExceptions = {BadRequestException.class}, dependsOnMethods = "deleteTagsMappingsNullDeviceType") + public void deleteTagsMappingsNullTags() throws TagManagementException, DeviceManagementException { + tagManagementProviderService.deleteDeviceTagMapping(new ArrayList<>(Arrays.asList(DEVICE_ID_1, DEVICE_ID_2)), + DEVICE_TYPE, null); + } + + @Test(dependsOnMethods = "deleteTagsMappingsNullTags") + public void deleteTagsMappings() throws TagManagementException, DeviceManagementException { + tagManagementProviderService.deleteDeviceTagMapping(new ArrayList<>(Arrays.asList(DEVICE_ID_1, DEVICE_ID_2)), + DEVICE_TYPE, new ArrayList<>(Arrays.asList("tag1", "tag2"))); + } +} + diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/task/DeviceTaskManagerServiceTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/task/DeviceTaskManagerServiceTest.java index 9bd5beca62..0a1504d952 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/task/DeviceTaskManagerServiceTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/task/DeviceTaskManagerServiceTest.java @@ -17,17 +17,17 @@ */ package io.entgra.device.mgt.core.device.mgt.core.task; +import io.entgra.device.mgt.core.device.mgt.core.TestTaskServiceImpl; +import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; +import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; +import io.entgra.device.mgt.core.device.mgt.core.task.impl.DeviceTaskManagerServiceImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import io.entgra.device.mgt.core.device.mgt.core.TestTaskServiceImpl; -import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder; -import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; -import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; -import io.entgra.device.mgt.core.device.mgt.core.task.impl.DeviceTaskManagerServiceImpl; import org.wso2.carbon.ntask.common.TaskException; import org.wso2.carbon.ntask.core.TaskInfo; import org.wso2.carbon.ntask.core.TaskManager; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/task/DeviceTaskManagerTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/task/DeviceTaskManagerTest.java index e232bffe44..59de82f57b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/task/DeviceTaskManagerTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/task/DeviceTaskManagerTest.java @@ -50,11 +50,7 @@ import io.entgra.device.mgt.core.device.mgt.core.task.impl.DeviceTaskManagerImpl import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; +import java.util.*; /** * This is a test class to test the functionality in {@link DeviceTaskManager}. diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/config/datasource/data-source-config-mock.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/config/datasource/data-source-config-mock.xml index f6031ebc08..35a3fcf16c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/config/datasource/data-source-config-mock.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/config/datasource/data-source-config-mock.xml @@ -18,7 +18,7 @@ --> - jdbc:h2:mem:cdm-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true + jdbc:h2:mem:cdm-test-db;DB_CLOSE_ON_EXIT=FALSE io.entgra.device.mgt.core.device.mgt.core.mock.MockJDBCDriver wso2carbon wso2carbon diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/config/datasource/data-source-config-no-table.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/config/datasource/data-source-config-no-table.xml index b28626efe7..71e35416f3 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/config/datasource/data-source-config-no-table.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/config/datasource/data-source-config-no-table.xml @@ -18,7 +18,7 @@ --> - jdbc:h2:mem:nodb-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true + jdbc:h2:mem:nodb-test-db;DB_CLOSE_ON_EXIT=FALSE org.h2.Driver wso2carbon wso2carbon diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/config/datasource/data-source-config.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/config/datasource/data-source-config.xml index 27b6dfeaeb..533fd82959 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/config/datasource/data-source-config.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/config/datasource/data-source-config.xml @@ -18,7 +18,7 @@ --> - jdbc:h2:mem:cdm-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true + jdbc:h2:mem:cdm-test-db;DB_CLOSE_ON_EXIT=FALSE org.h2.Driver wso2carbon wso2carbon diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/mssql-testng.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/mssql-testng.xml index 2015c5eb5e..51d60a2aee 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/mssql-testng.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/mssql-testng.xml @@ -33,6 +33,7 @@ + diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/mysql-testng.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/mysql-testng.xml index 190802eb51..3959510cbd 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/mysql-testng.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/mysql-testng.xml @@ -33,6 +33,7 @@ + diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/oracle-testng.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/oracle-testng.xml index e4b774a06f..8650e43b96 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/oracle-testng.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/oracle-testng.xml @@ -33,6 +33,7 @@ + diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/postgre-testng.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/postgre-testng.xml index a4839a1a0d..b4bfc29da1 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/postgre-testng.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/postgre-testng.xml @@ -33,6 +33,7 @@ + diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/sql/h2.sql b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/sql/h2.sql index 5f94591885..323f52762a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/sql/h2.sql +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/sql/h2.sql @@ -34,7 +34,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE ( ID INTEGER auto_increment NOT NULL, DESCRIPTION TEXT DEFAULT NULL, NAME VARCHAR(100) DEFAULT NULL, - DEVICE_TYPE_ID INT(11) DEFAULT NULL, + DEVICE_TYPE_ID INT DEFAULT NULL, DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, TENANT_ID INTEGER DEFAULT 0, @@ -243,16 +243,18 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE ( ); CREATE TABLE IF NOT EXISTS DM_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , + ID INT NOT NULL AUTO_INCREMENT , NAME VARCHAR(45) DEFAULT NULL , DESCRIPTION VARCHAR(1000) NULL, - TENANT_ID INT(11) NOT NULL , - PROFILE_ID INT(11) NOT NULL , + PAYLOAD_VERSION VARCHAR (45) NULL, + TENANT_ID INT NOT NULL , + PROFILE_ID INT NOT NULL , OWNERSHIP_TYPE VARCHAR(45) NULL, COMPLIANCE VARCHAR(100) NULL, PRIORITY INT NOT NULL, - ACTIVE INT(2) NOT NULL, - UPDATED INT(1) NULL, + ACTIVE INT NOT NULL, + UPDATED INT NULL, + POLICY_TYPE VARCHAR(45) NULL, PRIMARY KEY (ID) , CONSTRAINT FK_DM_PROFILE_DM_POLICY FOREIGN KEY (PROFILE_ID ) @@ -262,11 +264,11 @@ CREATE TABLE IF NOT EXISTS DM_POLICY ( ); CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , - DEVICE_ID INT(11) NOT NULL , - ENROLMENT_ID INT(11) NOT NULL, + ID INT NOT NULL AUTO_INCREMENT , + DEVICE_ID INT NOT NULL , + ENROLMENT_ID INT NOT NULL, DEVICE BLOB NOT NULL, - POLICY_ID INT(11) NOT NULL , + POLICY_ID INT NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_POLICY_DEVICE_POLICY FOREIGN KEY (POLICY_ID ) @@ -281,9 +283,9 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( ); CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( - ID INT(11) NOT NULL , + ID INT NOT NULL , DEVICE_TYPE VARCHAR(300) NOT NULL , - POLICY_ID INT(11) NOT NULL , + POLICY_ID INT NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_DEVICE_TYPE_POLICY FOREIGN KEY (POLICY_ID ) @@ -293,11 +295,11 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( ); CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( - ID INT(11) NOT NULL AUTO_INCREMENT, - PROFILE_ID INT(11) NOT NULL, + ID INT NOT NULL AUTO_INCREMENT, + PROFILE_ID INT NOT NULL, FEATURE_CODE VARCHAR(100) NOT NULL, DEVICE_TYPE VARCHAR(300) NOT NULL, - TENANT_ID INT(11) NOT NULL , + TENANT_ID INT NOT NULL , CONTENT BLOB NULL DEFAULT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES @@ -308,9 +310,9 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( ); CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , + ID INT NOT NULL AUTO_INCREMENT , ROLE_NAME VARCHAR(45) NOT NULL , - POLICY_ID INT(11) NOT NULL , + POLICY_ID INT NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_ROLE_POLICY_POLICY FOREIGN KEY (POLICY_ID ) @@ -334,11 +336,11 @@ CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( ID INT NOT NULL AUTO_INCREMENT , DEVICE_ID INT NOT NULL , - ENROLMENT_ID INT(11) NOT NULL, + ENROLMENT_ID INT NOT NULL, POLICY_ID INT NOT NULL , POLICY_CONTENT TEXT NULL , TENANT_ID INT NOT NULL, - APPLIED TINYINT(1) NULL , + APPLIED TINYINT NULL , CREATED_TIME TIMESTAMP NULL , UPDATED_TIME TIMESTAMP NULL , APPLIED_TIME TIMESTAMP NULL , @@ -391,7 +393,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES ( CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( ID INT NOT NULL AUTO_INCREMENT, DEVICE_ID INT NOT NULL, - ENROLMENT_ID INT(11) NOT NULL, + ENROLMENT_ID INT NOT NULL, POLICY_ID INT NOT NULL, TENANT_ID INT NOT NULL, STATUS INT NULL, @@ -406,7 +408,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( ID INT NOT NULL AUTO_INCREMENT, POLICY_ID INT NOT NULL, DEVICE_TYPE VARCHAR(300) NOT NULL , - TENANT_ID INT(11) NOT NULL, + TENANT_ID INT NOT NULL, PRIMARY KEY (ID) ); @@ -435,7 +437,7 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION ( LOCATION_URL VARCHAR(100) DEFAULT NULL, IMAGE_URL VARCHAR(100) DEFAULT NULL, APP_PROPERTIES BLOB NULL, - MEMORY_USAGE INTEGER(10) NULL, + MEMORY_USAGE INTEGER NULL, IS_ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, DEVICE_ID INTEGER NOT NULL, ENROLMENT_ID INTEGER NOT NULL, @@ -502,7 +504,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( STATE VARCHAR(45) NULL, COUNTRY VARCHAR(45) NULL, GEO_HASH VARCHAR(45) NULL, - UPDATE_TIMESTAMP BIGINT(15) NOT NULL, + UPDATE_TIMESTAMP BIGINT NOT NULL, PRIMARY KEY (ID), CONSTRAINT DM_DEVICE_LOCATION_DEVICE FOREIGN KEY (DEVICE_ID) @@ -535,8 +537,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( CPU_USAGE DECIMAL(5) NULL, TOTAL_RAM_MEMORY DECIMAL(30,3) NULL, AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL, - PLUGGED_IN INT(1) NULL, - UPDATE_TIMESTAMP BIGINT(15) NOT NULL, + PLUGGED_IN INT NULL, + UPDATE_TIMESTAMP BIGINT NOT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE FOREIGN KEY (DEVICE_ID) @@ -550,24 +552,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( ON UPDATE NO ACTION ); -/* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you 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. - */ - -- POLICY AND DEVICE GROUP MAPPING -- CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY ( ID INT NOT NULL AUTO_INCREMENT, @@ -685,3 +669,25 @@ CREATE TABLE IF NOT EXISTS DM_METADATA ( CONSTRAINT METADATA_KEY_TENANT_ID UNIQUE (METADATA_KEY, TENANT_ID) ); -- END OF METADATA TABLE -- + +-- DM_TAG TABLE -- +CREATE TABLE IF NOT EXISTS DM_TAG ( + ID INTEGER AUTO_INCREMENT, + NAME VARCHAR(255) NOT NULL, + DESCRIPTION VARCHAR(255) NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT DM_TAG_NAME_TENANT_UNIQUE UNIQUE (NAME, TENANT_ID) + ); +-- END OF DM_TAG TABLE -- + +-- DM_DEVICE_TAG_MAPPING TABLE -- +CREATE TABLE IF NOT EXISTS DM_DEVICE_TAG_MAPPING ( + ENROLMENT_ID INTEGER NOT NULL, + TAG_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY (ENROLMENT_ID, TAG_ID, TENANT_ID), + FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT(ID), + FOREIGN KEY (TAG_ID) REFERENCES DM_TAG(ID) ON DELETE CASCADE + ); +-- END OF DM_DEVICE_TAG_MAPPING TABLE -- diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/testng.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/testng.xml index 9e8e787ce0..a51df0bc38 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/testng.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/testng.xml @@ -33,6 +33,7 @@ + @@ -43,6 +44,7 @@ + diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/user-test/user-mgt-registry-test.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/user-test/user-mgt-registry-test.xml index fc32a2698d..96fd6acfff 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/user-test/user-mgt-registry-test.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/user-test/user-mgt-registry-test.xml @@ -27,7 +27,7 @@ everyone false 500 - jdbc:h2:target/databasetest/CARBON_TEST + jdbc:h2:./target/databasetest/CARBON_TEST org.h2.Driver 50 60000 diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/pom.xml index cf44513980..2f7e1c60e4 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/pom.xml @@ -31,9 +31,14 @@ bundle WSO2 Carbon - Device Management Extensions WSO2 Carbon - Device Management Extensions - http://wso2.org + https://entgra.io + + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + org.wso2.carbon.governance org.wso2.carbon.governance.api @@ -61,6 +66,12 @@ org.wso2.carbon org.wso2.carbon.utils + + + org.eclipse.platform + org.eclipse.osgi + + org.wso2.carbon @@ -73,7 +84,7 @@ org.powermock - powermock-api-mockito + powermock-api-mockito2 test @@ -87,8 +98,8 @@ test - com.h2database.wso2 - h2-database-engine + org.wso2.orbit.com.h2database + h2 test @@ -106,10 +117,10 @@ org.wso2.carbon.governance.registry.extensions test - - jaxen - jaxen - + + jaxen + jaxen + @@ -136,14 +147,28 @@ org.apache.sling.testing.osgi-mock test + + org.wso2.orbit.javax.xml.bind + jaxb-api + provided + + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.notification.logger + provided + - - org.apache.felix - maven-scr-plugin - + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + org.apache.felix maven-bundle-plugin @@ -159,34 +184,56 @@ io.entgra.device.mgt.core.device.mgt.extensions.* - org.wso2.carbon.governance.api.*, - javax.xml.namespace;resolution:=optional, - org.wso2.carbon.context, - io.entgra.device.mgt.core.device.mgt.common.*, - org.wso2.carbon.registry.api, - org.wso2.carbon.registry.core, - org.wso2.carbon.registry.core.exceptions, - org.wso2.carbon.registry.core.session, - org.wso2.carbon.base, - javax.xml.bind, - org.apache.commons.logging, - org.wso2.carbon.utils, - javax.naming, - javax.sql, - javax.xml, - javax.xml.bind.annotation, - javax.xml.stream, - javax.xml.parsers;resolution:=optional, - org.apache.commons.lang, + com.google.gson;version="[2.9,3)", + io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.app.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.configuration.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.exceptions;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.general;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.invitation.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.license.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.metadata.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.policy.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.pull.notification;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.push.notification;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.spi;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.type.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.service;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.extensions.device.type.template, + io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config, + io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao, + io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.exception, + io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.feature, + io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.policy.mgt, + io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.pull.notification, + io.entgra.device.mgt.core.device.mgt.extensions.logger;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.extensions.spi, + javax.naming, + javax.sql, + javax.xml.bind;version="[0.0,1)", + javax.xml.bind.annotation;version="[0.0,1)", + javax.xml.namespace, + javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}", + javax.xml.stream;version="[1.0,2)", + org.apache.commons.lang;version="[2.6,3)", + org.apache.commons.logging;version="[1.2,2)", org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.w3c.dom, - org.wso2.carbon.ndatasource.core, - org.wso2.carbon.registry.core.service, - org.wso2.carbon.utils.dbcreator, - org.wso2.carbon.utils.multitenancy, - io.entgra.device.mgt.core.device.mgt.core.service, - com.google.gson + org.w3c.dom, + org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.governance.api.exception;version="[4.8,5)", + org.wso2.carbon.governance.api.generic;version="[4.8,5)", + org.wso2.carbon.governance.api.generic.dataobjects;version="[4.8,5)", + org.wso2.carbon.governance.api.util;version="[4.8,5)", + org.wso2.carbon.ndatasource.core;version="[4.8,5)", + org.wso2.carbon.registry.api;version="[1.0,2)", + org.wso2.carbon.registry.core;version="[1.0,2)", + org.wso2.carbon.registry.core.exceptions;version="[1.0,2)", + org.wso2.carbon.registry.core.service;version="[1.0,2)", + org.wso2.carbon.registry.core.session;version="[1.0,2)", + org.wso2.carbon.utils;version="[4.8,5)", + org.wso2.carbon.utils.dbcreator;version="[4.8,5)" io.entgra.device.mgt.core.device.mgt.extensions.pull.notification, io.entgra.device.mgt.core.device.mgt.extensions.pull.notification.* @@ -228,8 +275,6 @@ - - diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManager.java index 46ee29af59..23fa43739c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManager.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManager.java @@ -17,28 +17,14 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.DeviceManager; -import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; -import io.entgra.device.mgt.core.device.mgt.common.FeatureManager; +import io.entgra.device.mgt.core.device.mgt.common.*; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.License; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.LicenseManagementException; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.LicenseManager; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.DataSource; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.DeviceDetails; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.Feature; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.Properties; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.Table; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.TableConfig; +import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.*; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao.DeviceDAODefinition; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOManager; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.exception.DeviceTypeDeployerPayloadException; @@ -49,6 +35,11 @@ import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.util import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.util.DeviceTypeUtils; import io.entgra.device.mgt.core.device.mgt.extensions.license.mgt.meta.data.MetaRepositoryBasedLicenseManager; import io.entgra.device.mgt.core.device.mgt.extensions.spi.DeviceTypePluginExtensionService; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.registry.api.RegistryException; import org.wso2.carbon.registry.api.Resource; import org.wso2.carbon.utils.CarbonUtils; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerService.java index b357c94cca..eb03f93334 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerService.java @@ -17,11 +17,6 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template; -import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypeMetaDetails; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.DeviceManager; import io.entgra.device.mgt.core.device.mgt.common.DeviceStatusTaskPluginConfig; import io.entgra.device.mgt.core.device.mgt.common.InitialOperationConfig; @@ -29,6 +24,8 @@ import io.entgra.device.mgt.core.device.mgt.common.MonitoringOperation; import io.entgra.device.mgt.core.device.mgt.common.OperationMonitoringTaskConfig; import io.entgra.device.mgt.core.device.mgt.common.ProvisioningConfig; import io.entgra.device.mgt.core.device.mgt.common.StartupOperationConfig; +import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypeMetaDetails; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ApplicationManager; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationEntry; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; @@ -41,17 +38,13 @@ import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotific import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService; import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypePlatformDetails; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.ConfigProperties; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.DeviceStatusTaskConfiguration; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.Feature; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.PolicyMonitoring; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.Property; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.PullNotificationSubscriberConfig; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.PushNotificationProvider; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.TaskConfiguration; +import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.*; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.policy.mgt.DefaultPolicyMonitoringManager; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.pull.notification.PullNotificationSubscriberLoader; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; import java.util.ArrayList; import java.util.HashMap; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypePluginExtensionServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypePluginExtensionServiceImpl.java index 1ca266b733..9fa52f5766 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypePluginExtensionServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypePluginExtensionServiceImpl.java @@ -17,11 +17,11 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOManager; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.exception.DeviceTypePluginExtensionException; import io.entgra.device.mgt.core.device.mgt.extensions.spi.DeviceTypePluginExtensionService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.util.HashMap; import java.util.Map; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/HTTPDeviceTypeManagerService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/HTTPDeviceTypeManagerService.java index e962ce45b9..82ca6b2082 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/HTTPDeviceTypeManagerService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/HTTPDeviceTypeManagerService.java @@ -17,22 +17,13 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Feature; import io.entgra.device.mgt.core.device.mgt.common.InitialOperationConfig; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationConfig; import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypeDefinitionProvider; import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.DeviceDetails; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.Properties; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.Features; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.PolicyMonitoring; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.ProvisioningConfig; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.PushNotificationProvider; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.ConfigProperties; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.Property; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.PullNotificationSubscriberConfig; +import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.*; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.util.ArrayList; import java.util.List; @@ -77,6 +68,9 @@ public class HTTPDeviceTypeManagerService extends DeviceTypeManagerService imple if (feature.getCode() != null && feature.getName() != null) { configFeature.setCode(feature.getCode()); configFeature.setDescription(feature.getDescription()); + if (feature.getTooltip() != null) { + configFeature.setTooltip(feature.getTooltip()); + } configFeature.setName(feature.getName()); if (feature.getMetadataEntries() != null && feature.getMetadataEntries().size() > 0) { List metaValues = new ArrayList<>(); @@ -85,6 +79,29 @@ public class HTTPDeviceTypeManagerService extends DeviceTypeManagerService imple } configFeature.setMetaData(metaValues); } + if (feature.getConfirmationTexts() != null) { + List confirmationTextValues = new ArrayList<>(); + Feature.ConfirmationTexts confirmationText = feature.getConfirmationTexts(); + confirmationTextValues.add(confirmationText.getDeleteConfirmModalTitle()); + confirmationTextValues.add(confirmationText.getDeleteConfirmModalText()); + confirmationTextValues.add(confirmationText.getDeleteConfirmationTextDescribe()); + confirmationTextValues.add(confirmationText.getDeleteConfirmationText()); + confirmationTextValues.add(confirmationText.getCancelText()); + confirmationTextValues.add(confirmationText.getConfirmText()); + confirmationTextValues.add(confirmationText.getInputLabel()); + confirmationTextValues.add(confirmationText.getInputRequireMessage()); + configFeature.setConfirmationTexts(confirmationTextValues); + } + if (feature.getDangerZoneTooltipTexts() != null) { + List dangerZoneTextValues = new ArrayList<>(); + Feature.DangerZoneTooltipTexts dangerZoneText = feature.getDangerZoneTooltipTexts(); + dangerZoneTextValues.add(dangerZoneText.getToolTipTitle()); + dangerZoneTextValues.add(dangerZoneText.getToolTipPopConfirmText()); + dangerZoneTextValues.add(dangerZoneText.getConfirmText()); + dangerZoneTextValues.add(dangerZoneText.getCancelText()); + dangerZoneTextValues.add(dangerZoneText.getToolTipAvailable()); + configFeature.setDangerZoneTooltipTexts(dangerZoneTextValues); + } featureList.add(configFeature); } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Attributes.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Attributes.java index df6f362a32..6357d78862 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Attributes.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Attributes.java @@ -17,12 +17,12 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; -import java.util.ArrayList; -import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; +import java.util.ArrayList; +import java.util.List; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/ConfigProperties.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/ConfigProperties.java index 3c2caa49d8..5d5768e40f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/ConfigProperties.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/ConfigProperties.java @@ -17,12 +17,12 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; -import java.util.ArrayList; -import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; +import java.util.ArrayList; +import java.util.List; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/ConfirmationTexts.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/ConfirmationTexts.java new file mode 100644 index 0000000000..d3bf15f8e6 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/ConfirmationTexts.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; + + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "confirmationTexts", propOrder = { + "deleteConfirmModalTitle", + "deleteConfirmModalText", + "deleteConfirmationTextDescribe", + "deleteConfirmationText", + "cancelText", + "confirmText", + "inputLabel", + "inputRequireMessage" +}) +public class ConfirmationTexts { + + @XmlElement(name = "deleteConfirmModalTitle") + private String deleteConfirmModalTitle; + + @XmlElement(name = "deleteConfirmModalText") + private String deleteConfirmModalText; + + @XmlElement(name = "deleteConfirmationTextDescribe") + private String deleteConfirmationTextDescribe; + + @XmlElement(name = "deleteConfirmationText") + private String deleteConfirmationText; + + @XmlElement(name = "cancelText") + private String cancelText; + + @XmlElement(name = "confirmText") + private String confirmText; + + @XmlElement(name = "inputLabel") + private String inputLabel; + + @XmlElement(name = "inputRequireMessage") + private String inputRequireMessage; + + public String getCancelText() { + return cancelText; + } + + public void setCancelText(String cancelText) { + this.cancelText = cancelText; + } + + public String getInputRequireMessage() { + return inputRequireMessage; + } + + public void setInputRequireMessage(String inputRequireMessage) { + this.inputRequireMessage = inputRequireMessage; + } + + public String getInputLabel() { + return inputLabel; + } + + public void setInputLabel(String inputLabel) { + this.inputLabel = inputLabel; + } + + public String getConfirmText() { + return confirmText; + } + + public void setConfirmText(String confirmText) { + this.confirmText = confirmText; + } + + public String getDeleteConfirmModalTitle() { + return deleteConfirmModalTitle; + } + + public void setDeleteConfirmModalTitle(String deleteConfirmModalTitle) { + this.deleteConfirmModalTitle = deleteConfirmModalTitle; + } + + public String getDeleteConfirmModalText() { + return deleteConfirmModalText; + } + + public void setDeleteConfirmModalText(String deleteConfirmModalText) { + this.deleteConfirmModalText = deleteConfirmModalText; + } + + public String getDeleteConfirmationTextDescribe() { + return deleteConfirmationTextDescribe; + } + + public void setDeleteConfirmationTextDescribe(String deleteConfirmationTextDescribe) { + this.deleteConfirmationTextDescribe = deleteConfirmationTextDescribe; + } + + public String getDeleteConfirmationText() { + return deleteConfirmationText; + } + + public void setDeleteConfirmationText(String deleteConfirmationText) { + this.deleteConfirmationText = deleteConfirmationText; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/DangerZoneTooltipTexts.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/DangerZoneTooltipTexts.java new file mode 100644 index 0000000000..2a38729c99 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/DangerZoneTooltipTexts.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "dangerZoneTooltipTexts", propOrder = { + "toolTipTitle", + "toolTipPopConfirmText", + "confirmText", + "cancelText", + "toolTipAvailable" +}) +public class DangerZoneTooltipTexts { + + @XmlElement(name = "toolTipTitle") + private String toolTipTitle; + + @XmlElement(name = "toolTipPopConfirmText") + private String toolTipPopConfirmText; + + @XmlElement(name = "confirmText") + private String confirmText; + + @XmlElement(name = "cancelText") + private String cancelText; + + @XmlElement(name = "toolTipAvailable") + private String toolTipAvailable; + + public String getToolTipAvailable() { + return toolTipAvailable; + } + + public void setToolTipAvailable(String toolTipAvailable) { + this.toolTipAvailable = toolTipAvailable; + } + + public String getToolTipTitle() { + return toolTipTitle; + } + + public void setToolTipTitle(String toolTipTitle) { + this.toolTipTitle = toolTipTitle; + } + + public String getToolTipPopConfirmText() { + return toolTipPopConfirmText; + } + + public void setToolTipPopConfirmText(String toolTipPopConfirmText) { + this.toolTipPopConfirmText = toolTipPopConfirmText; + } + + public String getConfirmText() { + return confirmText; + } + + public void setConfirmText(String confirmText) { + this.confirmText = confirmText; + } + + public String getCancelText() { + return cancelText; + } + + public void setCancelText(String cancelText) { + this.cancelText = cancelText; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/DataPanel.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/DataPanel.java index 336300b7e6..43f99fba3a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/DataPanel.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/DataPanel.java @@ -18,11 +18,7 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.*; import java.util.List; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/DeviceDetails.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/DeviceDetails.java index 00a999c806..97cb9ded15 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/DeviceDetails.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/DeviceDetails.java @@ -17,11 +17,7 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.*; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/DeviceTypeConfiguration.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/DeviceTypeConfiguration.java index 3d8d95b1bf..b15c2f3c88 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/DeviceTypeConfiguration.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/DeviceTypeConfiguration.java @@ -21,12 +21,7 @@ import io.entgra.device.mgt.core.device.mgt.common.invitation.mgt.DeviceEnrollme import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypeMetaDetails; import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypePlatformDetails; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.*; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Feature.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Feature.java index 28e5e6ddfc..a8c32e621b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Feature.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Feature.java @@ -18,12 +18,7 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.*; import java.util.List; @@ -50,8 +45,11 @@ import java.util.List; @XmlType(name = "Feature", propOrder = { "name", "description", + "tooltip", "operation", - "metaData" + "metaData", + "confirmationTexts", + "dangerZoneTooltipTexts" }) public class Feature { @@ -61,6 +59,9 @@ public class Feature { @XmlElement(name = "Description", required = true) protected String description; + @XmlElement(name = "Tooltip", required = false) + protected String tooltip; + @XmlElement(name = "Operation") protected Operation operation; @@ -74,6 +75,12 @@ public class Feature { @XmlElement(name = "Property", required = true) private List metaData; + @XmlElement(name = "ConfirmationTexts", required = false) + private List confirmationTexts; + + @XmlElement(name = "DangerZoneTooltipTexts", required = false) + private List dangerZoneTooltipTexts; + /** * Gets the value of the name property. * @@ -122,6 +129,31 @@ public class Feature { this.description = value; } + /** + * Gets the value of the tooltip property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getTooltip() { + return tooltip; + } + + /** + * Sets the value of the tooltip property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setTooltip(String value) { + this.tooltip = value; + } + + /** * Gets the value of the operation property. * @@ -185,4 +217,20 @@ public class Feature { public void setType(String type) { this.type = type; } + + public List getConfirmationTexts() { + return confirmationTexts; + } + + public void setConfirmationTexts(List confirmationTexts) { + this.confirmationTexts = confirmationTexts; + } + + public List getDangerZoneTooltipTexts() { + return dangerZoneTooltipTexts; + } + + public void setDangerZoneTooltipTexts(List dangerZoneTooltipTexts) { + this.dangerZoneTooltipTexts = dangerZoneTooltipTexts; + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/InitialOperationConfig.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/InitialOperationConfig.java index 3da81e3bdb..561a47ae90 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/InitialOperationConfig.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/InitialOperationConfig.java @@ -18,7 +18,9 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; -import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; import java.util.List; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Operation.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Operation.java index ce57e7edd9..e7c9275cd5 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Operation.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Operation.java @@ -18,11 +18,7 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.*; /** @@ -45,8 +41,10 @@ import javax.xml.bind.annotation.XmlType; */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Operation", propOrder = { - "params", - "metadata" + "params", + "metadata", + "confirmationTexts", + "tooltipTexts" }) public class Operation { @@ -62,6 +60,28 @@ public class Operation { @XmlAttribute(name = "icon") private String icon; + @XmlElement(name = "tooltipTexts", required = false) + private DangerZoneTooltipTexts tooltipTexts; + + @XmlElement(name = "confirmationTexts", required = false) + private ConfirmationTexts confirmationTexts; + + public DangerZoneTooltipTexts getTooltipTexts() { + return tooltipTexts; + } + + public void setTooltipTexts(DangerZoneTooltipTexts tooltipTexts) { + this.tooltipTexts = tooltipTexts; + } + + public ConfirmationTexts getConfirmationTexts() { + return confirmationTexts; + } + + public void setConfirmationTexts(ConfirmationTexts confirmationTexts) { + this.confirmationTexts = confirmationTexts; + } + public Params getParams() { return params; } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/OperationMetadata.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/OperationMetadata.java index acaa065474..47900f3842 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/OperationMetadata.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/OperationMetadata.java @@ -18,11 +18,7 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.*; import java.util.List; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Option.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Option.java index c8c44263d7..f02ae629ad 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Option.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Option.java @@ -18,7 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; -import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; public class Option { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/OptionalData.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/OptionalData.java index fdaad227e3..7367f26e10 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/OptionalData.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/OptionalData.java @@ -17,7 +17,6 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; -import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Policy.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Policy.java index 73a8c03554..761f452f2e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Policy.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Policy.java @@ -17,12 +17,7 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.*; import java.util.List; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/PolicyMonitoring.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/PolicyMonitoring.java index d307813fc3..64800faf0f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/PolicyMonitoring.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/PolicyMonitoring.java @@ -17,11 +17,7 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.XmlValue; +import javax.xml.bind.annotation.*; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Properties.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Properties.java index eb2566bdc0..50dfafbd9c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Properties.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Properties.java @@ -19,12 +19,12 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; -import java.util.ArrayList; -import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; +import java.util.ArrayList; +import java.util.List; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Property.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Property.java index d8560e4a3c..3f606ac90b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Property.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Property.java @@ -17,11 +17,7 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.XmlValue; +import javax.xml.bind.annotation.*; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/PullNotificationSubscriberConfig.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/PullNotificationSubscriberConfig.java index 5658a7026c..7cd28253d6 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/PullNotificationSubscriberConfig.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/PullNotificationSubscriberConfig.java @@ -17,11 +17,7 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.*; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/PushNotificationProvider.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/PushNotificationProvider.java index 580ba18569..e4f2e944d7 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/PushNotificationProvider.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/PushNotificationProvider.java @@ -17,11 +17,7 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.*; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Table.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Table.java index 6ed1032510..de8a527faa 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Table.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/Table.java @@ -17,11 +17,7 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.*; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/TableConfig.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/TableConfig.java index e24bc2e2a3..e048f4fc9b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/TableConfig.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/TableConfig.java @@ -17,12 +17,12 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; -import java.util.ArrayList; -import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; +import java.util.ArrayList; +import java.util.List; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/UIParameter.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/UIParameter.java index ee7ea78a24..a5978edda9 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/UIParameter.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/UIParameter.java @@ -18,11 +18,7 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.*; import java.util.List; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/DeviceTypeDAOHandler.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/DeviceTypeDAOHandler.java index 9d944a3025..5499a60595 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/DeviceTypeDAOHandler.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/DeviceTypeDAOHandler.java @@ -17,11 +17,11 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.exception.DeviceTypeDeployerPayloadException; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.naming.Context; import javax.naming.InitialContext; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/DeviceTypePluginDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/DeviceTypePluginDAOImpl.java index f7de3a3911..3b3f9ef270 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/DeviceTypePluginDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/DeviceTypePluginDAOImpl.java @@ -18,18 +18,14 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.util.DeviceTypeUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; +import java.sql.*; import java.util.ArrayList; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/DeviceTypePluginDAOManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/DeviceTypePluginDAOManager.java index 19a0af1a4f..0b4a66c402 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/DeviceTypePluginDAOManager.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/DeviceTypePluginDAOManager.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.DeviceDetails; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; public class DeviceTypePluginDAOManager { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/PropertyBasedPluginDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/PropertyBasedPluginDAOImpl.java index 97516dd01e..2e01511746 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/PropertyBasedPluginDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/PropertyBasedPluginDAOImpl.java @@ -18,19 +18,15 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.DeviceDetails; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.util.DeviceTypeUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.Statement; -import java.sql.SQLException; +import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/feature/ConfigurationBasedFeatureManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/feature/ConfigurationBasedFeatureManager.java index bcadc82954..7b6a55e260 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/feature/ConfigurationBasedFeatureManager.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/feature/ConfigurationBasedFeatureManager.java @@ -18,14 +18,14 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.feature; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import org.apache.commons.lang.StringUtils; import io.entgra.device.mgt.core.device.mgt.common.Feature; import io.entgra.device.mgt.core.device.mgt.common.FeatureManager; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.Operation; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.OperationMetadata; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.Params; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.UIParameter; +import org.apache.commons.lang.StringUtils; import java.util.ArrayList; import java.util.HashMap; @@ -60,6 +60,9 @@ public class ConfigurationBasedFeatureManager implements FeatureManager { deviceFeature.setCode(feature.getCode()); deviceFeature.setName(feature.getName()); deviceFeature.setDescription(feature.getDescription()); + if (feature.getTooltip() != null) { + deviceFeature.setTooltip(feature.getTooltip()); + } deviceFeature.setType(feature.getType()); Operation operation = feature.getOperation(); List metadataEntries = null; @@ -113,7 +116,32 @@ public class ConfigurationBasedFeatureManager implements FeatureManager { operationMeta.put(UI_PARAMS, uiParams); operationMeta.put(FORM_PARAMS, formParams); } - + if (operation.getConfirmationTexts() != null) { + Feature.ConfirmationTexts confirmationTexts = new Feature.ConfirmationTexts(); + confirmationTexts.setDeleteConfirmModalTitle( + operation.getConfirmationTexts().getDeleteConfirmModalTitle()); + confirmationTexts.setDeleteConfirmModalText( + operation.getConfirmationTexts().getDeleteConfirmModalText()); + confirmationTexts.setDeleteConfirmationTextDescribe( + operation.getConfirmationTexts().getDeleteConfirmationTextDescribe()); + confirmationTexts.setDeleteConfirmationText( + operation.getConfirmationTexts().getDeleteConfirmationText()); + confirmationTexts.setCancelText(operation.getConfirmationTexts().getCancelText()); + confirmationTexts.setConfirmText(operation.getConfirmationTexts().getConfirmText()); + confirmationTexts.setInputLabel(operation.getConfirmationTexts().getInputLabel()); + confirmationTexts.setInputRequireMessage( + operation.getConfirmationTexts().getInputRequireMessage()); + deviceFeature.setConfirmationTexts(confirmationTexts); + } + if (operation.getTooltipTexts() != null) { + Feature.DangerZoneTooltipTexts tooltipTexts = new Feature.DangerZoneTooltipTexts(); + tooltipTexts.setToolTipTitle(operation.getTooltipTexts().getToolTipTitle()); + tooltipTexts.setToolTipPopConfirmText(operation.getTooltipTexts().getToolTipPopConfirmText()); + tooltipTexts.setConfirmText(operation.getTooltipTexts().getConfirmText()); + tooltipTexts.setCancelText(operation.getTooltipTexts().getCancelText()); + tooltipTexts.setToolTipAvailable(operation.getTooltipTexts().getToolTipAvailable()); + deviceFeature.setDangerZoneTooltipTexts(tooltipTexts); + } if (metadataEntries == null) { metadataEntries = new ArrayList<>(); } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/policy/mgt/DefaultPolicyMonitoringManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/policy/mgt/DefaultPolicyMonitoringManager.java index d43b6e7001..5a399f6fcf 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/policy/mgt/DefaultPolicyMonitoringManager.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/policy/mgt/DefaultPolicyMonitoringManager.java @@ -17,13 +17,13 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.policy.mgt; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.PolicyMonitoringManager; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.ComplianceFeature; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.NonComplianceData; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.util.ArrayList; import java.util.List; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/util/DeviceTypeUtils.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/util/DeviceTypeUtils.java index 4a1cbeaa54..c10d1d083f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/util/DeviceTypeUtils.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/util/DeviceTypeUtils.java @@ -18,14 +18,13 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.util; +import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; +import io.entgra.device.mgt.core.device.mgt.extensions.internal.DeviceTypeExtensionDataHolder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; -import io.entgra.device.mgt.core.device.mgt.extensions.internal.DeviceTypeExtensionDataHolder; import org.wso2.carbon.registry.api.RegistryException; -import org.wso2.carbon.registry.api.RegistryService; import org.wso2.carbon.registry.api.Resource; import org.wso2.carbon.registry.core.Registry; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/internal/DeviceTypeExtensionDataHolder.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/internal/DeviceTypeExtensionDataHolder.java index 0b26765dfc..d0db293991 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/internal/DeviceTypeExtensionDataHolder.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/internal/DeviceTypeExtensionDataHolder.java @@ -17,9 +17,9 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.internal; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.registry.core.service.RegistryService; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/internal/DeviceTypeExtensionServiceComponent.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/internal/DeviceTypeExtensionServiceComponent.java index 222358d1cf..ebe088fd56 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/internal/DeviceTypeExtensionServiceComponent.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/internal/DeviceTypeExtensionServiceComponent.java @@ -18,33 +18,25 @@ package io.entgra.device.mgt.core.device.mgt.extensions.internal; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceTypeGeneratorService; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.DeviceTypeGeneratorServiceImpl; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.DeviceTypePluginExtensionServiceImpl; import io.entgra.device.mgt.core.device.mgt.extensions.spi.DeviceTypePluginExtensionService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.registry.core.service.RegistryService; -/** - * @scr.component name="io.entgra.device.mgt.core.device.mgt.extensions.DeviceTypeExtensionServiceComponent" - * immediate="true" - * @scr.reference name="registry.service" - * interface="org.wso2.carbon.registry.core.service.RegistryService" cardinality="0..1" - * policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService" - * @scr.reference name="org.wso2.carbon.ndatasource" - * interface="org.wso2.carbon.ndatasource.core.DataSourceService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDataSourceService" - * unbind="unsetDataSourceService" - */ +@Component( + name = "io.entgra.device.mgt.core.device.mgt.extensions.internal.DeviceTypeExtensionServiceComponent", + immediate = true) public class DeviceTypeExtensionServiceComponent { private static final Log log = LogFactory.getLog(DeviceTypeExtensionServiceComponent.class); + @Activate protected void activate(ComponentContext ctx) { try { if (log.isDebugEnabled()) { @@ -61,13 +53,19 @@ public class DeviceTypeExtensionServiceComponent { log.error("Error occurred while initializing device type extension component ", e); } } - + @Deactivate protected void deactivate(ComponentContext ctx) { if (log.isDebugEnabled()) { log.debug("De-activating DeviceType Deployer Service Component"); } } + @Reference( + name = "registry.service", + service = org.wso2.carbon.registry.core.service.RegistryService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRegistryService") protected void setRegistryService(RegistryService registryService) { if (log.isDebugEnabled()) { log.debug("RegistryService acquired"); @@ -79,6 +77,12 @@ public class DeviceTypeExtensionServiceComponent { DeviceTypeExtensionDataHolder.getInstance().setRegistryService(null); } + @Reference( + name = "datasource.service", + service = org.wso2.carbon.ndatasource.core.DataSourceService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDataSourceService") protected void setDataSourceService(DataSourceService dataSourceService) { /* This is to avoid device management component getting initialized before the underlying datasources are registered */ diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/license/mgt/meta/data/MetaRepositoryBasedLicenseManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/license/mgt/meta/data/MetaRepositoryBasedLicenseManager.java index 06e5b58461..c38701e111 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/license/mgt/meta/data/MetaRepositoryBasedLicenseManager.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/license/mgt/meta/data/MetaRepositoryBasedLicenseManager.java @@ -19,10 +19,6 @@ package io.entgra.device.mgt.core.device.mgt.extensions.license.mgt.meta.data; import com.google.gson.Gson; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataKeyAlreadyExistsException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; @@ -34,6 +30,10 @@ import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManageme import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.util.DeviceTypePluginConstants; import io.entgra.device.mgt.core.device.mgt.extensions.internal.DeviceTypeExtensionDataHolder; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; public class MetaRepositoryBasedLicenseManager implements LicenseManager { @@ -107,13 +107,13 @@ public class MetaRepositoryBasedLicenseManager implements LicenseManager { } else { metadataManagementService.createMetadata(metadata); } - } catch (MetadataManagementException e) { - String msg = "Error occurred while saving the licence value in meta data repository"; + } catch (MetadataKeyAlreadyExistsException e) { + String msg = "Error occurred while saving the licence key and licence key exist.Licence Key: " + + licenceKey; log.error(msg, e); throw new LicenseManagementException(msg, e); - } catch (MetadataKeyAlreadyExistsException e) { - String msg = - "Error occurred while saving the licence key and licence key exist. Licence Key: " + licenceKey; + } catch (MetadataManagementException e) { + String msg = "Error occurred while saving the licence value in meta data repository"; log.error(msg, e); throw new LicenseManagementException(msg, e); } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/license/mgt/registry/GenericArtifactManagerFactory.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/license/mgt/registry/GenericArtifactManagerFactory.java index 0065d89d8b..5201e1b169 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/license/mgt/registry/GenericArtifactManagerFactory.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/license/mgt/registry/GenericArtifactManagerFactory.java @@ -17,9 +17,9 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.license.mgt.registry; -import org.wso2.carbon.context.CarbonContext; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.LicenseManagementException; +import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.governance.api.generic.GenericArtifactManager; import org.wso2.carbon.governance.api.util.GovernanceUtils; import org.wso2.carbon.registry.api.Registry; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/license/mgt/registry/RegistryBasedLicenseManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/license/mgt/registry/RegistryBasedLicenseManager.java index df032f2818..57440bbdff 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/license/mgt/registry/RegistryBasedLicenseManager.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/license/mgt/registry/RegistryBasedLicenseManager.java @@ -18,14 +18,14 @@ package io.entgra.device.mgt.core.device.mgt.extensions.license.mgt.registry; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.RegistryType; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.License; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.LicenseManagementException; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.LicenseManager; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.RegistryType; import org.wso2.carbon.governance.api.exception.GovernanceException; import org.wso2.carbon.governance.api.generic.GenericArtifactFilter; import org.wso2.carbon.governance.api.generic.GenericArtifactManager; @@ -33,7 +33,6 @@ import org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact; import org.wso2.carbon.registry.api.Registry; import javax.xml.namespace.QName; -import java.lang.String; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/BaseExtensionsTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/BaseExtensionsTest.java index 992969aa92..cc0c9b0d8d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/BaseExtensionsTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/BaseExtensionsTest.java @@ -18,32 +18,28 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template; -import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; -import org.apache.tomcat.jdbc.pool.PoolProperties; -import org.mockito.Mockito; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Optional; -import org.testng.annotations.Parameters; -import org.w3c.dom.Document; -import org.wso2.carbon.CarbonConstants; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.context.RegistryType; -import org.wso2.carbon.context.internal.OSGiDataHolder; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.license.mgt.License; -import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.MetadataManagementServiceImpl; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory; +import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; import io.entgra.device.mgt.core.device.mgt.extensions.common.DataSourceConfig; import io.entgra.device.mgt.core.device.mgt.extensions.internal.DeviceTypeExtensionDataHolder; -import io.entgra.device.mgt.core.device.mgt.extensions.license.mgt.meta.data.MetaRepositoryBasedLicenseManager; import io.entgra.device.mgt.core.device.mgt.extensions.mock.TypeXDeviceManagementService; import io.entgra.device.mgt.core.device.mgt.extensions.utils.Utils; +import org.apache.tomcat.jdbc.pool.PoolProperties; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Optional; +import org.testng.annotations.Parameters; +import org.w3c.dom.Document; +import org.wso2.carbon.CarbonConstants; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.context.RegistryType; +import org.wso2.carbon.context.internal.OSGiDataHolder; import org.wso2.carbon.governance.api.util.GovernanceArtifactConfiguration; import org.wso2.carbon.governance.api.util.GovernanceUtils; import org.wso2.carbon.registry.core.Registry; @@ -62,7 +58,6 @@ import java.sql.Statement; import java.util.ArrayList; import java.util.List; -import static org.mockito.Matchers.anyString; import static org.wso2.carbon.governance.api.util.GovernanceUtils.getGovernanceArtifactConfiguration; /** diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerNegativeTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerNegativeTest.java index 6c239cef50..74b1cc1d44 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerNegativeTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerNegativeTest.java @@ -18,11 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template; -import org.h2.jdbcx.JdbcDataSource; -import org.mockito.Mockito; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.base.MultitenantConstants; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; @@ -32,14 +27,15 @@ import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.conf import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.Properties; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.exception.DeviceTypeConfigurationException; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao.DeviceDAODefinition; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao.DeviceTypeDAOHandler; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOImpl; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOManager; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao.PropertyBasedPluginDAOImpl; +import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao.*; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.exception.DeviceTypeDeployerPayloadException; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; import io.entgra.device.mgt.core.device.mgt.extensions.utils.Utils; +import org.h2.jdbcx.JdbcDataSource; +import org.mockito.Mockito; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.base.MultitenantConstants; import org.xml.sax.SAXException; import javax.xml.bind.JAXBException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerServiceTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerServiceTest.java index eb59f2e2fb..dcf3dd26bd 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerServiceTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerServiceTest.java @@ -18,29 +18,24 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.base.MultitenantConstants; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.DeviceStatusTaskPluginConfig; import io.entgra.device.mgt.core.device.mgt.common.InitialOperationConfig; import io.entgra.device.mgt.core.device.mgt.common.OperationMonitoringTaskConfig; import io.entgra.device.mgt.core.device.mgt.common.ProvisioningConfig; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationEntry; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.License; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.LicenseManagementException; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationConfig; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.DeviceStatusTaskConfiguration; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.PolicyMonitoring; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.PullNotificationSubscriberConfig; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.PushNotificationProvider; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.TaskConfiguration; +import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.*; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.exception.DeviceTypeConfigurationException; import io.entgra.device.mgt.core.device.mgt.extensions.utils.Utils; +import org.mockito.Mockito; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.xml.sax.SAXException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerTest.java index 7b3d624180..395cd1c7d8 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerTest.java @@ -18,25 +18,20 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.DeviceDetails; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.Properties; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.exception.DeviceTypeConfigurationException; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao.DeviceDAODefinition; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao.DeviceTypeDAOHandler; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOImpl; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOManager; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao.PluginDAO; -import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao.PropertyBasedPluginDAOImpl; +import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao.*; import io.entgra.device.mgt.core.device.mgt.extensions.utils.Utils; +import org.mockito.Mockito; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.xml.sax.SAXException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest.java index 9a6a8b44ac..1fd84a5e14 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest.java @@ -18,14 +18,11 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationEntry; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.License; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationConfig; import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService; @@ -35,6 +32,9 @@ import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.conf import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.PushNotificationProvider; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.exception.DeviceTypeConfigurationException; import io.entgra.device.mgt.core.device.mgt.extensions.utils.Utils; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.xml.sax.SAXException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/DeviceDAODefinitionNegativeTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/DeviceDAODefinitionNegativeTest.java index 2666233222..20e14e7102 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/DeviceDAODefinitionNegativeTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/dao/DeviceDAODefinitionNegativeTest.java @@ -18,9 +18,9 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao; -import org.testng.annotations.Test; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.Table; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.exception.DeviceTypeDeployerPayloadException; +import org.testng.annotations.Test; /** * This class tests the negative scenarios related with {@link DeviceDAODefinition} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/mock/TypeXDeviceManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/mock/TypeXDeviceManagementService.java index 3591d9caa8..5a81a5be18 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/mock/TypeXDeviceManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/mock/TypeXDeviceManagementService.java @@ -17,15 +17,9 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.mock; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.DeviceManager; -import io.entgra.device.mgt.core.device.mgt.common.DeviceStatusTaskPluginConfig; -import io.entgra.device.mgt.core.device.mgt.common.InitialOperationConfig; -import io.entgra.device.mgt.core.device.mgt.common.MonitoringOperation; -import io.entgra.device.mgt.core.device.mgt.common.OperationMonitoringTaskConfig; -import io.entgra.device.mgt.core.device.mgt.common.ProvisioningConfig; -import io.entgra.device.mgt.core.device.mgt.common.StartupOperationConfig; +import io.entgra.device.mgt.core.device.mgt.common.*; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ApplicationManager; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.general.GeneralConfig; import io.entgra.device.mgt.core.device.mgt.common.invitation.mgt.DeviceEnrollmentInvitationDetails; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.License; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/mock/TypeXDeviceManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/mock/TypeXDeviceManager.java index fc8afc602e..341daa1d3d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/mock/TypeXDeviceManager.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/mock/TypeXDeviceManager.java @@ -17,11 +17,7 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.mock; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.DeviceManager; -import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; -import io.entgra.device.mgt.core.device.mgt.common.FeatureManager; +import io.entgra.device.mgt.core.device.mgt.common.*; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.License; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/utils/Utils.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/utils/Utils.java index 9676b6bfb5..4a38a1a4c0 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/utils/Utils.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/utils/Utils.java @@ -18,14 +18,14 @@ package io.entgra.device.mgt.core.device.mgt.extensions.utils; -import org.h2.jdbcx.JdbcDataSource; -import org.w3c.dom.Document; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.DeviceDetails; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.Table; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.exception.DeviceTypeConfigurationException; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.dao.DeviceDAODefinition; +import org.h2.jdbcx.JdbcDataSource; +import org.w3c.dom.Document; import org.wso2.carbon.registry.core.config.RegistryContext; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.internal.RegistryDataHolder; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/utils/UtilsTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/utils/UtilsTest.java index 29d752316a..862b73cb9c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/utils/UtilsTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/utils/UtilsTest.java @@ -18,11 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.extensions.utils; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.License; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.LicenseManagementException; @@ -37,6 +32,11 @@ import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.util import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.util.DeviceTypeUtils; import io.entgra.device.mgt.core.device.mgt.extensions.license.mgt.file.FileSystemBasedLicenseManager; import io.entgra.device.mgt.core.device.mgt.extensions.license.mgt.registry.RegistryBasedLicenseManager; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.io.File; import java.lang.reflect.InvocationTargetException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/carbon-home/dbscripts/h2.sql b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/carbon-home/dbscripts/h2.sql index 2f96eeba79..620b98e321 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/carbon-home/dbscripts/h2.sql +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/carbon-home/dbscripts/h2.sql @@ -16,24 +16,6 @@ * under the License. */ -/* - * Copyright (c) 2021, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you 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. - */ - CREATE TABLE IF NOT EXISTS REG_CLUSTER_LOCK ( REG_LOCK_NAME VARCHAR (20), REG_LOCK_STATUS VARCHAR (20), diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/carbon-home/repository/conf/datasource/data-source-config.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/carbon-home/repository/conf/datasource/data-source-config.xml index 27b6dfeaeb..533fd82959 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/carbon-home/repository/conf/datasource/data-source-config.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/carbon-home/repository/conf/datasource/data-source-config.xml @@ -18,7 +18,7 @@ --> - jdbc:h2:mem:cdm-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true + jdbc:h2:mem:cdm-test-db;DB_CLOSE_ON_EXIT=FALSE org.h2.Driver wso2carbon wso2carbon diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/sql-files/h2.sql b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/sql-files/h2.sql index ed810f8308..24953ff026 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/sql-files/h2.sql +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/sql-files/h2.sql @@ -31,7 +31,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE ( ID INTEGER auto_increment NOT NULL, DESCRIPTION TEXT DEFAULT NULL, NAME VARCHAR(100) DEFAULT NULL, - DEVICE_TYPE_ID INT(11) DEFAULT NULL, + DEVICE_TYPE_ID INT DEFAULT NULL, DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, TENANT_ID INTEGER DEFAULT 0, @@ -149,16 +149,16 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE ( ); CREATE TABLE IF NOT EXISTS DM_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , + ID INT NOT NULL AUTO_INCREMENT , NAME VARCHAR(45) DEFAULT NULL , DESCRIPTION VARCHAR(1000) NULL, - TENANT_ID INT(11) NOT NULL , - PROFILE_ID INT(11) NOT NULL , + TENANT_ID INT NOT NULL , + PROFILE_ID INT NOT NULL , OWNERSHIP_TYPE VARCHAR(45) NULL, COMPLIANCE VARCHAR(100) NULL, PRIORITY INT NOT NULL, - ACTIVE INT(2) NOT NULL, - UPDATED INT(1) NULL, + ACTIVE INT NOT NULL, + UPDATED INT NULL, PRIMARY KEY (ID) , CONSTRAINT FK_DM_PROFILE_DM_POLICY FOREIGN KEY (PROFILE_ID ) @@ -168,11 +168,11 @@ CREATE TABLE IF NOT EXISTS DM_POLICY ( ); CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , - DEVICE_ID INT(11) NOT NULL , - ENROLMENT_ID INT(11) NOT NULL, + ID INT NOT NULL AUTO_INCREMENT , + DEVICE_ID INT NOT NULL , + ENROLMENT_ID INT NOT NULL, DEVICE BLOB NOT NULL, - POLICY_ID INT(11) NOT NULL , + POLICY_ID INT NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_POLICY_DEVICE_POLICY FOREIGN KEY (POLICY_ID ) @@ -187,9 +187,9 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( ); CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( - ID INT(11) NOT NULL , + ID INT NOT NULL , DEVICE_TYPE VARCHAR(300) NOT NULL , - POLICY_ID INT(11) NOT NULL , + POLICY_ID INT NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_DEVICE_TYPE_POLICY FOREIGN KEY (POLICY_ID ) @@ -199,11 +199,11 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( ); CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( - ID INT(11) NOT NULL AUTO_INCREMENT, - PROFILE_ID INT(11) NOT NULL, + ID INT NOT NULL AUTO_INCREMENT, + PROFILE_ID INT NOT NULL, FEATURE_CODE VARCHAR(100) NOT NULL, DEVICE_TYPE VARCHAR(300) NOT NULL, - TENANT_ID INT(11) NOT NULL , + TENANT_ID INT NOT NULL , CONTENT BLOB NULL DEFAULT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES @@ -214,9 +214,9 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( ); CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , + ID INT NOT NULL AUTO_INCREMENT , ROLE_NAME VARCHAR(45) NOT NULL , - POLICY_ID INT(11) NOT NULL , + POLICY_ID INT NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_ROLE_POLICY_POLICY FOREIGN KEY (POLICY_ID ) @@ -240,11 +240,11 @@ CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( ID INT NOT NULL AUTO_INCREMENT , DEVICE_ID INT NOT NULL , - ENROLMENT_ID INT(11) NOT NULL, + ENROLMENT_ID INT NOT NULL, POLICY_ID INT NOT NULL , POLICY_CONTENT TEXT NULL , TENANT_ID INT NOT NULL, - APPLIED TINYINT(1) NULL , + APPLIED TINYINT NULL , CREATED_TIME TIMESTAMP NULL , UPDATED_TIME TIMESTAMP NULL , APPLIED_TIME TIMESTAMP NULL , @@ -297,7 +297,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES ( CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( ID INT NOT NULL AUTO_INCREMENT, DEVICE_ID INT NOT NULL, - ENROLMENT_ID INT(11) NOT NULL, + ENROLMENT_ID INT NOT NULL, POLICY_ID INT NOT NULL, TENANT_ID INT NOT NULL, STATUS INT NULL, @@ -312,7 +312,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( ID INT NOT NULL AUTO_INCREMENT, POLICY_ID INT NOT NULL, DEVICE_TYPE VARCHAR(300) NOT NULL , - TENANT_ID INT(11) NOT NULL, + TENANT_ID INT NOT NULL, PRIMARY KEY (ID) ); @@ -341,10 +341,22 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION ( LOCATION_URL VARCHAR(100) DEFAULT NULL, IMAGE_URL VARCHAR(100) DEFAULT NULL, APP_PROPERTIES BLOB NULL, - MEMORY_USAGE INTEGER(10) NULL, + MEMORY_USAGE INTEGER NULL, IS_ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, + DEVICE_ID INTEGER NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (ID) + PRIMARY KEY (ID), + CONSTRAINT fk_dm_device + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT fk_dm_enrolement + FOREIGN KEY (ENROLMENT_ID) + REFERENCES DM_ENROLMENT (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATION_MAPPING ( @@ -352,34 +364,15 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATION_MAPPING ( DEVICE_ID INTEGER NOT NULL, APPLICATION_ID INTEGER NOT NULL, APP_PROPERTIES BLOB NULL, - MEMORY_USAGE INTEGER(10) NULL, + MEMORY_USAGE INTEGER NULL, IS_ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID), - CONSTRAINT fk_dm_device FOREIGN KEY (DEVICE_ID) REFERENCES + CONSTRAINT fk_dm_device_tb FOREIGN KEY (DEVICE_ID) REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT fk_dm_application FOREIGN KEY (APPLICATION_ID) REFERENCES DM_APPLICATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); - -/* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you 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. - */ - -- POLICY RELATED TABLES FINISHED -- -- NOTIFICATION TABLE -- @@ -423,7 +416,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( STATE VARCHAR(45) NULL, COUNTRY VARCHAR(45) NULL, GEO_HASH VARCHAR(45) NULL, - UPDATE_TIMESTAMP BIGINT(15) NOT NULL, + UPDATE_TIMESTAMP BIGINT NOT NULL, PRIMARY KEY (ID), CONSTRAINT DM_DEVICE_LOCATION_DEVICE FOREIGN KEY (DEVICE_ID) @@ -435,6 +428,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( ID INT NOT NULL AUTO_INCREMENT, DEVICE_ID INT NOT NULL, + ENROLMENT_ID INT NOT NULL, DEVICE_MODEL VARCHAR(45) NULL, VENDOR VARCHAR(45) NULL, OS_VERSION VARCHAR(45) NULL, @@ -449,13 +443,18 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( CPU_USAGE DECIMAL(5) NULL, TOTAL_RAM_MEMORY DECIMAL(30,3) NULL, AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL, - PLUGGED_IN INT(1) NULL, - UPDATE_TIMESTAMP BIGINT(15) NOT NULL, + PLUGGED_IN INT NULL, + UPDATE_TIMESTAMP BIGINT NOT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE FOREIGN KEY (DEVICE_ID) REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT FK_DM_ENROLMENT_DEVICE_DETAILS + FOREIGN KEY (ENROLMENT_ID) + REFERENCES DM_ENROLMENT (ID) + ON DELETE NO ACTION ON UPDATE NO ACTION ); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/user-test/user-mgt-registry-test.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/user-test/user-mgt-registry-test.xml index 1ced8bb1f1..4d53df601c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/user-test/user-mgt-registry-test.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/user-test/user-mgt-registry-test.xml @@ -27,7 +27,7 @@ everyone false 500 - jdbc:h2:target/databasetest/CARBON_TEST + jdbc:h2:./target/databasetest/CARBON_TEST org.h2.Driver 50 60000 diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/pom.xml index 8dbc6d726e..0fc65c8a5d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/pom.xml @@ -32,26 +32,21 @@ bundle WSO2 Carbon - Device Management url printer WSO2 Carbon - Device Management url printer - http://wso2.org + https://entgra.io - org.apache.felix - maven-scr-plugin - - + org.apache.maven.plugins maven-compiler-plugin 1.8 1.8 - 2.3.2 org.apache.felix maven-bundle-plugin - 1.4.0 true @@ -61,12 +56,12 @@ IoT Server Impl Bundle io.entgra.device.mgt.core.device.mgt.url.printer.internal + org.apache.axis2.context;version="[1.6,2)", + org.apache.commons.logging;version="[1.2,2)", org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.apache.commons.logging, - org.apache.axis2.*;version="${axis2.osgi.version.range}", - org.wso2.carbon.core, - org.wso2.carbon.utils.*, + org.wso2.carbon.core;version="[4.8,5)", + org.wso2.carbon.utils;version="[4.8,5)" !io.entgra.device.mgt.core.device.mgt.url.printer.internal, @@ -106,20 +101,18 @@ - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services + org.apache.felix + org.apache.felix.scr.ds-annotations + provided org.wso2.carbon org.wso2.carbon.core - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api + provided org.wso2.carbon diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/src/main/java/io/entgra/device/mgt/core/device/mgt/url/printer/URLPrinterStartupHandler.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/src/main/java/io/entgra/device/mgt/core/device/mgt/url/printer/URLPrinterStartupHandler.java index 85ced7b90e..bab23693fd 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/src/main/java/io/entgra/device/mgt/core/device/mgt/url/printer/URLPrinterStartupHandler.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/src/main/java/io/entgra/device/mgt/core/device/mgt/url/printer/URLPrinterStartupHandler.java @@ -18,10 +18,10 @@ package io.entgra.device.mgt.core.device.mgt.url.printer; +import io.entgra.device.mgt.core.device.mgt.url.printer.internal.UrlPrinterDataHolder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.core.ServerStartupObserver; -import io.entgra.device.mgt.core.device.mgt.url.printer.internal.UrlPrinterDataHolder; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.NetworkUtils; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/src/main/java/io/entgra/device/mgt/core/device/mgt/url/printer/internal/UrlPrinterServiceComponent.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/src/main/java/io/entgra/device/mgt/core/device/mgt/url/printer/internal/UrlPrinterServiceComponent.java index b346b2cc5a..3f301fc4aa 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/src/main/java/io/entgra/device/mgt/core/device/mgt/url/printer/internal/UrlPrinterServiceComponent.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/src/main/java/io/entgra/device/mgt/core/device/mgt/url/printer/internal/UrlPrinterServiceComponent.java @@ -18,28 +18,23 @@ package io.entgra.device.mgt.core.device.mgt.url.printer.internal; +import io.entgra.device.mgt.core.device.mgt.url.printer.URLPrinterStartupHandler; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.core.ServerStartupObserver; -import io.entgra.device.mgt.core.device.mgt.url.printer.URLPrinterStartupHandler; import org.wso2.carbon.utils.ConfigurationContextService; -/** - * @scr.component name="UrlPrinterServiceComponent" - * immediate="true" - * @scr.reference name="config.context.service" - * interface="org.wso2.carbon.utils.ConfigurationContextService" - * cardinality="0..1" - * policy="dynamic" - * bind="setConfigurationContextService" - * unbind="unsetConfigurationContextService" - */ +@Component( + name = "io.entgra.device.mgt.core.device.mgt.url.printer.internal.UrlPrinterServiceComponent", + immediate = true) public class UrlPrinterServiceComponent { private static final Log log = LogFactory.getLog(UrlPrinterServiceComponent.class); + @Activate protected void activate(ComponentContext ctx) { if (log.isDebugEnabled()) { log.debug("Activating Url printer Service Component"); @@ -54,13 +49,19 @@ public class UrlPrinterServiceComponent { log.error("Error occurred while activating Url printer Service Component", e); } } - + @Deactivate protected void deactivate(ComponentContext ctx) { if (log.isDebugEnabled()) { log.debug("De-activating Url printer Service Component"); } } + @Reference( + name = "configuration.context.service", + service = org.wso2.carbon.utils.ConfigurationContextService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetConfigurationContextService") protected void setConfigurationContextService(ConfigurationContextService configurationContextService) { if (log.isDebugEnabled()) { log.debug("Setting ConfigurationContextService"); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/pom.xml deleted file mode 100644 index 3ac62b9500..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/pom.xml +++ /dev/null @@ -1,165 +0,0 @@ - - - - - - - io.entgra.device.mgt.core - device-mgt - 5.0.0-SNAPSHOT - ../pom.xml - - - 4.0.0 - org.wso2.carbon.device.mgt.analytics.data.publisher - bundle - WSO2 Carbon - Device Analytics - WSO2 Carbon - Device Analytics - http://wso2.org - - - - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services - - - org.testng - testng - - - org.wso2.tomcat - tomcat - - - org.wso2.tomcat - tomcat-servlet-api - - - org.wso2.carbon - org.wso2.carbon.core - - - org.wso2.carbon - org.wso2.carbon.logging - - - org.wso2.carbon - org.wso2.carbon.utils - - - org.wso2.carbon.analytics-common - org.wso2.carbon.databridge.agent - - - org.wso2.carbon.analytics-common - org.wso2.carbon.databridge.commons - - - org.wso2.carbon - org.wso2.carbon.securevault - - - org.apache.sling - org.apache.sling.testing.osgi-mock - - - - - - - org.apache.felix - maven-scr-plugin - - - org.apache.felix - maven-bundle-plugin - 1.4.0 - true - - - ${project.artifactId} - ${project.artifactId} - ${io.entgra.device.mgt.core.version} - Data Publisher - org.wso2.carbon.device.mgt.analytics.data.publisher.internal - - !org.wso2.carbon.device.mgt.analytics.data.publisher.internal, - org.wso2.carbon.device.mgt.analytics.data.publisher.*;version="${io.entgra.device.mgt.core.version}" - - - org.osgi.framework.*;version="${imp.package.version.osgi.framework}", - org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.apache.commons.logging.*, - org.wso2.carbon.utils.multitenancy, - org.wso2.carbon.context;version="${carbon.kernel.version.range}", - org.wso2.carbon.utils;version="${carbon.kernel.version.range}", - org.wso2.carbon.databridge.*;version="${carbon.analytics.common.version.range}", - org.json;version="${commons-json.version}", - javax.xml.*, - javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, - org.w3c.dom, - org.wso2.carbon.base, - org.wso2.carbon.utils.multitenancy - - - - - - org.jacoco - jacoco-maven-plugin - - ${basedir}/target/coverage-reports/jacoco-unit.exec - - - - jacoco-initialize - - prepare-agent - - - - jacoco-site - test - - report - - - ${basedir}/target/coverage-reports/jacoco-unit.exec - ${basedir}/target/coverage-reports/site - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - src/test/resources/testng.xml - - - - - - - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherUtil.java deleted file mode 100644 index 1d65b3092e..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherUtil.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.analytics.data.publisher; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.wso2.carbon.databridge.agent.exception.DataEndpointConfigurationException; -import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; - -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import java.io.File; -import java.util.ArrayList; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class DataPublisherUtil { - - private static final Log log = LogFactory.getLog(DataPublisherUtil.class); - - private DataPublisherUtil(){ - } - - public static Document convertToDocument(File file) throws DataPublisherConfigurationException { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - try { - factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - DocumentBuilder docBuilder = factory.newDocumentBuilder(); - return docBuilder.parse(file); - } catch (Exception e) { - throw new DataPublisherConfigurationException("Error occurred while parsing file, while converting " + - "to a org.w3c.dom.Document", e); - } - } - - public static ArrayList getEndpointGroups(String urlSet) { - ArrayList urlGroups = new ArrayList<>(); - Pattern regex = Pattern.compile("\\{.*?\\}"); - Matcher regexMatcher = regex.matcher(urlSet); - - while(regexMatcher.find()) { - urlGroups.add(regexMatcher.group().replace("{", "").replace("}", "")); - } - - if (urlGroups.size() == 0) { - urlGroups.add(urlSet.replace("{", "").replace("}", "")); - } - return urlGroups; - } - - public static String[] getEndpoints(String aURLGroup) throws DataEndpointConfigurationException { - boolean isLBURL = false; - boolean isFailOverURL = false; - if (aURLGroup.contains(",")) { - isLBURL = true; - } - - if (aURLGroup.contains("|")) { - isFailOverURL = true; - } - - if (isLBURL && isFailOverURL) { - String msg = "Invalid data endpoints URL set provided : " + aURLGroup + - ", a URL group can be configured as failover OR load balancing endpoints."; - log.error(msg); - throw new DataEndpointConfigurationException(msg); - } else { - String[] urls; - if (isLBURL) { - urls = aURLGroup.split(","); - } else if (isFailOverURL) { - urls = aURLGroup.split("\\|"); - } else { - urls = new String[]{aURLGroup}; - } - return urls; - } - } - - public static int obtainHashId(String deviceId, int urlGroupsCount) { - byte[] chars = deviceId.getBytes(); - int sum = 0; - for (byte b : chars) { - sum += b; - } - return sum % urlGroupsCount; - } - - @SuppressWarnings("Duplicates") - public static String replaceProperty(String urlWithPlaceholders) { - String regex = "\\$\\{(.*?)\\}"; - Pattern pattern = Pattern.compile(regex); - Matcher matchPattern = pattern.matcher(urlWithPlaceholders); - while (matchPattern.find()) { - String sysPropertyName = matchPattern.group(1); - String sysPropertyValue = System.getProperty(sysPropertyName); - if (sysPropertyValue != null && !sysPropertyName.isEmpty()) { - urlWithPlaceholders = urlWithPlaceholders.replaceAll("\\$\\{(" + sysPropertyName + ")\\}", sysPropertyValue); - } - } - return urlWithPlaceholders; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DeviceDataPublisher.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DeviceDataPublisher.java deleted file mode 100644 index 18d5be4287..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DeviceDataPublisher.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.analytics.data.publisher; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.databridge.agent.DataPublisher; -import org.wso2.carbon.databridge.agent.exception.DataEndpointAgentConfigurationException; -import org.wso2.carbon.databridge.agent.exception.DataEndpointAuthenticationException; -import org.wso2.carbon.databridge.agent.exception.DataEndpointConfigurationException; -import org.wso2.carbon.databridge.agent.exception.DataEndpointException; -import org.wso2.carbon.databridge.commons.exception.TransportException; -import org.wso2.carbon.device.mgt.analytics.data.publisher.config.AnalyticsConfiguration; -import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; -import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherServiceImpl; - -import java.util.HashMap; -import java.util.Map; - -/** - * This is used to manage data publisher per tenant. - */ -public class DeviceDataPublisher { - - private static Log log = LogFactory.getLog(EventsPublisherServiceImpl.class); - - private Map dataPublishers; - private static DeviceDataPublisher deviceDataPublisher; - - private DeviceDataPublisher() { - dataPublishers = new HashMap<>(); - } - - public static DeviceDataPublisher getInstance() { - if (deviceDataPublisher == null) { - synchronized (DeviceDataPublisher.class) { - if (deviceDataPublisher == null) { - deviceDataPublisher = new DeviceDataPublisher(); - } - } - } - return deviceDataPublisher; - } - - /** - * This returns the data publisher for the tenant based on the analytics node id. - * - * @param analyticsConfig Analytics configurations - * @param receiverURLSet Data receiver URL set as string - * @return instance of data publisher - * @throws DataPublisherConfigurationException on exception - */ - public DataPublisher getDataPublisher(AnalyticsConfiguration analyticsConfig, String receiverURLSet) - throws DataPublisherConfigurationException { - synchronized (this) { - if (this.dataPublishers.containsKey(receiverURLSet)) { - return this.dataPublishers.get(receiverURLSet); - } else { - String analyticsServerUrlGroups = analyticsConfig.getReceiverServerUrl(); - String analyticsServerUsername = analyticsConfig.getAdminUsername(); - String analyticsServerPassword = analyticsConfig.getAdminPassword(); - - try { - DataPublisher dataPublisher = new DataPublisher(receiverURLSet, analyticsServerUsername, - analyticsServerPassword); - this.dataPublishers.put(receiverURLSet, dataPublisher); - return dataPublisher; - } catch (DataEndpointAgentConfigurationException e) { - String msg = "Configuration Exception on data publisher for " + - "ReceiverGroup = " + analyticsServerUrlGroups + " for username " + analyticsServerUsername; - log.error(msg, e); - throw new DataPublisherConfigurationException(msg, e); - } catch (DataEndpointException e) { - String msg = "Invalid ReceiverGroup = " + analyticsServerUrlGroups; - log.error(msg, e); - throw new DataPublisherConfigurationException(msg, e); - } catch (DataEndpointConfigurationException e) { - String msg = "Invalid Data endpoint configuration."; - log.error(msg, e); - throw new DataPublisherConfigurationException(msg, e); - } catch (DataEndpointAuthenticationException e) { - String msg = "Authentication Failed for user " + analyticsServerUsername; - log.error(msg, e); - throw new DataPublisherConfigurationException(msg, e); - } catch (TransportException e) { - String msg = "Error occurred while retrieving data publisher"; - log.error(msg, e); - throw new DataPublisherConfigurationException(msg, e); - } - } - } - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/config/AnalyticsConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/config/AnalyticsConfiguration.java deleted file mode 100644 index 67a8c36333..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/config/AnalyticsConfiguration.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.analytics.data.publisher.config; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.wso2.carbon.device.mgt.analytics.data.publisher.DataPublisherUtil; -import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; -import org.wso2.carbon.utils.CarbonUtils; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import java.io.File; - -/** - * Configurations related to DAS data publisher and DAL. - */ -@XmlRootElement(name = "AnalyticsConfiguration") -public class AnalyticsConfiguration { - - private String receiverServerUrl; - private String analyticsPublisherUrl; - private String adminUsername; - private String adminPassword; - private boolean enable; - - private static AnalyticsConfiguration config; - - private static final Log log = LogFactory.getLog(AnalyticsConfiguration.class); - private static final String DEVICE_ANALYTICS_CONFIG_PATH = - CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "device-analytics-config.xml"; - - private AnalyticsConfiguration() { - } - - public static AnalyticsConfiguration getInstance() { - if (config == null) { - throw new InvalidConfigurationStateException("Device analytics configuration is not " + - "initialized properly"); - } - return config; - } - - - @XmlElement(name = "AdminUsername", required = true) - public String getAdminUsername() { - return adminUsername; - } - - public void setAdminUsername(String adminUsername) { - this.adminUsername = adminUsername; - } - - @XmlElement(name = "AdminPassword", required = true) - public String getAdminPassword() { - return adminPassword; - } - - public void setAdminPassword(String adminPassword) { - this.adminPassword = adminPassword; - } - - @XmlElement(name = "ReceiverServerUrl", required = true) - public String getReceiverServerUrl() { - return DataPublisherUtil.replaceProperty(receiverServerUrl); - } - - public void setReceiverServerUrl(String receiverServerUrl) { - this.receiverServerUrl = receiverServerUrl; - } - - @XmlElement(name = "AnalyticsPublisherUrl", required = true) - public String getAnalyticsPublisherUrl() { - return DataPublisherUtil.replaceProperty(analyticsPublisherUrl); - } - - public void setAnalyticsPublisherUrl(String analyticsPublisherUrl) { - this.analyticsPublisherUrl = analyticsPublisherUrl; - } - - @XmlElement(name = "Enabled", required = true) - public boolean isEnable() { - return enable; - } - - public void setEnable(boolean status) { - this.enable = status; - } - - public static void init() throws DataPublisherConfigurationException { - init(AnalyticsConfiguration.DEVICE_ANALYTICS_CONFIG_PATH); - } - - public static void init(String analyticsConfigPath) throws DataPublisherConfigurationException { - File authConfig = new File(analyticsConfigPath); - if (!authConfig.exists()) { - log.warn(DEVICE_ANALYTICS_CONFIG_PATH + " does not exist. Disabling AnalyticsConfiguration."); - config = new AnalyticsConfiguration(); - config.setEnable(false); - return; - } - try { - Document doc = DataPublisherUtil.convertToDocument(authConfig); - - /* Un-marshaling device analytics configuration */ - JAXBContext ctx = JAXBContext.newInstance(AnalyticsConfiguration.class); - Unmarshaller unmarshaller = ctx.createUnmarshaller(); - config = (AnalyticsConfiguration) unmarshaller.unmarshal(doc); - } catch (JAXBException e) { - throw new DataPublisherConfigurationException("Error occurred while un-marshalling device analytics " + - "Config", e); - } - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/config/InvalidConfigurationStateException.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/config/InvalidConfigurationStateException.java deleted file mode 100644 index b9686bac42..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/config/InvalidConfigurationStateException.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.analytics.data.publisher.config; - -public class InvalidConfigurationStateException extends RuntimeException { - - private static final long serialVersionUID = -3151274311329070297L; - - public InvalidConfigurationStateException(String message) { - super(message); - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/exception/DataPublisherConfigurationException.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/exception/DataPublisherConfigurationException.java deleted file mode 100644 index ea93c62a31..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/exception/DataPublisherConfigurationException.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.analytics.data.publisher.exception; - -public class DataPublisherConfigurationException extends Exception { - - public DataPublisherConfigurationException(String message) { - super(message); - } - - public DataPublisherConfigurationException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/internal/DataPublisherServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/internal/DataPublisherServiceComponent.java deleted file mode 100644 index fe2cad0ea1..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/internal/DataPublisherServiceComponent.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.analytics.data.publisher.internal; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; -import org.osgi.service.component.ComponentContext; -import org.wso2.carbon.device.mgt.analytics.data.publisher.config.AnalyticsConfiguration; -import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; -import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherServiceImpl; - -/** - * @scr.component name="org.wso2.carbon.device.mgt.analytics.data.publisher.internal.DataPublisherServiceComponent" - * immediate="true" - */ -public class DataPublisherServiceComponent { - - private ServiceRegistration analyticsServiceRef; - private static Log log = LogFactory.getLog(DataPublisherServiceComponent.class); - - protected void activate(ComponentContext componentCtx) { - try { - if (log.isDebugEnabled()) { - log.debug("Initializing device analytics bundle"); - } - AnalyticsConfiguration.init(); - BundleContext bundleCtx = componentCtx.getBundleContext(); - this.analyticsServiceRef = - bundleCtx.registerService(EventsPublisherService.class, new EventsPublisherServiceImpl(), null); - if (log.isDebugEnabled()) { - log.debug("Device management analytics bundle has been successfully initialized"); - } - } catch (Throwable e) { - log.error("Error occurred while initializing device analytics bundle", e); - } - } - - protected void deactivate(ComponentContext componentCtx) { - if (log.isDebugEnabled()) { - log.debug("Deactivating device analytics bundle"); - } - if (analyticsServiceRef != null) { - analyticsServiceRef.unregister(); - } - if (log.isDebugEnabled()) { - log.debug("Device analytics bundle has been successfully deactivated"); - } - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/service/EventsPublisherService.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/service/EventsPublisherService.java deleted file mode 100644 index f75496d0e2..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/service/EventsPublisherService.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.analytics.data.publisher.service; - -import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; - -/** - * This service can be used to publish and retrieve data from the Analytics Server. - */ -public interface EventsPublisherService { - - /** - * This is used to publish an event to DAS. - * @param streamName is the name of the stream that the data needs to pushed - * @param version is the version of the stream - * @param metaDataArray - meta data that needs to pushed - * @param correlationDataArray - correlation data that needs to be pushed - * @param payloadDataArray - payload data that needs to be pushed - * @return if success returns true - * @throws DataPublisherConfigurationException on exception - */ - boolean publishEvent(String streamName, String version, Object[] metaDataArray, Object[] correlationDataArray, - Object[] payloadDataArray) throws DataPublisherConfigurationException; - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/service/EventsPublisherServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/service/EventsPublisherServiceImpl.java deleted file mode 100644 index 6b7b81aa36..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/service/EventsPublisherServiceImpl.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.analytics.data.publisher.service; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.databridge.agent.DataPublisher; -import org.wso2.carbon.databridge.commons.utils.DataBridgeCommonsUtils; -import org.wso2.carbon.device.mgt.analytics.data.publisher.DataPublisherUtil; -import org.wso2.carbon.device.mgt.analytics.data.publisher.DeviceDataPublisher; -import org.wso2.carbon.device.mgt.analytics.data.publisher.config.AnalyticsConfiguration; -import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; - -import java.util.ArrayList; - -/** - * This is the implementation of Osgi Service which can be used to publish and retireved - * event/records. - */ -public class EventsPublisherServiceImpl implements EventsPublisherService { - - private static Log log = LogFactory.getLog(EventsPublisherServiceImpl.class); - - /** - * @param streamName is the name of the stream that the data needs to pushed - * @param version is the version of the stream - * @param metaDataArray meta data that needs to pushed - * @param correlationDataArray correlation data that needs to be pushed - * @param payloadDataArray payload data that needs to be pushed - * @return if success returns true - * @throws DataPublisherConfigurationException on exception - */ - @Override - public boolean publishEvent(String streamName, String version, Object[] metaDataArray, - Object[] correlationDataArray, - Object[] payloadDataArray) throws DataPublisherConfigurationException { - AnalyticsConfiguration analyticsConfig = AnalyticsConfiguration.getInstance(); - if (!analyticsConfig.isEnable()) { - log.warn("Analytics data publishing not enabled."); - return false; - } - - if (metaDataArray == null || metaDataArray.length == 0) { - String msg = "meta data[0] must have the device Id field"; - log.error(msg); - throw new DataPublisherConfigurationException(msg); - } - - ArrayList receiverURLGroups = DataPublisherUtil.getEndpointGroups(analyticsConfig.getReceiverServerUrl()); - int hashId = DataPublisherUtil.obtainHashId(metaDataArray[0].toString(), receiverURLGroups.size()); - if (receiverURLGroups.size() <= hashId) { - String msg = "Invalid receiver url group size. Expected to be higher than: " + hashId + " Actual: " + - receiverURLGroups.size(); - log.error(msg); - throw new DataPublisherConfigurationException(msg); - } - - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { - metaDataArray[0] = tenantDomain + "@" + metaDataArray[0]; - } - - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext() - .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); - try { - DataPublisher dataPublisher = DeviceDataPublisher.getInstance() - .getDataPublisher(analyticsConfig, receiverURLGroups.get(hashId)); - if (dataPublisher != null) { - String streamId = DataBridgeCommonsUtils.generateStreamId(streamName, version); - return dataPublisher.tryPublish(streamId, System.currentTimeMillis(), metaDataArray, - correlationDataArray, - payloadDataArray); - } else { - return false; - } - } finally { - PrivilegedCarbonContext.endTenantFlow(); - } - } -} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/BaseAnalyticsDataPublisherTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/BaseAnalyticsDataPublisherTest.java deleted file mode 100644 index 3d42a3020b..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/BaseAnalyticsDataPublisherTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* -* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.analytics.data.publisher; - -import org.testng.annotations.BeforeSuite; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.context.PrivilegedCarbonContext; - -import java.io.File; - -public class BaseAnalyticsDataPublisherTest { - - @BeforeSuite - public void init() { - setUpCarbonHome(); - } - - private void setUpCarbonHome() { - if (System.getProperty("carbon.home") == null) { - File file = new File("src/test/resources/carbon-home"); - if (file.exists()) { - System.setProperty("carbon.home", file.getAbsolutePath()); - } - file = new File("carbon-home"); - if (file.exists()) { - System.setProperty("carbon.home", file.getAbsolutePath()); - } - file = new File("../../resources/carbon-home"); - if (file.exists()) { - System.setProperty("carbon.home", file.getAbsolutePath()); - } - file = new File("../../../resources/carbon-home"); - if (file.exists()) { - System.setProperty("carbon.home", file.getAbsolutePath()); - } - } - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants - .SUPER_TENANT_DOMAIN_NAME); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID); - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherConfigTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherConfigTest.java deleted file mode 100644 index 0e04de8a56..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherConfigTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* -* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.analytics.data.publisher; - -import junit.framework.Assert; -import org.testng.annotations.Test; -import org.wso2.carbon.device.mgt.analytics.data.publisher.config.AnalyticsConfiguration; -import org.wso2.carbon.device.mgt.analytics.data.publisher.config.InvalidConfigurationStateException; -import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; - -import java.io.File; -import java.lang.reflect.Field; -import java.net.URL; - -/** - * This test class will validate the Data publisher configuration creation. - */ -public class DataPublisherConfigTest extends BaseAnalyticsDataPublisherTest { - - @Test(description = "Validating the behaviour of getInstance config before calling the init", - expectedExceptions = InvalidConfigurationStateException.class) - public void testGetInstanceWithoutInit() throws NoSuchFieldException, IllegalAccessException { - Field configField = AnalyticsConfiguration.class.getDeclaredField("config"); - configField.setAccessible(true); - configField.set(configField, null); - AnalyticsConfiguration.getInstance(); - } - - @Test(description = "Analytics configuration initialization with invalid config", - expectedExceptions = DataPublisherConfigurationException.class, - dependsOnMethods = "testGetInstanceWithoutInit") - public void testInitWithInvalidConfig() throws DataPublisherConfigurationException { - ClassLoader classLoader = this.getClass().getClassLoader(); - URL invalidConfig = classLoader.getResource("carbon-home/repository/conf/etc/" + - "device-analytics-config-invalid.xml"); - Assert.assertTrue("No configuration - device-analytics-config-invalid.xml found in resource dir", - invalidConfig != null); - File file = new File(invalidConfig.getFile()); - AnalyticsConfiguration.init(file.getAbsolutePath()); - } - - - @Test(description = "Analytics config initialization with invalid xml", - expectedExceptions = DataPublisherConfigurationException.class, - dependsOnMethods = "testInitWithInvalidConfig") - public void testInitWithInvalidXML() throws DataPublisherConfigurationException { - ClassLoader classLoader = this.getClass().getClassLoader(); - URL invalidConfig = classLoader.getResource("carbon-home/repository/conf/etc/" + - "device-analytics-config-invalid-xml.xml"); - Assert.assertTrue("No configuration - device-analytics-config-invalid-xml.xml found in resource dir", - invalidConfig != null); - File file = new File(invalidConfig.getFile()); - AnalyticsConfiguration.init(file.getAbsolutePath()); - } - - - @Test(description = "Validating the init method with all required params", - dependsOnMethods = "testInitWithInvalidXML") - public void testInitWithValidConfig() throws DataPublisherConfigurationException { - AnalyticsConfiguration.init(); - AnalyticsConfiguration analyticsConfiguration = AnalyticsConfiguration.getInstance(); - Assert.assertEquals(analyticsConfiguration.getAdminPassword(), "testuserpwd"); - Assert.assertEquals(analyticsConfiguration.getAdminUsername(), "testuser"); - Assert.assertEquals(analyticsConfiguration.getReceiverServerUrl(), "tcp://localhost:7615"); - Assert.assertTrue(analyticsConfiguration.isEnable()); - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherServiceComponentTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherServiceComponentTest.java deleted file mode 100644 index d5ffb75d48..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherServiceComponentTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* -* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.analytics.data.publisher; - - -import org.apache.sling.testing.mock.osgi.MockOsgi; -import org.osgi.service.component.ComponentContext; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.device.mgt.analytics.data.publisher.internal.DataPublisherServiceComponent; -import org.wso2.carbon.device.mgt.analytics.data.publisher.util.TestComponentContext; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * This tesclass will be validating the behaviour of {@link DataPublisherServiceComponent} - */ -public class DataPublisherServiceComponentTest extends BaseAnalyticsDataPublisherTest { - private DataPublisherServiceComponent serviceComponent; - - @BeforeClass - public void initTest() { - this.serviceComponent = new DataPublisherServiceComponent(); - } - - @Test (description = "Test bundle activation with exception thrown when service resgistration") - public void activateWithException() throws NoSuchMethodException, IllegalAccessException, - InvocationTargetException { - this.activate(new TestComponentContext()); - } - - @Test(dependsOnMethods = "activateWithException", description = "Test the bundle activation with succesful path") - public void activateWithoutException() throws NoSuchMethodException, InvocationTargetException, - IllegalAccessException { - this.activate(MockOsgi.newComponentContext()); - } - - @Test(dependsOnMethods = "activateWithoutException", description = "Test bundle deactivation") - public void deActivate() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { - Method method = this.serviceComponent.getClass().getDeclaredMethod("deactivate", ComponentContext.class); - method.setAccessible(true); - method.invoke(this.serviceComponent, MockOsgi.newComponentContext()); - } - - private void activate(ComponentContext componentContext) throws NoSuchMethodException, InvocationTargetException, - IllegalAccessException { - Method method = this.serviceComponent.getClass().getDeclaredMethod("activate", ComponentContext.class); - method.setAccessible(true); - method.invoke(this.serviceComponent, componentContext); - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/EventPublisherServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/EventPublisherServiceTest.java deleted file mode 100644 index a7e5e8083d..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/EventPublisherServiceTest.java +++ /dev/null @@ -1,144 +0,0 @@ -/* -* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.analytics.data.publisher; - -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.databridge.agent.AgentHolder; -import org.wso2.carbon.databridge.agent.exception.DataEndpointAgentConfigurationException; -import org.wso2.carbon.device.mgt.analytics.data.publisher.config.AnalyticsConfiguration; -import org.wso2.carbon.device.mgt.analytics.data.publisher.config.InvalidConfigurationStateException; -import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; -import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; -import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherServiceImpl; - -import java.lang.reflect.Field; - -/** - * This test class will test the methods that are exposed from {@link EventsPublisherService} - */ -public class EventPublisherServiceTest extends BaseAnalyticsDataPublisherTest { - - private static final String STREAM_NAME = "org.wso2.test.stream"; - private static final String TENANT_DOMAIN = "test.com"; - - private EventsPublisherService eventsPublisherService; - - @BeforeClass - public void initTest() { - this.eventsPublisherService = new EventsPublisherServiceImpl(); - } - - @Test(description = "Publish the event before initializing", - expectedExceptions = InvalidConfigurationStateException.class) - public void publishBeforeInit() throws DataPublisherConfigurationException, NoSuchFieldException, - IllegalAccessException, InstantiationException { - Field configField = AnalyticsConfiguration.class.getDeclaredField("config"); - configField.setAccessible(true); - configField.set(configField, null); - this.eventsPublisherService.publishEvent(STREAM_NAME, "1.0.0", getEventProps(), getEventProps(), - getEventProps()); - } - - @Test(description = "Publish with analytics config disabled", dependsOnMethods = "publishBeforeInit") - public void publishWhenAnalyticsConfigDisabled() throws DataPublisherConfigurationException { - AnalyticsConfiguration.init(); - AnalyticsConfiguration.getInstance().setEnable(false); - boolean published = this.eventsPublisherService.publishEvent(STREAM_NAME, "1.0.0", getEventProps(), - getEventProps(), getEventProps()); - Assert.assertFalse(published); - } - - @Test(description = "Publish the event after initializing", dependsOnMethods = "publishWhenAnalyticsConfigDisabled") - public void publishAfterInit() throws DataPublisherConfigurationException { - AnalyticsConfiguration.getInstance().setEnable(true); - boolean published = this.eventsPublisherService.publishEvent(STREAM_NAME, "1.0.0", getEventProps(), - getEventProps(), getEventProps()); - Assert.assertTrue(published); - } - - @Test(description = "Publish as tenant", dependsOnMethods = "publishAfterInit") - public void publishAsTenant() throws DataPublisherConfigurationException { - publishAsTenant(getEventProps()); - } - - @Test(description = "Publish the with no meta data as tenant", dependsOnMethods = "publishAsTenant", - expectedExceptions = DataPublisherConfigurationException.class) - public void publishAsTenantWithNoMetaData() throws DataPublisherConfigurationException { - publishAsTenant(null); - } - - @Test(description = "Publish the with empty meta data as tenant", dependsOnMethods = "publishAsTenant", - expectedExceptions = DataPublisherConfigurationException.class) - public void publishAsTenantWithEmptyMetaData() throws DataPublisherConfigurationException { - publishAsTenant(new Object[0]); - } - - @Test(description = "Publishing with invalid data publisher config", - dependsOnMethods = {"publishAsTenantWithEmptyMetaData", "publishAsTenantWithNoMetaData"}, - expectedExceptions = DataPublisherConfigurationException.class) - public void publishWithDataEndpointConfigException() throws DataPublisherConfigurationException, - NoSuchFieldException, IllegalAccessException { - AnalyticsConfiguration analyticsConfiguration = AnalyticsConfiguration.getInstance(); - analyticsConfiguration.setReceiverServerUrl(""); - Field dataPublisherField = DeviceDataPublisher.class.getDeclaredField("deviceDataPublisher"); - dataPublisherField.setAccessible(true); - dataPublisherField.set(dataPublisherField, null); - publishAsTenant(getEventProps()); - } - - @Test(description = "Publishing with invalid data publisher config", - dependsOnMethods = "publishWithDataEndpointConfigException", - expectedExceptions = DataPublisherConfigurationException.class) - public void publishWithDataAgentConfigException() throws DataPublisherConfigurationException, - NoSuchFieldException, IllegalAccessException, DataEndpointAgentConfigurationException { - AnalyticsConfiguration.init(); - Field defaultAgentName = AgentHolder.getInstance().getClass().getDeclaredField("defaultDataEndpointAgentName"); - defaultAgentName.setAccessible(true); - defaultAgentName.set(AgentHolder.getInstance(), "dummyAgent"); - publishAsTenant(getEventProps()); - } - - @Test(description = "Publishing with invalid data publisher config", - dependsOnMethods = "publishWithDataAgentConfigException") - public void publishWithDataEndpointException() throws DataPublisherConfigurationException, - NoSuchFieldException, IllegalAccessException, DataEndpointAgentConfigurationException { - AnalyticsConfiguration.init(); - - } - - private void publishAsTenant(Object[] metaData) throws DataPublisherConfigurationException { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(TENANT_DOMAIN, true); - try { - boolean published = this.eventsPublisherService.publishEvent(STREAM_NAME, "1.0.0", metaData, - getEventProps(), getEventProps()); - Assert.assertTrue(published); - } finally { - PrivilegedCarbonContext.endTenantFlow(); - } - } - - private Object[] getEventProps() { - return new Object[]{"123"}; - } - - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/util/TestComponentContext.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/util/TestComponentContext.java deleted file mode 100644 index adcb3cba2f..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/util/TestComponentContext.java +++ /dev/null @@ -1,81 +0,0 @@ -/* -* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.analytics.data.publisher.util; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.osgi.service.component.ComponentContext; -import org.osgi.service.component.ComponentInstance; - -import java.util.Dictionary; - -/** - * Mock implementation for component context. - */ -public class TestComponentContext implements ComponentContext { - @Override - public Dictionary getProperties() { - return null; - } - - @Override - public Object locateService(String s) { - return null; - } - - @Override - public Object locateService(String s, ServiceReference serviceReference) { - return null; - } - - @Override - public Object[] locateServices(String s) { - return new Object[0]; - } - - @Override - public BundleContext getBundleContext() { - return null; - } - - @Override - public Bundle getUsingBundle() { - return null; - } - - @Override - public ComponentInstance getComponentInstance() { - return null; - } - - @Override - public void enableComponent(String s) { - - } - - @Override - public void disableComponent(String s) { - - } - - @Override - public ServiceReference getServiceReference() { - return null; - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/carbon.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/carbon.xml deleted file mode 100644 index a5518cb720..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/carbon.xml +++ /dev/null @@ -1,658 +0,0 @@ - - - - - - - - - ${product.name} - - - ${product.key} - - - ${product.version} - - - - - - - - - local:/${carbon.context}/services/ - - - - - - - ${default.server.role} - - - - - - - org.wso2.carbon - - - / - - - - - - - - - 15 - - - - - - - - - 0 - - - - - 9999 - - 11111 - - - - - - 10389 - - 8000 - - - - - - 10500 - - - - - - - org.wso2.carbon.tomcat.jndi.CarbonJavaURLContextFactory - - - - - - - - - java - - - - - - - - - - false - - - false - - - 600 - - - - false - - - - - - - - 30 - - - - - - - - - 15 - - - - - - ${carbon.home}/repository/deployment/server/ - - - 15 - - - ${carbon.home}/repository/conf/axis2/axis2.xml - - - 30000 - - - ${carbon.home}/repository/deployment/client/ - - ${carbon.home}/repository/conf/axis2/axis2_client.xml - - true - - - - - - - - - - admin - Default Administrator Role - - - user - Default User Role - - - - - - - - - - - - ${carbon.home}/repository/resources/security/wso2carbon.jks - - JKS - - wso2carbon - - wso2carbon - - wso2carbon - - - - - - ${carbon.home}/repository/resources/security/client-truststore.jks - - JKS - - wso2carbon - - - - - - - - - - - - - - - - - - - UserManager - - - false - - - - - - - ${carbon.home}/tmp/work - - - - - - true - - - 10 - - - 30 - - - - - - 100 - - - - keystore - certificate - * - - org.wso2.carbon.ui.transports.fileupload.AnyFileUploadExecutor - - - - - jarZip - - org.wso2.carbon.ui.transports.fileupload.JarZipUploadExecutor - - - - dbs - - org.wso2.carbon.ui.transports.fileupload.DBSFileUploadExecutor - - - - tools - - org.wso2.carbon.ui.transports.fileupload.ToolsFileUploadExecutor - - - - toolsAny - - org.wso2.carbon.ui.transports.fileupload.ToolsAnyFileUploadExecutor - - - - - - - info - org.wso2.carbon.core.transports.util.InfoProcessor - - - wsdl - org.wso2.carbon.core.transports.util.Wsdl11Processor - - - wsdl2 - org.wso2.carbon.core.transports.util.Wsdl20Processor - - - xsd - org.wso2.carbon.core.transports.util.XsdProcessor - - - - - - false - false - true - svn - http://svnrepo.example.com/repos/ - username - password - true - - - - - - - - - - - - - - - ${require.carbon.servlet} - - - - - true - - - - - - - default repository - ${p2.repo.url} - - - - - - - - true - - - - - - true - - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/data-bridge/data-agent-config-invalid.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/data-bridge/data-agent-config-invalid.xml deleted file mode 100644 index a399556257..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/data-bridge/data-agent-config-invalid.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - Thrift - org.wso2.carbon.databridge.agent.endpoint.thrift.ThriftDataEndpointNoClass - src/test/resources/client-truststore.jks - wso2carbon - 32768 - 200 - 1 - 30000 - 1 - 20 - 30 - 250 - 250 - 5500 - 5000 - 250 - 250 - 5500 - 5000 - - - - - - Binary - org.wso2.carbon.databridge.agent.endpoint.binary.BinaryDataEndpoint - src/test/resources/client-truststore.jks - wso2carbon - 32768 - 200 - 1 - 1 - 30000 - 20 - 30 - 250 - 250 - 5500 - 5000 - 250 - 250 - 5500 - 5000 - - - - - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/data-bridge/data-agent-config.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/data-bridge/data-agent-config.xml deleted file mode 100644 index 995b44705b..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/data-bridge/data-agent-config.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - Thrift - org.wso2.carbon.databridge.agent.endpoint.thrift.ThriftDataEndpoint - src/test/resources/client-truststore.jks - wso2carbon - 32768 - 200 - 1 - 30000 - 1 - 20 - 30 - 250 - 250 - 5500 - 5000 - 250 - 250 - 5500 - 5000 - - - - - - Binary - org.wso2.carbon.databridge.agent.endpoint.binary.BinaryDataEndpoint - src/test/resources/client-truststore.jks - wso2carbon - 32768 - 200 - 1 - 1 - 30000 - 20 - 30 - 250 - 250 - 5500 - 5000 - 250 - 250 - 5500 - 5000 - - - - - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/etc/device-analytics-config-invalid-xml.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/etc/device-analytics-config-invalid-xml.xml deleted file mode 100644 index c9298fdb34..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/etc/device-analytics-config-invalid-xml.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - tcp://localhost:7615 - testuser - testuserpwd diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/etc/device-analytics-config-invalid.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/etc/device-analytics-config-invalid.xml deleted file mode 100644 index 4a63c9cf5c..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/etc/device-analytics-config-invalid.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - tcp://localhost:7615 - testuser - testuserpwd - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/etc/device-analytics-config.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/etc/device-analytics-config.xml deleted file mode 100644 index a4caa4fa31..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/etc/device-analytics-config.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - true - tcp://localhost:7615 - testuser - testuserpwd - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/registry.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/registry.xml deleted file mode 100644 index 331c448c87..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/registry.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - wso2registry - false - true - / - - - jdbc:h2:./target/databasetest/CARBON_TEST - - org.h2.Driver - 80 - 60000 - 5 - - - false - - - - true - true - true - true - - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/client-truststore.jks b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/client-truststore.jks deleted file mode 100644 index 3b9fdfb9e8..0000000000 Binary files a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/client-truststore.jks and /dev/null differ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/testng.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/testng.xml deleted file mode 100644 index fffc1f8f85..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/testng.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/pom.xml deleted file mode 100644 index 2ede4c663c..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/pom.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - - - device-mgt - io.entgra.device.mgt.core - 5.0.0-SNAPSHOT - - 4.0.0 - - org.wso2.carbon.device.mgt.analytics.wsproxy - war - WSO2 - Webapp for Web Socket Proxy - http://wso2.org - - - - io.entgra.device.mgt.core - org.wso2.carbon.device.mgt.analytics.data.publisher - provided - - - javax.ws.rs - javax.ws.rs-api - - - org.apache.cxf - cxf-rt-frontend-jaxrs - - - - - secured-websocket-proxy - - - org.jacoco - jacoco-maven-plugin - - ${basedir}/target/coverage-reports/jacoco-unit.exec - - - - jacoco-initialize - - prepare-agent - - - - jacoco-site - test - - report - - - ${basedir}/target/coverage-reports/jacoco-unit.exec - ${basedir}/target/coverage-reports/site - - - - - - - - \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/src/main/java/org/wso2/carbon/device/mgt/analytics/wsproxy/exception/WSProxyException.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/src/main/java/org/wso2/carbon/device/mgt/analytics/wsproxy/exception/WSProxyException.java deleted file mode 100644 index 7937ada371..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/src/main/java/org/wso2/carbon/device/mgt/analytics/wsproxy/exception/WSProxyException.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.analytics.wsproxy.exception; - -/** - * Indicates an error with deployment tinkerer - * - * @since 1.0.0 - */ -public class WSProxyException extends Exception { - - /** - * Constructs a new exception with the message provided and the cause. - * - * @param message the detailed message of the exception - * @param cause the cause of the exception - */ - public WSProxyException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/src/main/java/org/wso2/carbon/device/mgt/analytics/wsproxy/inbound/SubscriptionEndpoint.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/src/main/java/org/wso2/carbon/device/mgt/analytics/wsproxy/inbound/SubscriptionEndpoint.java deleted file mode 100644 index b556949ae1..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/src/main/java/org/wso2/carbon/device/mgt/analytics/wsproxy/inbound/SubscriptionEndpoint.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.analytics.wsproxy.inbound; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.databridge.agent.exception.DataEndpointConfigurationException; -import org.wso2.carbon.device.mgt.analytics.data.publisher.DataPublisherUtil; -import org.wso2.carbon.device.mgt.analytics.data.publisher.config.AnalyticsConfiguration; -import org.wso2.carbon.device.mgt.analytics.wsproxy.exception.WSProxyException; -import org.wso2.carbon.device.mgt.analytics.wsproxy.outbound.AnalyticsClient; - -import javax.websocket.CloseReason; -import javax.websocket.Session; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Interface for subscription and un-subscription for web socket - */ - -public class SubscriptionEndpoint { - - private static final Log log = LogFactory.getLog(SubscriptionEndpoint.class); - private Map> analyticsClientsMap = new HashMap<>(); - - /** - * Web socket onOpen - When client sends a message - * - * @param session - Users registered session. - */ - void onOpen(Session session) { - if (log.isDebugEnabled()) { - log.debug("WebSocket opened, for Session id: " + session.getId()); - } - - AnalyticsConfiguration analyticsConfig = AnalyticsConfiguration.getInstance(); - ArrayList publisherGroups = - DataPublisherUtil.getEndpointGroups(analyticsConfig.getAnalyticsPublisherUrl()); - List analyticsClients = new ArrayList<>(); - for (String publisherURLGroup : publisherGroups) { - try { - String[] endpoints = DataPublisherUtil.getEndpoints(publisherURLGroup); - for (String endpoint : endpoints) { - try { - endpoint = endpoint.trim(); - if (!endpoint.endsWith("/")) { - endpoint += "/"; - } - endpoint += session.getRequestURI().getSchemeSpecificPart().replace("secured-websocket-proxy",""); - AnalyticsClient analyticsClient = new AnalyticsClient(session, new URI(endpoint)); - analyticsClients.add(analyticsClient); - } catch (URISyntaxException e) { - log.error("Unable to create URL from: " + endpoint, e); - } catch (WSProxyException e) { - log.error("Unable to create WS client for: " + endpoint, e); - } - } - } catch (DataEndpointConfigurationException e) { - log.error("Unable to obtain endpoints from receiverURLGroup: " + publisherURLGroup, e); - } - } - if (log.isDebugEnabled()) { - log.debug("Configured " + analyticsClients.size() + " analytics clients for Session id: " + - session.getId()); - } - analyticsClientsMap.put(session.getId(), analyticsClients); - } - - /** - * Web socket onClose - Remove the registered sessions - * - * @param session - Users registered session. - * @param reason - Status code for web-socket close. - * @param streamName - StreamName extracted from the ws url. - * @param version - Version extracted from the ws url. - * @param tenantDomain - Domain of the tenant. - */ - public void onClose(Session session, CloseReason reason, String streamName, String version, String tenantDomain) { - if (log.isDebugEnabled()) { - log.debug("Closing a WebSocket due to " + reason.getReasonPhrase() + ", for session ID:" + - session.getId() + ", for request URI - " + session.getRequestURI()); - } - for (AnalyticsClient analyticsClient : analyticsClientsMap.get(session.getId())) { - if (analyticsClient != null) { - try { - analyticsClient.closeConnection(reason); - } catch (WSProxyException e) { - log.error("Error occurred while closing ws connection due to " + reason.getReasonPhrase() + - ", for session ID:" + session.getId() + ", for request URI - " + session.getRequestURI(), e); - } - } - } - analyticsClientsMap.remove(session.getId()); - } - - /** - * Web socket onMessage - When client sens a message - * - * @param session - Users registered session. - * @param message - Status code for web-socket close. - */ - void onMessage(Session session, String message) { - for (AnalyticsClient analyticsClient : analyticsClientsMap.get(session.getId())) { - if (analyticsClient != null) { - analyticsClient.sendMessage(message); - } - } - } - - /** - * Web socket onError - * - * @param session - Users registered session. - * @param throwable - Status code for web-socket close. - * @param streamName - StreamName extracted from the ws url. - * @param version - Version extracted from the ws url. - * @param tenantDomain - Domain of the tenant. - */ - public void onError(Session session, Throwable throwable, String streamName, String version, String tenantDomain) { - log.error("Error occurred in session ID: " + session.getId() + ", for request URI - " + - session.getRequestURI() + ", " + throwable.getMessage(), throwable); - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/src/main/java/org/wso2/carbon/device/mgt/analytics/wsproxy/inbound/SuperTenantSubscriptionEndpoint.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/src/main/java/org/wso2/carbon/device/mgt/analytics/wsproxy/inbound/SuperTenantSubscriptionEndpoint.java deleted file mode 100644 index 0e4bc3684d..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/src/main/java/org/wso2/carbon/device/mgt/analytics/wsproxy/inbound/SuperTenantSubscriptionEndpoint.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.analytics.wsproxy.inbound; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.base.MultitenantConstants; - -import javax.websocket.CloseReason; -import javax.websocket.EndpointConfig; -import javax.websocket.OnClose; -import javax.websocket.OnError; -import javax.websocket.OnMessage; -import javax.websocket.OnOpen; -import javax.websocket.Session; -import javax.websocket.server.PathParam; -import javax.websocket.server.ServerEndpoint; - -/** - * Connect to web socket with Super tenant - */ - -@ServerEndpoint(value = "/{destination}/{streamname}/{version}") -public class SuperTenantSubscriptionEndpoint extends SubscriptionEndpoint { - - private static final Log log = LogFactory.getLog(SuperTenantSubscriptionEndpoint.class); - - /** - * Web socket onOpen - When client sends a message - * - * @param session - Users registered session. - * @param streamName - StreamName extracted from the ws url. - * @param version - Version extracted from the ws url. - */ - @OnOpen - public void onOpen(Session session, EndpointConfig config, @PathParam("streamname") String streamName, - @PathParam("version") String version) { - if (log.isDebugEnabled()) { - log.debug("WebSocket opened, for Session id: " + session.getId() + ", for the Stream:" + streamName); - } - super.onOpen(session); - } - - /** - * Web socket onMessage - When client sens a message - * - * @param session - Users registered session. - * @param message - Status code for web-socket close. - * @param streamName - StreamName extracted from the ws url. - */ - @OnMessage - public void onMessage(Session session, String message, @PathParam("streamname") String streamName) { - if (log.isDebugEnabled()) { - log.debug("Received message from client. Message: " + message + ", " + - "for Session id: " + session.getId() + ", for the Stream:" + streamName); - } - super.onMessage(session, message); - } - - /** - * Web socket onClose - Remove the registered sessions - * - * @param session - Users registered session. - * @param reason - Status code for web-socket close. - * @param streamName - StreamName extracted from the ws url. - * @param version - Version extracted from the ws url. - */ - @OnClose - public void onClose(Session session, CloseReason reason, @PathParam("streamname") String streamName, - @PathParam("version") String version) { - super.onClose(session, reason, streamName, version, MultitenantConstants.SUPER_TENANT_NAME); - } - - /** - * Web socket onError - Remove the registered sessions - * - * @param session - Users registered session. - * @param throwable - Status code for web-socket close. - * @param streamName - StreamName extracted from the ws url. - * @param version - Version extracted from the ws url. - */ - @OnError - public void onError(Session session, Throwable throwable, @PathParam("streamname") String streamName, - @PathParam("version") String version) { - super.onError(session, throwable, streamName, version, MultitenantConstants.SUPER_TENANT_NAME); - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/src/main/java/org/wso2/carbon/device/mgt/analytics/wsproxy/inbound/TenantSubscriptionEndpoint.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/src/main/java/org/wso2/carbon/device/mgt/analytics/wsproxy/inbound/TenantSubscriptionEndpoint.java deleted file mode 100644 index 02e55cfed6..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/src/main/java/org/wso2/carbon/device/mgt/analytics/wsproxy/inbound/TenantSubscriptionEndpoint.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.analytics.wsproxy.inbound; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.websocket.CloseReason; -import javax.websocket.EndpointConfig; -import javax.websocket.OnClose; -import javax.websocket.OnError; -import javax.websocket.OnMessage; -import javax.websocket.OnOpen; -import javax.websocket.Session; -import javax.websocket.server.PathParam; -import javax.websocket.server.ServerEndpoint; - -/** - * Connect to web socket with a tenant - */ - -@ServerEndpoint(value = "/{destination}/t/{tdomain}/{streamname}/{version}") -public class TenantSubscriptionEndpoint extends SubscriptionEndpoint { - - private static final Log log = LogFactory.getLog(TenantSubscriptionEndpoint.class); - - /** - * Web socket onOpen - When client sends a message - * - * @param session - Users registered session. - * @param streamName - StreamName extracted from the ws url. - * @param version - Version extracted from the ws url. - * @param tdomain - Tenant domain extracted from ws url. - */ - @OnOpen - public void onOpen(Session session, EndpointConfig config, @PathParam("streamname") String streamName, - @PathParam("version") String version, @PathParam("tdomain") String tdomain) { - if (log.isDebugEnabled()) { - log.debug("WebSocket opened, for Session id: " + session.getId() + ", for the Stream:" + streamName); - } - super.onOpen(session); - } - - /** - * Web socket onMessage - When client sens a message - * - * @param session - Users registered session. - * @param message - Status code for web-socket close. - * @param streamName - StreamName extracted from the ws url. - */ - @OnMessage - public void onMessage(Session session, String message, @PathParam("streamname") String streamName, @PathParam("tdomain") String tdomain) { - if (log.isDebugEnabled()) { - log.debug("Received message from client. Message: " + message + ", for Session id: " + - session.getId() + ", for tenant domain" + tdomain + ", for the Adaptor:" + streamName); - } - super.onMessage(session, message); - } - - /** - * Web socket onClose - Remove the registered sessions - * - * @param session - Users registered session. - * @param reason - Status code for web-socket close. - * @param streamName - StreamName extracted from the ws url. - * @param version - Version extracted from the ws url. - */ - @OnClose - public void onClose(Session session, CloseReason reason, @PathParam("streamname") String streamName, - @PathParam("version") String version, @PathParam("tdomain") String tdomain) { - super.onClose(session, reason, streamName, version, tdomain); - } - - /** - * Web socket onError - Remove the registered sessions - * - * @param session - Users registered session. - * @param throwable - Status code for web-socket close. - * @param streamName - StreamName extracted from the ws url. - * @param version - Version extracted from the ws url. - */ - @OnError - public void onError(Session session, Throwable throwable, @PathParam("streamname") String streamName, - @PathParam("version") String version, @PathParam("tdomain") String tdomain) { - super.onError(session, throwable, streamName, version, tdomain); - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/src/main/java/org/wso2/carbon/device/mgt/analytics/wsproxy/outbound/AnalyticsClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/src/main/java/org/wso2/carbon/device/mgt/analytics/wsproxy/outbound/AnalyticsClient.java deleted file mode 100644 index 96e6d6974a..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/src/main/java/org/wso2/carbon/device/mgt/analytics/wsproxy/outbound/AnalyticsClient.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.analytics.wsproxy.outbound; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.analytics.wsproxy.exception.WSProxyException; - -import javax.websocket.CloseReason; -import javax.websocket.ContainerProvider; -import javax.websocket.DeploymentException; -import javax.websocket.OnClose; -import javax.websocket.OnMessage; -import javax.websocket.Session; -import javax.websocket.WebSocketContainer; -import java.io.IOException; -import java.net.URI; - -/** - * This class holds web socket client implementation - * - * @since 1.0.0 - */ -@javax.websocket.ClientEndpoint -public class AnalyticsClient { - - private static final Log log = LogFactory.getLog(AnalyticsClient.class); - - private final Session analyticsSession; - private final Session clientSession; - - /** - * Create {@link AnalyticsClient} instance. - */ - public AnalyticsClient(Session clientSession, URI endpointURI) throws WSProxyException { - WebSocketContainer container = ContainerProvider.getWebSocketContainer(); - this.clientSession = clientSession; - - try { - this.analyticsSession = container.connectToServer(this, endpointURI); - } catch (DeploymentException | IOException e) { - String msg = "Error occurred while connecting to remote endpoint " + endpointURI.toString(); - log.error(msg, e); - throw new WSProxyException(msg, e); - } - } - - /** - * Callback hook for Connection close events. - * - * @param userSession the analyticsSession which is getting closed. - * @param reason the reason for connection close - */ - @OnClose - public void onClose(Session userSession, CloseReason reason) { - if (log.isDebugEnabled()) { - log.debug("Closing web socket session: '" + userSession.getId() + "'. Code: " + - reason.getCloseCode().toString() + " Reason: " + reason.getReasonPhrase()); - } - } - - /** - * Callback hook for Message Events. - * - *

This method will be invoked when a client send a message. - * - * @param message The text message. - */ - @OnMessage - public void onMessage(String message) { - synchronized (this.clientSession) { - try { - this.clientSession.getBasicRemote().sendText(message); - } catch (IOException e) { - log.warn("Sending message to client failed due to " + e.getMessage()); - if (log.isDebugEnabled()) { - log.debug("Full stack trace:", e); - } - } - } - } - - /** - * Send a message. - * - * @param message the message which is going to send. - */ - public void sendMessage(String message) { - synchronized (this.analyticsSession) { - try { - this.analyticsSession.getBasicRemote().sendText(message); - } catch (IOException e) { - log.warn("Sending message to analytics failed due to " + e.getMessage()); - if (log.isDebugEnabled()) { - log.debug("Full stack trace:", e); - } - } - } - } - - /** - * Close current connection. - */ - public void closeConnection(CloseReason closeReason) throws WSProxyException { - if (this.analyticsSession.isOpen()) { - try { - this.analyticsSession.close(closeReason); - } catch (IOException e) { - String msg = "Error on closing WS connection."; - log.error(msg, e); - throw new WSProxyException(msg, e); - } - } else { - log.warn("Analytics session '" + this.analyticsSession.getId() + "' is already closed"); - } - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/src/main/webapp/WEB-INF/web.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 933cf86531..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - Output WebSocket Proxy - - - ContentTypeBasedCachePreventionFilter - org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter - - patterns - text/html" ,application/json" ,text/plain - - - filterAction - enforce - - - httpHeaders - Cache-Control: no-store, no-cache, must-revalidate, private - - - - - ContentTypeBasedCachePreventionFilter - /* - - diff --git a/components/device-mgt/pom.xml b/components/device-mgt/pom.xml index baca16bf79..1881c7f0ad 100644 --- a/components/device-mgt/pom.xml +++ b/components/device-mgt/pom.xml @@ -30,7 +30,7 @@ device-mgt pom WSO2 Carbon - Device Management Component - http://wso2.org + https://entgra.io io.entgra.device.mgt.core.device.mgt.core diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/pom.xml b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/pom.xml index 6316fff69a..1a44ac0544 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/pom.xml +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/pom.xml @@ -36,8 +36,12 @@ - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -51,20 +55,28 @@ Server Startup Heart Beat Beacon Bundle io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.internal - org.apache.axis2.*;version="${axis2.osgi.version.range}", - org.apache.axiom.*; version="${axiom.osgi.version.range}", + io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.exceptions;version="[5.0,6)", + io.entgra.device.mgt.core.server.bootup.heartbeat.beacon, + io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.config, + io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.config.datasource, + io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.dao, + io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.dao.exception, + io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.dao.impl, + io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.dao.util, + io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.dto, + io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception, + javax.naming, + javax.sql, + javax.xml.bind;version="[0.0,1)", + javax.xml.bind.annotation;version="[0.0,1)", + javax.xml.parsers, + org.apache.commons.logging;version="[1.2,2)", org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.apache.commons.logging, - javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, - org.wso2.carbon.context, - org.wso2.carbon.utils.*, - org.wso2.carbon.ndatasource.core, org.w3c.dom, - org.apache.commons.io, - org.apache.axis2.transport.mail, - org.apache.commons.collections, - io.entgra.device.mgt.core.device.mgt.common.* + org.wso2.carbon.ndatasource.core;version="[4.8,5)", + org.wso2.carbon.utils;version="[4.8,5)" !io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.internal, @@ -74,59 +86,18 @@ - - org.apache.maven.plugins - maven-surefire-plugin - - - file:src/test/resources/log4j.properties - - - src/test/resources/testng.xml - - - - - org.jacoco - jacoco-maven-plugin - - ${basedir}/target/coverage-reports/jacoco-unit.exec - - - - jacoco-initialize - - prepare-agent - - - - jacoco-site - test - - report - - - ${basedir}/target/coverage-reports/jacoco-unit.exec - ${basedir}/target/coverage-reports/site - - - - - org.eclipse.osgi - org.eclipse.osgi + org.apache.felix + org.apache.felix.scr.ds-annotations + provided - org.eclipse.osgi - org.eclipse.osgi.services - - - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api org.wso2.carbon @@ -170,6 +141,11 @@ + + org.wso2.orbit.javax.xml.bind + jaxb-api + provided + diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java index 42964b448d..0fccadc29e 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java @@ -29,12 +29,7 @@ import javax.sql.DataSource; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/config/datasource/JNDILookupDefinition.java b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/config/datasource/JNDILookupDefinition.java index c32b51fb02..1c0ae05af7 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/config/datasource/JNDILookupDefinition.java +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/config/datasource/JNDILookupDefinition.java @@ -18,11 +18,7 @@ package io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.config.datasource; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlValue; +import javax.xml.bind.annotation.*; import java.util.List; /** diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/dao/HeartBeatBeaconDAOFactory.java b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/dao/HeartBeatBeaconDAOFactory.java index e3c3dd3381..b58ec1bde8 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/dao/HeartBeatBeaconDAOFactory.java +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/dao/HeartBeatBeaconDAOFactory.java @@ -18,14 +18,14 @@ package io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.dao; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.HeartBeatBeaconUtils; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.config.datasource.DataSourceConfig; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.config.datasource.JNDILookupDefinition; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.dao.impl.GenericHeartBeatDAOImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; import javax.sql.DataSource; import java.sql.Connection; diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java index fcdee6e5cc..03fe012c5d 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java @@ -28,12 +28,7 @@ import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.dto.ServerContex import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; +import java.sql.*; import java.util.HashMap; import java.util.List; import java.util.Map; diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java index 356f5d4996..9d09ae699d 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java @@ -28,26 +28,21 @@ import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBea import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.core.ServerStartupObserver; import org.wso2.carbon.ndatasource.core.DataSourceService; import java.util.List; -/** - * @scr.component name="io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.heartbeatBeaconComponent" - * immediate="true" - * @scr.reference name="org.wso2.carbon.ndatasource" - * interface="org.wso2.carbon.ndatasource.core.DataSourceService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDataSourceService" - * unbind="unsetDataSourceService" - */ +@Component( + name = "io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.internal.HeartBeatBeaconComponent", + immediate = true) public class HeartBeatBeaconComponent { private static Log log = LogFactory.getLog(HeartBeatBeaconComponent.class); @SuppressWarnings("unused") + @Activate protected void activate(ComponentContext componentContext) { try { if (log.isDebugEnabled()) { @@ -90,6 +85,7 @@ public class HeartBeatBeaconComponent { } @SuppressWarnings("unused") + @Deactivate protected void deactivate(ComponentContext componentContext) { //do nothing } @@ -103,6 +99,12 @@ public class HeartBeatBeaconComponent { componentContext.getBundleContext().registerService(HeartBeatManagementService.class, heartBeatServiceProvider, null); } + @Reference( + name = "datasource.service", + service = org.wso2.carbon.ndatasource.core.DataSourceService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDataSourceService") protected void setDataSourceService(DataSourceService dataSourceService) { /* This is to avoid mobile device management component getting initialized before the underlying datasources are registered */ diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java index f8c6afcc56..afe54139ad 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java @@ -18,10 +18,10 @@ package io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service; +import io.entgra.device.mgt.core.device.mgt.common.ServerCtxInfo; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.dto.ServerContext; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; -import io.entgra.device.mgt.core.device.mgt.common.ServerCtxInfo; import java.util.Map; diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java index c243d4e9b6..4cf88ac8fe 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java @@ -18,6 +18,8 @@ package io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service; +import io.entgra.device.mgt.core.device.mgt.common.ServerCtxInfo; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.config.HeartBeatBeaconConfig; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.dao.HeartBeatBeaconDAOFactory; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.dao.HeartBeatDAO; @@ -29,17 +31,10 @@ import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception.HeartB import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.internal.HeartBeatBeaconDataHolder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.ServerCtxInfo; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; import java.sql.SQLException; import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Set; +import java.util.*; import java.util.concurrent.TimeUnit; public class HeartBeatManagementServiceImpl implements HeartBeatManagementService { diff --git a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/pom.xml b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/pom.xml index 4b46d40ee6..e86a5947dc 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/pom.xml +++ b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/pom.xml @@ -30,9 +30,14 @@ io.entgra.device.mgt.core.device.mgt.oauth.extensions bundle WSO2 Carbon - OAuth Extensions - http://wso2.org + https://entgra.io + + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + commons-codec.wso2 commons-codec @@ -62,13 +67,16 @@ - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix maven-bundle-plugin - 1.4.0 true @@ -82,32 +90,41 @@ io.entgra.device.mgt.core.device.mgt.oauth.extensions.* - org.wso2.carbon.identity.oauth2.grant.jwt;version="${carbon.identity.jwt.grant.version.range}", - org.apache.commons.lang, - org.apache.commons.logging, - org.osgi.service.component, - org.wso2.carbon.identity.application.common.model;version="${carbon.identity.framework.version.range}", - org.wso2.carbon.identity.application.common;version="${carbon.identity.framework.version.range}", - org.wso2.carbon.identity.application.mgt.*;version="${carbon.identity.framework.version.range}", - org.wso2.carbon.user.api, - org.wso2.carbon.user.core.service, - org.wso2.carbon.user.core.tenant, - org.wso2.carbon.user.core.util, - org.json.simple, - javax.cache, - org.wso2.carbon.identity.core.util;version="${carbon.identity.framework.version.range}", - org.wso2.carbon.utils, - org.wso2.carbon.context, - org.wso2.carbon.identity.oauth.*;version="${carbon.identity.framework.version.range}", - - org.wso2.carbon.base, - org.wso2.carbon.identity.application.authentication.framework.model;version="${carbon.identity.framework.version.range}", - org.wso2.carbon.identity.base;version="${carbon.identity.framework.version.range}", - org.wso2.carbon.identity.oauth2.*;version="${carbon.identity.framework.version.range}", - org.wso2.carbon.utils.multitenancy, - org.apache.oltu.oauth2.common.validators, - org.apache.commons.lang3.tuple, + io.entgra.device.mgt.core.device.mgt.oauth.extensions.handlers.grant.oauth.validator, + io.entgra.device.mgt.core.device.mgt.oauth.extensions.handlers.grant.oauth.validator.internal, + javax.servlet.http;version="[2.6,3)", + org.apache.commons.lang;version="[2.6,3)", + org.apache.commons.lang3.tuple;version="[3.1,4)", + org.apache.commons.logging;version="[1.2,2)", + org.apache.oltu.oauth2.common.validators;version="[1.0,2)", + org.osgi.service.*;version="${imp.package.version.osgi.service}", + org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.identity.application.authentication.framework.model;version="[5.24,6)", + org.wso2.carbon.identity.application.common;version="[5.24,6)", + org.wso2.carbon.identity.application.common.model;version="[5.24,6)", + org.wso2.carbon.identity.application.mgt;version="[5.24,6)", + org.wso2.carbon.identity.core.util;version="[5.24,6)", + org.wso2.carbon.identity.oauth.cache;version="[6.9,7)", + org.wso2.carbon.identity.oauth2;version="[6.9,7)", + org.wso2.carbon.identity.oauth2.dao;version="[6.9,7)", + org.wso2.carbon.identity.oauth2.dto;version="[6.9,7)", + org.wso2.carbon.identity.oauth2.grant.jwt;version="[2.1,3)", + org.wso2.carbon.identity.oauth2.internal;version="[6.9,7)", + org.wso2.carbon.identity.oauth2.model;version="[6.9,7)", + org.wso2.carbon.identity.oauth2.token;version="[6.9,7)", + org.wso2.carbon.identity.oauth2.token.handlers.grant;version="[6.9,7)", + org.wso2.carbon.identity.oauth2.token.handlers.grant.saml;version="[6.9,7)", + org.wso2.carbon.identity.oauth2.util;version="[6.9,7)", + org.wso2.carbon.identity.oauth2.validators;version="[6.9,7)", + org.wso2.carbon.user.api;version="[1.0,2)", + org.wso2.carbon.user.core.service;version="[4.8,5)", + org.wso2.carbon.user.core.tenant;version="[4.8,5)", + org.wso2.carbon.user.core.util;version="[4.8,5)", + org.wso2.carbon.utils.multitenancy;version="[4.8,5)" + + oltu;scope=compile|runtime;inline=false + diff --git a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/handlers/ScopeValidationHandler.java b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/handlers/ScopeValidationHandler.java index aeff930a8a..cb97fc7319 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/handlers/ScopeValidationHandler.java +++ b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/handlers/ScopeValidationHandler.java @@ -17,17 +17,16 @@ */ package io.entgra.device.mgt.core.device.mgt.oauth.extensions.handlers; +import io.entgra.device.mgt.core.device.mgt.oauth.extensions.internal.OAuthExtensionsDataHolder; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.oauth.extensions.internal.OAuthExtensionsDataHolder; import org.wso2.carbon.identity.oauth.cache.CacheEntry; import org.wso2.carbon.identity.oauth.cache.OAuthCache; import org.wso2.carbon.identity.oauth.cache.OAuthCacheKey; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; import org.wso2.carbon.identity.oauth2.dao.TokenManagementDAO; import org.wso2.carbon.identity.oauth2.dao.TokenManagementDAOImpl; -import org.wso2.carbon.identity.oauth2.dao.TokenMgtDAO; import org.wso2.carbon.identity.oauth2.model.AccessTokenDO; import org.wso2.carbon.identity.oauth2.model.ResourceScopeCacheEntry; import org.wso2.carbon.identity.oauth2.validators.OAuth2ScopeValidator; diff --git a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/handlers/grant/AccessTokenGrantHandler.java b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/handlers/grant/AccessTokenGrantHandler.java index d4c0d3bb5d..c3fd491e4e 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/handlers/grant/AccessTokenGrantHandler.java +++ b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/handlers/grant/AccessTokenGrantHandler.java @@ -18,11 +18,11 @@ package io.entgra.device.mgt.core.device.mgt.oauth.extensions.handlers.grant; +import io.entgra.device.mgt.core.device.mgt.oauth.extensions.handlers.grant.oauth.validator.LocalOAuthValidator; +import io.entgra.device.mgt.core.device.mgt.oauth.extensions.handlers.grant.oauth.validator.OAuthValidationResponse; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.oauth.extensions.handlers.grant.oauth.validator.LocalOAuthValidator; -import io.entgra.device.mgt.core.device.mgt.oauth.extensions.handlers.grant.oauth.validator.OAuthValidationResponse; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; import org.wso2.carbon.identity.application.common.model.ServiceProvider; @@ -35,6 +35,7 @@ import org.wso2.carbon.identity.oauth2.token.handlers.grant.AbstractAuthorizatio import org.wso2.carbon.identity.oauth2.util.OAuth2Util; import org.wso2.carbon.user.core.util.UserCoreUtil; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; + import java.rmi.RemoteException; /** diff --git a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/handlers/grant/oauth/validator/internal/OAuthAuthenticatorServiceComponent.java b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/handlers/grant/oauth/validator/internal/OAuthAuthenticatorServiceComponent.java index cbe5510bcb..64c020f743 100755 --- a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/handlers/grant/oauth/validator/internal/OAuthAuthenticatorServiceComponent.java +++ b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/handlers/grant/oauth/validator/internal/OAuthAuthenticatorServiceComponent.java @@ -21,22 +21,18 @@ package io.entgra.device.mgt.core.device.mgt.oauth.extensions.handlers.grant.oau import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; -/** - * @scr.component name="io.entgra.device.mgt.core.device.mgt.oauth.extensions.authenticator" immediate="true" - * @scr.reference name="identity.oauth2.validation.service" - * interface="org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService" - * cardinality="1..1" - * policy="dynamic" - * bind="setOAuth2ValidationService" - * unbind="unsetOAuth2ValidationService" - */ +@Component( + name = "io.entgra.device.mgt.core.device.mgt.oauth.extensions.handlers.grant.oauth.validator.internal.OAuthAuthenticatorServiceComponent", + immediate = true) public class OAuthAuthenticatorServiceComponent { private static final Log log = LogFactory.getLog(OAuthAuthenticatorServiceComponent.class); @SuppressWarnings("unused") + @Activate protected void activate(ComponentContext componentContext) { if (log.isDebugEnabled()) { log.debug("Starting Backend OAuthAuthenticator Framework Bundle"); @@ -44,6 +40,7 @@ public class OAuthAuthenticatorServiceComponent { } @SuppressWarnings("unused") + @Deactivate protected void deactivate(ComponentContext componentContext) { //do nothing } @@ -54,6 +51,12 @@ public class OAuthAuthenticatorServiceComponent { * @param tokenValidationService An instance of OAuth2TokenValidationService. */ @SuppressWarnings("unused") + @Reference( + name = "oauth2.token.validation.service", + service = org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetOAuth2ValidationService") protected void setOAuth2ValidationService(OAuth2TokenValidationService tokenValidationService) { if (log.isDebugEnabled()) { log.debug("Setting OAuth2TokenValidationService Service"); diff --git a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/internal/OAuthExtensionServiceComponent.java b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/internal/OAuthExtensionServiceComponent.java index 4308da4d39..6de407711e 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/internal/OAuthExtensionServiceComponent.java +++ b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/internal/OAuthExtensionServiceComponent.java @@ -22,33 +22,15 @@ import io.entgra.device.mgt.core.device.mgt.oauth.extensions.validators.Extended import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; - +import org.osgi.service.component.annotations.*; import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; import org.wso2.carbon.identity.oauth2.validators.JDBCScopeValidator; import org.wso2.carbon.identity.oauth2.validators.OAuth2ScopeValidator; import org.wso2.carbon.user.core.service.RealmService; -/** - * @scr.component name="io.entgra.device.mgt.core.device.mgt.oauth.extensions" immediate="true" - * @scr.reference name="user.realmservice.default" - * interface="org.wso2.carbon.user.core.service.RealmService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRealmService" - * unbind="unsetRealmService" - * @scr.reference name="identity.oauth2.validation.service" - * interface="org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService" - * cardinality="1..1" - * policy="dynamic" - * bind="setOAuth2ValidationService" - * unbind="unsetOAuth2ValidationService" - * * @scr.reference name="scope.validator.service" - * interface="org.wso2.carbon.identity.oauth2.validators.OAuth2ScopeValidator" - * cardinality="0..n" - * policy="dynamic" - * bind="addScopeValidator" - * unbind="removeScopeValidator" - */ +@Component( + name = "io.entgra.device.mgt.core.device.mgt.oauth.extensions.internal.OAuthExtensionServiceComponent", + immediate = true) public class OAuthExtensionServiceComponent { private static final Log log = LogFactory.getLog(OAuthExtensionServiceComponent.class); @@ -60,6 +42,7 @@ public class OAuthExtensionServiceComponent { @SuppressWarnings("unused") + @Activate protected void activate(ComponentContext componentContext) { if (log.isDebugEnabled()) { log.debug("Starting OAuthExtensionBundle"); @@ -75,6 +58,7 @@ public class OAuthExtensionServiceComponent { } @SuppressWarnings("unused") + @Deactivate protected void deactivate(ComponentContext componentContext) { if (log.isDebugEnabled()) { log.debug("Stopping OAuthExtensionBundle"); @@ -86,6 +70,12 @@ public class OAuthExtensionServiceComponent { * * @param realmService An instance of RealmService */ + @Reference( + name = "realm.service", + service = org.wso2.carbon.user.core.service.RealmService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRealmService") protected void setRealmService(RealmService realmService) { if (log.isDebugEnabled()) { log.debug("Setting Realm Service"); @@ -110,6 +100,12 @@ public class OAuthExtensionServiceComponent { * * @param tokenValidationService An instance of OAuth2TokenValidationService */ + @Reference( + name = "oauth2.token.validation.service", + service = org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetOAuth2ValidationService") protected void setOAuth2ValidationService(OAuth2TokenValidationService tokenValidationService) { if (log.isDebugEnabled()) { log.debug("Setting OAuth2TokenValidation Service"); @@ -133,6 +129,12 @@ public class OAuthExtensionServiceComponent { * Add scope validator to the map. * @param scopesValidator */ + @Reference( + name = "oauth2.scope.validator", + service = org.wso2.carbon.identity.oauth2.validators.OAuth2ScopeValidator.class, + cardinality = ReferenceCardinality.MULTIPLE, + policy = ReferencePolicy.DYNAMIC, + unbind = "removeScopeValidator") protected void addScopeValidator(OAuth2ScopeValidator scopesValidator) { OAuthExtensionsDataHolder.getInstance().addScopeValidator(scopesValidator, DEFAULT_PREFIX); } diff --git a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/validators/ExtendedJDBCScopeValidator.java b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/validators/ExtendedJDBCScopeValidator.java index 46aa1ea8cb..75fbccbf7f 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/validators/ExtendedJDBCScopeValidator.java +++ b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/validators/ExtendedJDBCScopeValidator.java @@ -18,11 +18,11 @@ package io.entgra.device.mgt.core.device.mgt.oauth.extensions.validators; +import io.entgra.device.mgt.core.device.mgt.oauth.extensions.internal.OAuthExtensionsDataHolder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.oauth.extensions.internal.OAuthExtensionsDataHolder; import org.wso2.carbon.identity.application.common.model.User; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.oauth.cache.CacheEntry; diff --git a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java index d768110ce1..97defd2e2d 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java +++ b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java @@ -18,11 +18,11 @@ package io.entgra.device.mgt.core.device.mgt.oauth.extensions.validators; +import io.entgra.device.mgt.core.device.mgt.oauth.extensions.internal.OAuthExtensionsDataHolder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.oauth.extensions.internal.OAuthExtensionsDataHolder; import org.wso2.carbon.identity.application.common.model.User; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; diff --git a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/validators/RoleBasedScopeValidator.java b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/validators/RoleBasedScopeValidator.java index db33b266a1..94a126e085 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/validators/RoleBasedScopeValidator.java +++ b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/oauth/extensions/validators/RoleBasedScopeValidator.java @@ -18,11 +18,11 @@ package io.entgra.device.mgt.core.device.mgt.oauth.extensions.validators; +import io.entgra.device.mgt.core.device.mgt.oauth.extensions.internal.OAuthExtensionsDataHolder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.oauth.extensions.internal.OAuthExtensionsDataHolder; import org.wso2.carbon.identity.application.common.model.User; import org.wso2.carbon.identity.base.IdentityConstants; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; diff --git a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/pom.xml b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/pom.xml index 47b4616212..826280ae17 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/pom.xml +++ b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/pom.xml @@ -31,9 +31,14 @@ bundle WSO2 Carbon - Device Management JWT Client Extensions WSO2 Carbon - Device Management JWT Client Extensions - http://wso2.org + https://entgra.io + + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + org.wso2.carbon.governance org.wso2.carbon.governance.api @@ -55,23 +60,15 @@ org.wso2.carbon.utils - org.wso2.orbit.org.scannotation + io.entgra.org.scannotation scannotation - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services - - - org.wso2.tomcat + org.wso2.orbit.org.apache.tomcat tomcat - org.wso2.tomcat + org.wso2.orbit.org.apache.tomcat tomcat-servlet-api @@ -121,8 +118,9 @@ commons-codec - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api + provided org.testng @@ -146,8 +144,8 @@ - com.h2database.wso2 - h2-database-engine + org.wso2.orbit.com.h2database + h2 test @@ -157,21 +155,33 @@ org.powermock - powermock-api-mockito + powermock-api-mockito2 + test + + + org.mockito + mockito-core test + + org.wso2.orbit.javax.xml.bind + jaxb-api + - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix maven-bundle-plugin - 1.4.0 true @@ -185,35 +195,35 @@ io.entgra.device.mgt.core.identity.jwt.client.extension.* + com.nimbusds.jose;version="[7.9,8)", + com.nimbusds.jose.crypto;version="[7.9,8)", + com.nimbusds.jwt;version="[7.9,8)", + io.entgra.device.mgt.core.identity.jwt.client.extension, + io.entgra.device.mgt.core.identity.jwt.client.extension.dto, + io.entgra.device.mgt.core.identity.jwt.client.extension.exception, + io.entgra.device.mgt.core.identity.jwt.client.extension.service, + javax.net.ssl, + org.apache.commons.codec.binary;version="[1.4,2)", + org.apache.commons.logging;version="[1.2,2)", + org.apache.http;version="[4.4,5)", + org.apache.http.client;version="[4.3,5)", + org.apache.http.client.entity;version="[4.3,5)", + org.apache.http.client.methods;version="[4.3,5)", + org.apache.http.conn.socket;version="[4.3,5)", + org.apache.http.conn.ssl;version="[4.3,5)", + org.apache.http.impl.client;version="[4.3,5)", + org.apache.http.message;version="[4.4,5)", + org.apache.http.util;version="[4.4,5)", + org.json.simple;version="[1.1,2)", + org.json.simple.parser;version="[1.1,2)", org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.wso2.carbon.context, - org.wso2.carbon.registry.core, - org.wso2.carbon.registry.core.exceptions, - org.wso2.carbon.registry.core.session, - org.wso2.carbon.utils, - org.apache.commons.logging, - org.wso2.carbon.registry.core.*;resolution:=optional, - org.wso2.carbon.registry.indexing.*; version="${carbon.registry.imp.pkg.version.range}", - com.nimbusds.jwt.*;version="${nimbus.orbit.version.range}", - com.nimbusds.jose.*;version="${nimbus.orbit.version.range}", - javax.net.ssl, - org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}", - org.apache.http;version="${httpclient.version.range}", - org.apache.http.client;version="${httpclient.version.range}", - org.apache.http.message;version="${httpclient.version.range}", - org.apache.http.client;version="${httpclient.version.range}", - org.apache.http.conn.*;version="${httpclient.version.range}", - org.apache.http.util;version="${httpclient.version.range}", - org.apache.http.client.entity;version="${httpclient.version.range}", - org.apache.http.client.methods;version="${httpclient.version.range}", - org.apache.http.impl.client;version="${httpclient.version.range}", - org.json.simple.*, - org.wso2.carbon.core.util, - javax.net.ssl, - org.wso2.carbon.user.core.service, - org.wso2.carbon.user.core.tenant, - org.wso2.carbon.base + org.wso2.carbon.context;version="${carbon.platform.package.import.version.range}", + org.wso2.carbon.core.*; version="${carbon.platform.package.import.version.range}", + org.wso2.carbon.registry.core.*; version="${carbon.registry.imp.pkg.version}", + org.wso2.carbon.registry.indexing.*;version="${carbon.registry.package.import.version.range}", + org.wso2.carbon.user.core.*;version="${carbon.platform.package.import.version.range}", + org.wso2.carbon.utils.*; version="${carbon.platform.package.import.version.range}" @@ -248,15 +258,21 @@ org.apache.maven.plugins maven-surefire-plugin + + --add-opens=java.xml/jdk.xml.internal=ALL-UNNAMED + --add-opens=java.base/jdk.internal.loader=ALL-UNNAMED + file:src/test/resources/log4j.properties src/test/resources/testng.xml + + org.ops4j.pax.logging + - diff --git a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/JWTClient.java b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/JWTClient.java index 7bd07850a2..2675314524 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/JWTClient.java +++ b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/JWTClient.java @@ -18,6 +18,11 @@ package io.entgra.device.mgt.core.identity.jwt.client.extension; +import io.entgra.device.mgt.core.identity.jwt.client.extension.constant.JWTConstants; +import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.AccessTokenInfo; +import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.JWTConfig; +import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; +import io.entgra.device.mgt.core.identity.jwt.client.extension.util.JWTClientUtil; import org.apache.commons.codec.binary.Base64; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -30,11 +35,6 @@ import org.apache.http.message.BasicNameValuePair; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; -import io.entgra.device.mgt.core.identity.jwt.client.extension.constant.JWTConstants; -import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.AccessTokenInfo; -import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.JWTConfig; -import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; -import io.entgra.device.mgt.core.identity.jwt.client.extension.util.JWTClientUtil; import java.io.IOException; import java.net.MalformedURLException; @@ -138,7 +138,9 @@ public class JWTClient { if (jwtConfig == null) { return null; } - URL tokenEndpoint = new URL(jwtConfig.getTokenEndpoint()); +// todo: +// URL tokenEndpoint = new URL(jwtConfig.getTokenEndpoint()); + URL tokenEndpoint = new URL("https://localhost:9443/oauth2/token"); HttpClient httpClient = JWTClientUtil.getHttpClient(tokenEndpoint.getProtocol()); HttpPost postMethod = new HttpPost(tokenEndpoint.toString()); postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs)); diff --git a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/dto/JWTConfig.java b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/dto/JWTConfig.java index 609f3f3275..274a10c37a 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/dto/JWTConfig.java +++ b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/dto/JWTConfig.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.identity.jwt.client.extension.dto; -import org.wso2.carbon.core.util.Utils; import io.entgra.device.mgt.core.identity.jwt.client.extension.constant.JWTConstants; +import org.wso2.carbon.core.util.Utils; import java.util.ArrayList; import java.util.List; diff --git a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/internal/JWTClientExtensionServiceComponent.java b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/internal/JWTClientExtensionServiceComponent.java index 8b7fdd9f81..04b5215264 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/internal/JWTClientExtensionServiceComponent.java +++ b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/internal/JWTClientExtensionServiceComponent.java @@ -17,53 +17,32 @@ */ package io.entgra.device.mgt.core.identity.jwt.client.extension.internal; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.framework.BundleContext; -import org.osgi.service.component.ComponentContext; import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientConfigurationException; import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerServiceImpl; import io.entgra.device.mgt.core.identity.jwt.client.extension.util.JWTClientUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.framework.BundleContext; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.TenantRegistryLoader; import org.wso2.carbon.registry.indexing.service.TenantIndexingLoader; import org.wso2.carbon.user.core.service.RealmService; + import java.io.IOException; -/** - * @scr.component name="io.entgra.device.mgt.core.identity.jwt.client.extension.internal.JWTClientExtensionServiceComponent" - * immediate="true" - * @scr.reference name="registry.service" - * interface="org.wso2.carbon.registry.core.service.RegistryService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRegistryService" - * unbind="unsetRegistryService" - * @scr.reference name="tenant.registryloader" - * interface="org.wso2.carbon.registry.core.service.TenantRegistryLoader" - * cardinality="1..1" - * policy="dynamic" - * bind="setTenantRegistryLoader" - * unbind="unsetTenantRegistryLoader" - * @scr.reference name="tenant.indexloader" - * interface="org.wso2.carbon.registry.indexing.service.TenantIndexingLoader" - * cardinality="1..1" - * policy="dynamic" - * bind="setIndexLoader" - * unbind="unsetIndexLoader" - * @scr.reference name="realm.service" - * interface="org.wso2.carbon.user.core.service.RealmService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRealmService" - * unbind="unsetRealmService" - */ +@Component( + name = "io.entgra.device.mgt.core.identity.jwt.client.extension.internal.JWTClientExtensionServiceComponent", + immediate = true) public class JWTClientExtensionServiceComponent { private static Log log = LogFactory.getLog(JWTClientExtensionServiceComponent.class); + // private ServiceRegistration serviceRegistration = null; + @Activate protected void activate(ComponentContext componentContext) { if (log.isDebugEnabled()) { log.debug("Initializing jwt extension bundle"); @@ -82,10 +61,19 @@ public class JWTClientExtensionServiceComponent { } } + @Deactivate protected void deactivate(ComponentContext componentContext) { - //do nothing + if (log.isDebugEnabled()) { + log.info("deactivating jwt extension bundle"); + } } + @Reference( + name = "registry.service", + service = org.wso2.carbon.registry.core.service.RegistryService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRegistryService") protected void setRegistryService(RegistryService registryService) { if (registryService != null && log.isDebugEnabled()) { log.debug("Registry service initialized"); @@ -97,6 +85,12 @@ public class JWTClientExtensionServiceComponent { JWTClientExtensionDataHolder.getInstance().setRegistryService(null); } + @Reference( + name = "tenant.registry.loader", + service = org.wso2.carbon.registry.core.service.TenantRegistryLoader.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetTenantRegistryLoader") protected void setTenantRegistryLoader(TenantRegistryLoader tenantRegistryLoader) { JWTClientExtensionDataHolder.getInstance().setTenantRegistryLoader(tenantRegistryLoader); } @@ -105,6 +99,12 @@ public class JWTClientExtensionServiceComponent { JWTClientExtensionDataHolder.getInstance().setTenantRegistryLoader(null); } + @Reference( + name = "tenant.index.loader", + service = org.wso2.carbon.registry.indexing.service.TenantIndexingLoader.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetIndexLoader") protected void setIndexLoader(TenantIndexingLoader indexLoader) { if (indexLoader != null && log.isDebugEnabled()) { log.debug("IndexLoader service initialized"); @@ -121,6 +121,12 @@ public class JWTClientExtensionServiceComponent { * * @param realmService An instance of RealmService */ + @Reference( + name = "realm.service", + service = org.wso2.carbon.user.core.service.RealmService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRealmService") protected void setRealmService(RealmService realmService) { if (log.isDebugEnabled()) { log.debug("Setting Realm Service"); diff --git a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/JWTClientManagerServiceImpl.java b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/JWTClientManagerServiceImpl.java index c36de4377e..cc926bc7de 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/JWTClientManagerServiceImpl.java +++ b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/JWTClientManagerServiceImpl.java @@ -18,11 +18,6 @@ package io.entgra.device.mgt.core.identity.jwt.client.extension.service; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.identity.jwt.client.extension.JWTClient; import io.entgra.device.mgt.core.identity.jwt.client.extension.constant.JWTConstants; import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.JWTConfig; @@ -30,6 +25,11 @@ import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClie import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientConfigurationException; import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; import io.entgra.device.mgt.core.identity.jwt.client.extension.util.JWTClientUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; diff --git a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/util/JWTClientUtil.java b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/util/JWTClientUtil.java index 4e43a38722..e2e5d30bb4 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/util/JWTClientUtil.java +++ b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/util/JWTClientUtil.java @@ -24,6 +24,11 @@ import com.nimbusds.jose.JWSSigner; import com.nimbusds.jose.crypto.RSASSASigner; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; +import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.JWTConfig; +import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientConfigurationException; +import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; +import io.entgra.device.mgt.core.identity.jwt.client.extension.internal.JWTClientExtensionDataHolder; +import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpResponse; @@ -36,11 +41,6 @@ import org.apache.http.util.EntityUtils; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.core.util.KeyStoreManager; -import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.JWTConfig; -import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientConfigurationException; -import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; -import io.entgra.device.mgt.core.identity.jwt.client.extension.internal.JWTClientExtensionDataHolder; -import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; @@ -48,19 +48,10 @@ import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.TenantRegistryLoader; import org.wso2.carbon.utils.CarbonUtils; -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; +import java.io.*; import java.net.URI; import java.net.URL; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.security.UnrecoverableKeyException; +import java.security.*; import java.security.cert.CertificateException; import java.security.interfaces.RSAPrivateKey; import java.util.Date; @@ -227,8 +218,7 @@ public class JWTClientUtil { long nbf = currentTimeMillis + jwtConfig.getValidityPeriodFromCurrentTime() * 60 * 1000; String jti = jwtConfig.getJti(); if (jti == null) { - String defaultTokenId = currentTimeMillis + "" + new SecureRandom().nextInt(); - jti = defaultTokenId; + jti = currentTimeMillis + "" + new SecureRandom().nextInt(); } List aud = jwtConfig.getAudiences(); //set up the basic claims @@ -282,8 +272,7 @@ public class JWTClientUtil { JWSSigner signer = new RSASSASigner(rsaPrivateKey); SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet.build()); signedJWT.sign(signer); - String assertion = signedJWT.serialize(); - return assertion; + return signedJWT.serialize(); } catch (KeyStoreException e) { throw new JWTClientException("Failed loading the keystore.", e); } catch (IOException e) { diff --git a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/JWTClientManagerServiceTest.java b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/JWTClientManagerServiceTest.java index a3d05da022..183241b85a 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/JWTClientManagerServiceTest.java +++ b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/JWTClientManagerServiceTest.java @@ -17,14 +17,14 @@ */ package io.entgra.device.mgt.core.identity.jwt.client.extension.service; +import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientConfigurationException; +import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; +import io.entgra.device.mgt.core.identity.jwt.client.extension.service.common.BaseJWTClientManagerExtTest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientConfigurationException; -import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; -import io.entgra.device.mgt.core.identity.jwt.client.extension.service.common.BaseJWTClientManagerExtTest; import java.util.Properties; diff --git a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/JWTClientTest.java b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/JWTClientTest.java index 6244bb7aed..beb7db9962 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/JWTClientTest.java +++ b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/JWTClientTest.java @@ -17,6 +17,11 @@ */ package io.entgra.device.mgt.core.identity.jwt.client.extension.service; +import io.entgra.device.mgt.core.identity.jwt.client.extension.JWTClient; +import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.AccessTokenInfo; +import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.JWTConfig; +import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; +import io.entgra.device.mgt.core.identity.jwt.client.extension.util.JWTClientUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpResponse; @@ -30,11 +35,6 @@ import org.testng.IObjectFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; -import io.entgra.device.mgt.core.identity.jwt.client.extension.JWTClient; -import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.AccessTokenInfo; -import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.JWTConfig; -import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; -import io.entgra.device.mgt.core.identity.jwt.client.extension.util.JWTClientUtil; import java.io.IOException; import java.security.KeyManagementException; @@ -43,9 +43,10 @@ import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; import java.util.Properties; +import org.powermock.modules.testng.PowerMockTestCase; @PrepareForTest(JWTClientUtil.class) -public class JWTClientTest { +public class JWTClientTest extends PowerMockTestCase{ private static final Log log = LogFactory.getLog(JWTClientTest.class); @ObjectFactory diff --git a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/JWTClientUtilTest.java b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/JWTClientUtilTest.java index 0223602fa2..587e9204b0 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/JWTClientUtilTest.java +++ b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/JWTClientUtilTest.java @@ -17,6 +17,9 @@ */ package io.entgra.device.mgt.core.identity.jwt.client.extension.service; +import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.JWTConfig; +import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; +import io.entgra.device.mgt.core.identity.jwt.client.extension.util.JWTClientUtil; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; @@ -29,9 +32,6 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.JWTConfig; -import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; -import io.entgra.device.mgt.core.identity.jwt.client.extension.util.JWTClientUtil; import org.wso2.carbon.registry.core.exceptions.RegistryException; import java.io.ByteArrayInputStream; diff --git a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/common/BaseJWTClientManagerExtTest.java b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/common/BaseJWTClientManagerExtTest.java index 78d9893f4b..3c8682c4a9 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/common/BaseJWTClientManagerExtTest.java +++ b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/java/io/entgra/device/mgt/core/identity/jwt/client/extension/service/common/BaseJWTClientManagerExtTest.java @@ -17,13 +17,13 @@ */ package io.entgra.device.mgt.core.identity.jwt.client.extension.service.common; +import io.entgra.device.mgt.core.identity.jwt.client.extension.internal.JWTClientExtensionDataHolder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeSuite; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.identity.jwt.client.extension.internal.JWTClientExtensionDataHolder; import org.wso2.carbon.registry.core.config.RegistryContext; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.internal.RegistryDataHolder; diff --git a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/resources/user-test/user-mgt-registry-test.xml b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/resources/user-test/user-mgt-registry-test.xml index fc32a2698d..96fd6acfff 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/resources/user-test/user-mgt-registry-test.xml +++ b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/test/resources/user-test/user-mgt-registry-test.xml @@ -27,7 +27,7 @@ everyone false 500 - jdbc:h2:target/databasetest/CARBON_TEST + jdbc:h2:./target/databasetest/CARBON_TEST org.h2.Driver 50 60000 diff --git a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/pom.xml b/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/pom.xml deleted file mode 100644 index 3024205c00..0000000000 --- a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/pom.xml +++ /dev/null @@ -1,152 +0,0 @@ - - - - - - identity-extensions - io.entgra.device.mgt.core - 5.0.0-SNAPSHOT - - - 4.0.0 - bundle - WSO2 Carbon - OAuth Back End Authenticator - org.wso2.carbon.identity.authenticator.backend.oauth - - - - org.wso2.carbon - org.wso2.carbon.utils - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.base - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.core - - - org.wso2.carbon - org.wso2.carbon.core - - - org.wso2.carbon - org.wso2.carbon.logging - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.application.authentication.framework - - - org.wso2.carbon - org.wso2.carbon.core.services - - - org.wso2.carbon.identity.inbound.auth.oauth2 - org.wso2.carbon.identity.oauth - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.application.common - - - org.wso2.carbon.identity.inbound.auth.oauth2 - org.wso2.carbon.identity.oauth.stub - - - commons-codec.wso2 - commons-codec - - - - - - - org.apache.felix - maven-scr-plugin - - - org.apache.felix - maven-bundle-plugin - 1.4.0 - true - - - ${project.artifactId} - ${project.artifactId} - ${io.entgra.device.mgt.core.version} - OAuth Authenticator Bundle - - org.wso2.carbon.identity.authenticator.backend.oauth.internal - - - !org.wso2.carbon.identity.authenticator.backend.oauth.internal, - org.wso2.carbon.identity.authenticator.backend.oauth.* - - - org.wso2.carbon.identity.oauth2.*, - javax.servlet.http, - org.apache.axis2.client, - org.apache.axis2.context, - org.apache.axis2.transport.http, - org.apache.commons.httpclient, - org.apache.commons.logging, - org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}", - org.osgi.framework, - org.osgi.service.component, - org.wso2.carbon.core.security, - org.wso2.carbon.core.services.authentication, - org.wso2.carbon.utils.multitenancy, - org.wso2.carbon.base, - org.wso2.carbon.utils - - - - - - org.jacoco - jacoco-maven-plugin - - ${basedir}/target/coverage-reports/jacoco-unit.exec - - - - jacoco-initialize - - prepare-agent - - - - jacoco-site - test - - report - - - ${basedir}/target/coverage-reports/jacoco-unit.exec - ${basedir}/target/coverage-reports/site - - - - - - - - diff --git a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/AuthenticatorException.java b/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/AuthenticatorException.java deleted file mode 100755 index 38cf6b178a..0000000000 --- a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/AuthenticatorException.java +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you 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.wso2.carbon.identity.authenticator.backend.oauth; - -/** - * Custom exception for backend OAuth authentication - */ -@SuppressWarnings("unused") -public class AuthenticatorException extends Exception { - - private static final long serialVersionUID = 1L; - - public AuthenticatorException(String message) { - super(message); - } - - public AuthenticatorException(Throwable e) { - super(e); - } - - public AuthenticatorException(String message, Throwable e) { - super(message, e); - } -} diff --git a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticator.java b/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticator.java deleted file mode 100755 index b1d41dd9e6..0000000000 --- a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticator.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.identity.authenticator.backend.oauth; - -import org.apache.axis2.context.MessageContext; -import org.apache.axis2.transport.http.HTTPConstants; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.core.security.AuthenticatorsConfiguration; -import org.wso2.carbon.core.services.authentication.CarbonServerAuthenticator; -import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationResponse; -import org.wso2.carbon.utils.ServerConstants; -import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator; -import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidatorFactory; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import java.rmi.RemoteException; - -/** - * This is a custom back end authenticator for enable OAuth token authentication for admin services - */ -public class OauthAuthenticator implements CarbonServerAuthenticator { - - private static final Log log = LogFactory.getLog(OauthAuthenticator.class); - private static final int PRIORITY = 5; - private static final int ACCESS_TOKEN_INDEX = 1; - private OAuth2TokenValidator tokenValidator; - - public OauthAuthenticator() { - try { - tokenValidator = OAuthValidatorFactory.getValidator(); - } catch (IllegalArgumentException e) { - log.error("Failed to initialise Authenticator", e); - } - } - - /** - * Checks whether the authentication of the context can be handled using this authenticator. - * - * @param messageContext containing the request need to be authenticated. - * @return boolean indicating whether the request can be authenticated by this Authenticator. - */ - public boolean isHandle(MessageContext messageContext) { - HttpServletRequest httpServletRequest = getHttpRequest(messageContext); - if (httpServletRequest != null) { - String headerValue = httpServletRequest.getHeader(HTTPConstants.HEADER_AUTHORIZATION); - if (headerValue != null && !headerValue.trim().isEmpty()) { - String[] headerPart = headerValue.trim().split(OauthAuthenticatorConstants.SPLITING_CHARACTOR); - if (OauthAuthenticatorConstants.AUTHORIZATION_HEADER_PREFIX_BEARER.equals(headerPart[0])) { - return true; - } - } else if (httpServletRequest.getParameter(OauthAuthenticatorConstants.BEARER_TOKEN_IDENTIFIER) != null) { - return true; - } - } - return false; - } - - /** - * Authenticates the user using the provided OAuth token and returns the status as a boolean. - * Sets the tenant domain and tenant friendly username to the session as attributes. - * - * @param messageContext containing the request need to be authenticated. - * @return boolean indicating the authentication status. - */ - public boolean isAuthenticated(MessageContext messageContext) { - HttpServletRequest httpServletRequest = getHttpRequest(messageContext); - String headerValue = httpServletRequest.getHeader(HTTPConstants.HEADER_AUTHORIZATION); - String[] headerPart = headerValue.trim().split(OauthAuthenticatorConstants.SPLITING_CHARACTOR); - String accessToken = headerPart[ACCESS_TOKEN_INDEX]; - OAuthValidationResponse response = null; - try { - response = tokenValidator.validateToken(accessToken); - } catch (RemoteException e) { - log.error("Failed to validate the OAuth token provided.", e); - } - if (response != null && response.isValid()) { - HttpSession session; - if ((session = httpServletRequest.getSession(false)) != null) { - session.setAttribute(MultitenantConstants.TENANT_DOMAIN, response.getTenantDomain()); - session.setAttribute(ServerConstants.USER_LOGGED_IN, response.getUserName()); - if (log.isDebugEnabled()) { - log.debug("Authentication successful for " + session.getAttribute(ServerConstants.USER_LOGGED_IN)); - } - } - return true; - } - if (log.isDebugEnabled()) { - log.debug("Authentication failed.Illegal attempt from session " + httpServletRequest.getSession().getId()); - } - return false; - } - - /** - * this method is currently not implemented. - * - * @param messageContext containing the request need to be authenticated. - * @return boolean - */ - public boolean authenticateWithRememberMe(MessageContext messageContext) { - throw new UnsupportedOperationException(); - } - - /** - * @return string Authenticator name. - */ - public String getAuthenticatorName() { - return OauthAuthenticatorConstants.AUTHENTICATOR_NAME; - } - - /** - * @return int priority of the authenticator. - */ - public int getPriority() { - return PRIORITY; - } - - /** - * @return boolean true for enable or otherwise for disable status. - */ - public boolean isDisabled() { - AuthenticatorsConfiguration authenticatorsConfiguration = AuthenticatorsConfiguration.getInstance(); - AuthenticatorsConfiguration.AuthenticatorConfig authenticatorConfig = authenticatorsConfiguration. - getAuthenticatorConfig(OauthAuthenticatorConstants.AUTHENTICATOR_NAME); - return authenticatorConfig.isDisabled(); - } - - /** - * Retrieve HTTP Servlet Request form thr Message Context. - * - * @param messageContext Containing the Servlet Request for backend authentication. - * @return HTTPServletRequest. - */ - private HttpServletRequest getHttpRequest(MessageContext messageContext) { - return (HttpServletRequest) messageContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); - } - -} diff --git a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticatorConstants.java b/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticatorConstants.java deleted file mode 100755 index 66e96101a8..0000000000 --- a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticatorConstants.java +++ /dev/null @@ -1,29 +0,0 @@ -/* -* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you 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.wso2.carbon.identity.authenticator.backend.oauth; - -public class OauthAuthenticatorConstants { - public static final String AUTHORIZATION_HEADER_PREFIX_BEARER = "Bearer"; - public static final String AUTHORIZATION_HEADER_PREFIX_BASIC = "Basic"; - public static final String BEARER_TOKEN_TYPE = "bearer"; - public static final String BEARER_TOKEN_IDENTIFIER = "token"; - public static final String AUTHENTICATOR_NAME = "OAuthAuthenticator"; - public static final String SPLITING_CHARACTOR = " "; - public static final String OAUTH_ENDPOINT_POSTFIX = - "/services/OAuth2TokenValidationService.OAuth2TokenValidationServiceHttpsSoap12Endpoint/"; -} diff --git a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/internal/OAuthAuthenticatorDataHolder.java b/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/internal/OAuthAuthenticatorDataHolder.java deleted file mode 100644 index 202568c4a5..0000000000 --- a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/internal/OAuthAuthenticatorDataHolder.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.identity.authenticator.backend.oauth.internal; - -import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; - -/** - * DataHolder of Backend OAuth Authenticator component. - */ -public class OAuthAuthenticatorDataHolder { - - private OAuth2TokenValidationService oAuth2TokenValidationService; - - private static OAuthAuthenticatorDataHolder thisInstance = new OAuthAuthenticatorDataHolder(); - - private OAuthAuthenticatorDataHolder() {} - - public static OAuthAuthenticatorDataHolder getInstance() { - return thisInstance; - } - - public OAuth2TokenValidationService getOAuth2TokenValidationService() { - if (oAuth2TokenValidationService == null) { - throw new IllegalStateException("OAuth2TokenValidation service is not initialized properly"); - } - return oAuth2TokenValidationService; - } - - public void setOAuth2TokenValidationService( - OAuth2TokenValidationService oAuth2TokenValidationService) { - this.oAuth2TokenValidationService = oAuth2TokenValidationService; - } -} \ No newline at end of file diff --git a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/internal/OAuthAuthenticatorServiceComponent.java b/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/internal/OAuthAuthenticatorServiceComponent.java deleted file mode 100755 index 0da3fa41ef..0000000000 --- a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/internal/OAuthAuthenticatorServiceComponent.java +++ /dev/null @@ -1,79 +0,0 @@ -/* -* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you 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.wso2.carbon.identity.authenticator.backend.oauth.internal; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.framework.BundleContext; -import org.osgi.service.component.ComponentContext; -import org.wso2.carbon.core.services.authentication.CarbonServerAuthenticator; -import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticator; -import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; - -/** - * @scr.component name="org.wso2.carbon.identity.backend.oauth.authenticator" immediate="true" - * @scr.reference name="identity.oauth2.validation.service" - * interface="org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService" - * cardinality="1..1" - * policy="dynamic" - * bind="setOAuth2ValidationService" - * unbind="unsetOAuth2ValidationService" - */ -public class OAuthAuthenticatorServiceComponent { - - private static final Log log = LogFactory.getLog(OAuthAuthenticatorServiceComponent.class); - - @SuppressWarnings("unused") - protected void activate(ComponentContext componentContext) { - if (log.isDebugEnabled()) { - log.debug("Starting Backend OAuthAuthenticator Framework Bundle"); - } - } - - @SuppressWarnings("unused") - protected void deactivate(ComponentContext componentContext) { - //do nothing - } - - /** - * Sets OAuth2TokenValidation Service. - * - * @param tokenValidationService An instance of OAuth2TokenValidationService. - */ - @SuppressWarnings("unused") - protected void setOAuth2ValidationService(OAuth2TokenValidationService tokenValidationService) { - if (log.isDebugEnabled()) { - log.debug("Setting OAuth2TokenValidationService Service"); - } - OAuthAuthenticatorDataHolder.getInstance().setOAuth2TokenValidationService(tokenValidationService); - } - - /** - * Unsets OAuth2TokenValidation Service. - * - * @param tokenValidationService An instance of OAuth2TokenValidationService - */ - @SuppressWarnings("unused") - protected void unsetOAuth2ValidationService(OAuth2TokenValidationService tokenValidationService) { - if (log.isDebugEnabled()) { - log.debug("Unsetting OAuth2TokenValidationService Service"); - } - OAuthAuthenticatorDataHolder.getInstance().setOAuth2TokenValidationService(null); - } -} \ No newline at end of file diff --git a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuth2TokenValidator.java b/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuth2TokenValidator.java deleted file mode 100755 index 1dbbd0fb68..0000000000 --- a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuth2TokenValidator.java +++ /dev/null @@ -1,35 +0,0 @@ -/* -* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you 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.wso2.carbon.identity.authenticator.backend.oauth.validator; - -import java.rmi.RemoteException; - -/** - * Declares the contract for OAuth2TokenValidator implementations. - */ -public interface OAuth2TokenValidator { - - /** - * This method gets a string accessToken and validates it and generate the OAuth2ClientApplicationDTO - * containing the validity and user details if valid. - * - * @param accessToken which need to be validated. - * @return OAuthValidationResponse with the validated results. - */ - OAuthValidationResponse validateToken(String accessToken) throws RemoteException; -} diff --git a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidationResponse.java b/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidationResponse.java deleted file mode 100755 index 8804924a4c..0000000000 --- a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidationResponse.java +++ /dev/null @@ -1,59 +0,0 @@ -/* -* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you 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.wso2.carbon.identity.authenticator.backend.oauth.validator; - -/** - * This class holds the authenticated user information after the OAuth2 token is validated. - */ -@SuppressWarnings("unused") -public class OAuthValidationResponse { - - private String userName; - private String tenantDomain; - private boolean isValid; - - public OAuthValidationResponse(String userName, String tenantDomain, boolean isValid) { - this.userName = userName; - this.tenantDomain = tenantDomain; - this.isValid = isValid; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public String getTenantDomain() { - return tenantDomain; - } - - public void setTenantDomain(String tenantDomain) { - this.tenantDomain = tenantDomain; - } - - public boolean isValid() { - return isValid; - } - - public void setIsValid(boolean isValid) { - this.isValid = isValid; - } -} \ No newline at end of file diff --git a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidatorFactory.java b/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidatorFactory.java deleted file mode 100755 index 8e0697e9db..0000000000 --- a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidatorFactory.java +++ /dev/null @@ -1,68 +0,0 @@ -/* -* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you 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.wso2.carbon.identity.authenticator.backend.oauth.validator; - -import org.wso2.carbon.core.security.AuthenticatorsConfiguration; -import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorConstants; -import org.wso2.carbon.identity.authenticator.backend.oauth.validator.impl.ExternalOAuthValidator; -import org.wso2.carbon.identity.authenticator.backend.oauth.validator.impl.LocalOAuthValidator; - -/** - * The class validate the configurations and provide the most suitable implementation according to the configuration. - * Factory class for OAuthValidator. - */ -public class OAuthValidatorFactory { - - private static final String AUTHENTICATOR_CONFIG_IS_REMOTE = "isRemote"; - private static final String AUTHENTICATOR_CONFIG_HOST_URL = "hostURL"; - private static final String AUTHENTICATOR_CONFIG_ADMIN_USERNAME = "adminUsername"; - private static final String AUTHENTICATOR_CONFIG_ADMIN_PASSWORD = "adminPassword"; - - /** - * The method check the configuration and provide the appropriate implementation for OAuth2TokenValidator - * - * @return OAuth2TokenValidator - */ - public static OAuth2TokenValidator getValidator() throws IllegalArgumentException { - AuthenticatorsConfiguration authenticatorsConfiguration = AuthenticatorsConfiguration.getInstance(); - AuthenticatorsConfiguration.AuthenticatorConfig authenticatorConfig = authenticatorsConfiguration. - getAuthenticatorConfig(OauthAuthenticatorConstants.AUTHENTICATOR_NAME); - boolean isRemote; - String hostUrl; - String adminUserName; - String adminPassword; - if (authenticatorConfig != null && authenticatorConfig.getParameters() != null) { - isRemote = Boolean.parseBoolean(authenticatorConfig.getParameters().get( - AUTHENTICATOR_CONFIG_IS_REMOTE)); - hostUrl = authenticatorConfig.getParameters().get(AUTHENTICATOR_CONFIG_HOST_URL); - adminUserName = authenticatorConfig.getParameters().get(AUTHENTICATOR_CONFIG_ADMIN_USERNAME); - adminPassword = authenticatorConfig.getParameters().get(AUTHENTICATOR_CONFIG_ADMIN_PASSWORD); - } else { - throw new IllegalArgumentException("Configuration parameters need to be defined in Authenticators.xml"); - } - if (isRemote) { - if (!(hostUrl == null || hostUrl.trim().isEmpty())) { - hostUrl = hostUrl + OauthAuthenticatorConstants.OAUTH_ENDPOINT_POSTFIX; - return new ExternalOAuthValidator(hostUrl, adminUserName, adminPassword); - } else { - throw new IllegalArgumentException("Remote server name and ip both can't be empty"); - } - } - return new LocalOAuthValidator(); - } -} diff --git a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java b/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java deleted file mode 100755 index c3d246bb16..0000000000 --- a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java +++ /dev/null @@ -1,95 +0,0 @@ -/* -* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you 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.wso2.carbon.identity.authenticator.backend.oauth.validator.impl; - -import org.apache.axis2.client.Options; -import org.apache.axis2.client.ServiceClient; -import org.apache.axis2.transport.http.HTTPConstants; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.httpclient.Header; -import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorConstants; -import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator; -import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationResponse; -import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; -import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO; -import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_OAuth2AccessToken; -import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; - -import java.rmi.RemoteException; -import java.util.ArrayList; -import java.util.List; - -/** - * Handles the Authentication form external IDP servers. Currently supports WSO2 IS only. - */ -public class ExternalOAuthValidator implements OAuth2TokenValidator{ - - private String hostURL; - private String adminUserName; - private String adminPassword; - - public ExternalOAuthValidator(String hostURL, String adminUserName, String adminPassword) { - this.hostURL = hostURL; - this.adminUserName = adminUserName; - this.adminPassword = adminPassword; - } - /** - * This method gets a string accessToken and validates it and generate the OAuth2ClientApplicationDTO - * containing the validity and user details if valid. - * - * @param token which need to be validated. - * @return OAuthValidationResponse with the validated results. - */ - public OAuthValidationResponse validateToken(String token) throws RemoteException { - OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO(); - OAuth2TokenValidationRequestDTO_OAuth2AccessToken accessToken = - new OAuth2TokenValidationRequestDTO_OAuth2AccessToken(); - accessToken.setTokenType(OauthAuthenticatorConstants.BEARER_TOKEN_TYPE); - accessToken.setIdentifier(token); - validationRequest.setAccessToken(accessToken); - OAuth2TokenValidationServiceStub tokenValidationService = - new OAuth2TokenValidationServiceStub(hostURL); - ServiceClient client = tokenValidationService._getServiceClient(); - Options options = client.getOptions(); - List

headerList = new ArrayList<>(); - Header header = new Header(); - header.setName(HTTPConstants.HEADER_AUTHORIZATION); - header.setValue(OauthAuthenticatorConstants.AUTHORIZATION_HEADER_PREFIX_BASIC + " " + getBasicAuthCredentials()); - headerList.add(header); - options.setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_HEADERS, headerList); - client.setOptions(options); - OAuth2TokenValidationResponseDTO tokenValidationResponse = tokenValidationService. - findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse(); - boolean isValid = tokenValidationResponse.getValid(); - String userName = null; - String tenantDomain = null; - if (isValid) { - userName = MultitenantUtils.getTenantAwareUsername( - tokenValidationResponse.getAuthorizedUser()); - tenantDomain = MultitenantUtils. - getTenantDomain(tokenValidationResponse.getAuthorizedUser()); - } - return new OAuthValidationResponse(userName,tenantDomain,isValid); - } - - private String getBasicAuthCredentials() { - byte[] bytesEncoded = Base64.encodeBase64((adminUserName + ":" + adminPassword).getBytes()); - return new String(bytesEncoded); - } -} diff --git a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java b/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java deleted file mode 100755 index 4182917f30..0000000000 --- a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java +++ /dev/null @@ -1,60 +0,0 @@ -/* -* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you 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.wso2.carbon.identity.authenticator.backend.oauth.validator.impl; - -import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorConstants; -import org.wso2.carbon.identity.authenticator.backend.oauth.internal.OAuthAuthenticatorDataHolder; -import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator; -import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationResponse; -import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; -import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO; -import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; - -/** - * Handles the authentication using the inbuilt IS features. - */ -public class LocalOAuthValidator implements OAuth2TokenValidator { - /** - * This method gets a string accessToken and validates it and generate the OAuth2ClientApplicationDTO - * containing the validity and user details if valid. - * - * @param token which need to be validated. - * @return OAuthValidationResponse with the validated results. - */ - public OAuthValidationResponse validateToken(String token) { - OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO(); - OAuth2TokenValidationRequestDTO.OAuth2AccessToken accessToken = - validationRequest.new OAuth2AccessToken(); - accessToken.setTokenType(OauthAuthenticatorConstants.BEARER_TOKEN_TYPE); - accessToken.setIdentifier(token); - validationRequest.setAccessToken(accessToken); - OAuth2TokenValidationResponseDTO tokenValidationResponse = OAuthAuthenticatorDataHolder.getInstance(). - getOAuth2TokenValidationService().findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse(); - boolean isValid = tokenValidationResponse.isValid(); - String userName = null; - String tenantDomain = null; - if (isValid) { - userName = MultitenantUtils.getTenantAwareUsername( - tokenValidationResponse.getAuthorizedUser()); - tenantDomain = - MultitenantUtils.getTenantDomain(tokenValidationResponse.getAuthorizedUser()); - } - return new OAuthValidationResponse(userName, tenantDomain, isValid); - } -} diff --git a/components/identity-extensions/pom.xml b/components/identity-extensions/pom.xml index 312b3ca244..ced68c877b 100644 --- a/components/identity-extensions/pom.xml +++ b/components/identity-extensions/pom.xml @@ -30,7 +30,7 @@ identity-extensions pom WSO2 Carbon - Identity Extensions Component - http://wso2.org + https://entgra.io io.entgra.device.mgt.core.device.mgt.oauth.extensions diff --git a/components/logger/io.entgra.device.mgt.core.notification.logger/pom.xml b/components/logger/io.entgra.device.mgt.core.notification.logger/pom.xml index ee50ab3265..dcf1f39304 100644 --- a/components/logger/io.entgra.device.mgt.core.notification.logger/pom.xml +++ b/components/logger/io.entgra.device.mgt.core.notification.logger/pom.xml @@ -33,8 +33,9 @@ - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api + provided org.testng @@ -44,12 +45,16 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.device.mgt.extensions.logger + + org.slf4j + slf4j-ext + - 8 - 8 - UTF-8 + + + @@ -57,6 +62,10 @@ org.apache.maven.plugins maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -69,10 +78,12 @@ ${io.entgra.device.mgt.core.version} Device Notification Logger Bundle - io.entgra.device.mgt.core.device.mgt.extensions.logger.*, - org.apache.commons.logging;version="[1.2,2)", - org.apache.log4j;version="[1.2,2)", - org.wso2.carbon.context;version="[4.4,5) + io.entgra.device.mgt.core.notification.logger, + io.entgra.device.mgt.core.notification.logger.util, + io.entgra.device.mgt.core.device.mgt.extensions.logger;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.extensions.logger.spi;version="[5.0,6)", + org.slf4j, + org.apache.commons.logging;version="[1.2,2)" io.entgra.device.mgt.core.notification.logger.* @@ -82,5 +93,4 @@ - \ No newline at end of file diff --git a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraAppInstallLoggerImpl.java b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraAppInstallLoggerImpl.java index e690c8118e..0dc701d37d 100644 --- a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraAppInstallLoggerImpl.java +++ b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraAppInstallLoggerImpl.java @@ -23,7 +23,8 @@ import io.entgra.device.mgt.core.notification.logger.AppInstallLogContext; import io.entgra.device.mgt.core.notification.logger.util.MDCContextUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.log4j.MDC; +import org.slf4j.MDC; + public class EntgraAppInstallLoggerImpl implements EntgraLogger { diff --git a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraDeviceConnectivityLoggerImpl.java b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraDeviceConnectivityLoggerImpl.java index d68ce4b0fb..d2f64fdbee 100644 --- a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraDeviceConnectivityLoggerImpl.java +++ b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraDeviceConnectivityLoggerImpl.java @@ -23,7 +23,8 @@ import io.entgra.device.mgt.core.notification.logger.DeviceConnectivityLogContex import io.entgra.device.mgt.core.notification.logger.util.MDCContextUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.log4j.MDC; +import org.slf4j.MDC; + public class EntgraDeviceConnectivityLoggerImpl implements EntgraLogger { diff --git a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraDeviceEnrolmentLoggerImpl.java b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraDeviceEnrolmentLoggerImpl.java index 3e86b94ecd..6c16ba628f 100644 --- a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraDeviceEnrolmentLoggerImpl.java +++ b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraDeviceEnrolmentLoggerImpl.java @@ -23,7 +23,8 @@ import io.entgra.device.mgt.core.notification.logger.DeviceEnrolmentLogContext; import io.entgra.device.mgt.core.notification.logger.util.MDCContextUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.log4j.MDC; +import org.slf4j.MDC; + public class EntgraDeviceEnrolmentLoggerImpl implements EntgraLogger { diff --git a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraDeviceLoggerImpl.java b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraDeviceLoggerImpl.java index 5d32f913f8..76e2865888 100644 --- a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraDeviceLoggerImpl.java +++ b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraDeviceLoggerImpl.java @@ -23,7 +23,8 @@ import io.entgra.device.mgt.core.notification.logger.DeviceLogContext; import io.entgra.device.mgt.core.notification.logger.util.MDCContextUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.log4j.MDC; +import org.slf4j.MDC; + public class EntgraDeviceLoggerImpl implements EntgraLogger { diff --git a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraGroupMgtLoggerImpl.java b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraGroupMgtLoggerImpl.java index 808213532b..f1896ce352 100644 --- a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraGroupMgtLoggerImpl.java +++ b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraGroupMgtLoggerImpl.java @@ -23,7 +23,8 @@ import io.entgra.device.mgt.core.notification.logger.GroupMgtLogContext; import io.entgra.device.mgt.core.notification.logger.util.MDCContextUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.log4j.MDC; +import org.slf4j.MDC; + public class EntgraGroupMgtLoggerImpl implements EntgraLogger { diff --git a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraPolicyLoggerImpl.java b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraPolicyLoggerImpl.java index b6868c8bc4..cd5be58405 100644 --- a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraPolicyLoggerImpl.java +++ b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraPolicyLoggerImpl.java @@ -23,7 +23,8 @@ import io.entgra.device.mgt.core.notification.logger.PolicyLogContext; import io.entgra.device.mgt.core.notification.logger.util.MDCContextUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.log4j.MDC; +import org.slf4j.MDC; + public class EntgraPolicyLoggerImpl implements EntgraLogger { diff --git a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraRoleMgtLoggerImpl.java b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraRoleMgtLoggerImpl.java index 0e9389339e..90c8008119 100644 --- a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraRoleMgtLoggerImpl.java +++ b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraRoleMgtLoggerImpl.java @@ -23,7 +23,8 @@ import io.entgra.device.mgt.core.notification.logger.RoleMgtLogContext; import io.entgra.device.mgt.core.notification.logger.util.MDCContextUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.log4j.MDC; +import org.slf4j.MDC; + public class EntgraRoleMgtLoggerImpl implements EntgraLogger { diff --git a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraUserLoginLoggerImpl.java b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraUserLoginLoggerImpl.java index edc2ad70fe..a1b1ed3670 100644 --- a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraUserLoginLoggerImpl.java +++ b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraUserLoginLoggerImpl.java @@ -23,7 +23,7 @@ import io.entgra.device.mgt.core.notification.logger.UserLoginLogContext; import io.entgra.device.mgt.core.notification.logger.util.MDCContextUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.log4j.MDC; +import org.slf4j.MDC; public class EntgraUserLoginLoggerImpl implements EntgraLogger { diff --git a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraUserMgtLoggerImpl.java b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraUserMgtLoggerImpl.java index 49f671504c..9c034778f2 100644 --- a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraUserMgtLoggerImpl.java +++ b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/impl/EntgraUserMgtLoggerImpl.java @@ -23,7 +23,8 @@ import io.entgra.device.mgt.core.notification.logger.UserMgtLogContext; import io.entgra.device.mgt.core.notification.logger.util.MDCContextUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.log4j.MDC; +import org.slf4j.MDC; + public class EntgraUserMgtLoggerImpl implements EntgraLogger { diff --git a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/util/MDCContextUtil.java b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/util/MDCContextUtil.java index adfb01ef4d..d9fb58fdcb 100644 --- a/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/util/MDCContextUtil.java +++ b/components/logger/io.entgra.device.mgt.core.notification.logger/src/main/java/io/entgra/device/mgt/core/notification/logger/util/MDCContextUtil.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.notification.logger.util; import io.entgra.device.mgt.core.notification.logger.*; -import org.apache.log4j.MDC; - +import org.slf4j.MDC; +// public final class MDCContextUtil { public static void populateDeviceMDCContext(final DeviceLogContext mdcContext) { @@ -54,7 +54,7 @@ public final class MDCContextUtil { MDC.put("IsUserRegistered", "Registered"); } if (mdcContext.isDeviceRegistered()) { - MDC.put("IsDeviceRegistered", mdcContext.isDeviceRegistered()); + MDC.put("IsDeviceRegistered", String.valueOf(mdcContext.isDeviceRegistered())); } if (mdcContext.getTenantDomain() != null) { MDC.put("TenantDomain", mdcContext.getTenantDomain()); diff --git a/components/logger/pom.xml b/components/logger/pom.xml index ce94ed8c7d..97de565b35 100644 --- a/components/logger/pom.xml +++ b/components/logger/pom.xml @@ -36,8 +36,6 @@ - 8 - 8 UTF-8 diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/pom.xml b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/pom.xml index ca39311fdb..158daff9f5 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/pom.xml +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/pom.xml @@ -37,10 +37,10 @@ org.apache.maven.plugins maven-compiler-plugin - - - org.apache.felix - maven-scr-plugin + + 1.8 + 1.8 + org.apache.felix @@ -54,33 +54,32 @@ IOT Operation Template Bundle io.entgra.device.mgt.core.operation.template.internal + com.google.common.cache;version="[32.1,33)";resolution:=optional, + com.google.gson;version="[2.9,3)", + io.entgra.device.mgt.core.device.mgt.common.exceptions;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.service;version="[5.0,6)", + io.entgra.device.mgt.core.operation.template.cache, + io.entgra.device.mgt.core.operation.template.dao, + io.entgra.device.mgt.core.operation.template.dao.impl, + io.entgra.device.mgt.core.operation.template.dao.impl.config, + io.entgra.device.mgt.core.operation.template.dao.impl.config.datasource, + io.entgra.device.mgt.core.operation.template.dao.impl.util, + io.entgra.device.mgt.core.operation.template.dto, + io.entgra.device.mgt.core.operation.template.exception, + io.entgra.device.mgt.core.operation.template.impl, + io.entgra.device.mgt.core.operation.template.spi, + io.entgra.device.mgt.core.operation.template.util, + javax.naming, + javax.sql, + javax.xml.bind.*;version="${javax.xml.bind.imp.pkg.version}", + javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}", + org.apache.commons.lang;version="[2.4,3)", + org.apache.commons.logging;version="[1.2,2)", org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.apache.commons.logging, - org.apache.commons.lang, - javax.xml, - javax.xml.stream, - javax.xml.bind.*;version="${javax.xml.bind.imp.pkg.version}", - javax.sql, - javax.xml.parsers; version=0.0.0, - org.w3c.dom, - com.google.gson.*, - javax.naming, - org.wso2.carbon.context, - org.wso2.carbon.base, - org.wso2.carbon.utils.*, - io.entgra.device.mgt.core.device.mgt.common.*, - io.entgra.device.mgt.core.device.mgt.core.*, - org.wso2.carbon.ndatasource.core, - org.wso2.carbon.registry.core, - org.wso2.carbon.registry.core.session, - org.wso2.carbon.registry.core.service, - org.wso2.carbon.registry.api, - io.entgra.device.mgt.core.device.mgt.extensions.license.mgt.registry, - javax.net.ssl, - org.wso2.carbon.core.util, - okhttp3, - com.google.common.cache.* + org.w3c.dom,org.wso2.carbon.ndatasource.core;version="[4.8,5)", + org.wso2.carbon.registry.core.service;version="[1.0,2)", + org.wso2.carbon.utils;version="[4.8,5)" !io.entgra.device.mgt.core.operation.template.internal, @@ -119,6 +118,10 @@ org.apache.maven.plugins maven-surefire-plugin + + --add-opens=java.xml/jdk.xml.internal=ALL-UNNAMED + --add-opens=java.base/jdk.internal.loader=ALL-UNNAMED + file:src/test/resources/carbon-home/repository/conf/log4j.properties @@ -126,11 +129,19 @@ src/test/resources/testng.xml + + org.ops4j.pax.logging + + + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + io.entgra.device.mgt.core io.entgra.device.mgt.core.device.mgt.common @@ -160,10 +171,6 @@ org.codehaus.woodstox wstx-asl - - - - org.wso2.carbon.analytics org.wso2.carbon.analytics.api @@ -234,28 +241,18 @@ - org.eclipse.osgi - org.eclipse.osgi - provided - - - com.h2database.wso2 - h2-database-engine + org.wso2.orbit.com.h2database + h2 test - - org.eclipse.osgi - org.eclipse.osgi.services - provided - org.wso2.carbon org.wso2.carbon.core provided - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api provided @@ -279,7 +276,7 @@ provided - org.apache.tomcat.wso2 + org.wso2.orbit.org.apache.tomcat jdbc-pool provided @@ -301,7 +298,7 @@ com.google.guava guava - ${guava.version} + ${google.guava.version} provided @@ -355,7 +352,7 @@ provided - javax.xml.bind + org.wso2.orbit.javax.xml.bind jaxb-api test diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/dao/OperationTemplateDAOFactory.java b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/dao/OperationTemplateDAOFactory.java index 4c4d096e6a..536f6f0235 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/dao/OperationTemplateDAOFactory.java +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/dao/OperationTemplateDAOFactory.java @@ -18,13 +18,13 @@ package io.entgra.device.mgt.core.operation.template.dao; +import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.operation.template.dao.impl.OperationTemplateDAOImpl; import io.entgra.device.mgt.core.operation.template.dao.impl.OperationTemplateMySQLDAOImpl; import io.entgra.device.mgt.core.operation.template.dao.impl.config.datasource.DataSourceConfig; import io.entgra.device.mgt.core.operation.template.util.ConnectionManagerUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; public class OperationTemplateDAOFactory { diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/dao/impl/OperationTemplateDAOImpl.java b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/dao/impl/OperationTemplateDAOImpl.java index 441521cba5..ae31685044 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/dao/impl/OperationTemplateDAOImpl.java +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/dao/impl/OperationTemplateDAOImpl.java @@ -39,6 +39,7 @@ import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + /** * Implementation for generic DB engines. */ diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/dao/impl/config/DeviceConfigurationManager.java b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/dao/impl/config/DeviceConfigurationManager.java index 0d35632763..01aa604460 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/dao/impl/config/DeviceConfigurationManager.java +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/dao/impl/config/DeviceConfigurationManager.java @@ -18,9 +18,9 @@ package io.entgra.device.mgt.core.operation.template.dao.impl.config; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.operation.template.dao.impl.util.OperationTemplateManagementUtil; import org.w3c.dom.Document; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.utils.CarbonUtils; import javax.xml.bind.JAXBContext; diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/dao/impl/util/OperationTemplateManagementUtil.java b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/dao/impl/util/OperationTemplateManagementUtil.java index b4ba139f6e..20e297e328 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/dao/impl/util/OperationTemplateManagementUtil.java +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/dao/impl/util/OperationTemplateManagementUtil.java @@ -18,9 +18,9 @@ package io.entgra.device.mgt.core.operation.template.dao.impl.util; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.operation.template.dto.OperationTemplateCacheKey; import org.w3c.dom.Document; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/impl/OperationTemplateServiceImpl.java b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/impl/OperationTemplateServiceImpl.java index 5bc0d1c238..9691c939a3 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/impl/OperationTemplateServiceImpl.java +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/impl/OperationTemplateServiceImpl.java @@ -31,8 +31,8 @@ import io.entgra.device.mgt.core.operation.template.exception.DBConnectionExcept import io.entgra.device.mgt.core.operation.template.exception.OperationTemplateManagementDAOException; import io.entgra.device.mgt.core.operation.template.exception.OperationTemplateMgtPluginException; import io.entgra.device.mgt.core.operation.template.spi.OperationTemplateService; -import io.entgra.device.mgt.core.operation.template.util.ConnectionManagerUtils; import io.entgra.device.mgt.core.operation.template.util.AssertUtils; +import io.entgra.device.mgt.core.operation.template.util.ConnectionManagerUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -216,8 +216,8 @@ public class OperationTemplateServiceImpl implements OperationTemplateService { throws OperationTemplateMgtPluginException { AssertUtils.hasText(deviceType, "Invalid device type."); try { - ConnectionManagerUtils.openDBConnection(); - return operationTemplateDAO.getAllOperationTemplates(deviceType); + ConnectionManagerUtils.openDBConnection(); + return operationTemplateDAO.getAllOperationTemplates(deviceType); } catch (DBConnectionException | OperationTemplateManagementDAOException e) { log.error(e.getMessage()); throw new OperationTemplateMgtPluginException(e.getMessage(), e); @@ -273,11 +273,12 @@ public class OperationTemplateServiceImpl implements OperationTemplateService { */ @Override public Set getOperationTemplateCodes(String deviceType, String subTypeId) - throws OperationTemplateMgtPluginException { + throws OperationTemplateMgtPluginException { try { - AssertUtils.hasText(subTypeId, "Invalid meter device subtype id: " + subTypeId); - AssertUtils.isTrue(Integer.valueOf(subTypeId)>0, "Invalid meter device subtype id: " + subTypeId); + AssertUtils.hasText(subTypeId, "Invalid device subtype id: " + subTypeId); + AssertUtils.isTrue(Integer.parseInt(subTypeId) > 0, + "Invalid device subtype id: " + subTypeId); AssertUtils.hasText(deviceType, "Invalid device type."); String key = OperationTemplateManagementUtil.setOperationTemplateCacheKey(deviceType, subTypeId); @@ -294,7 +295,6 @@ public class OperationTemplateServiceImpl implements OperationTemplateService { } /** - * * @param subTypeId * @param deviceType * @param operationCode @@ -303,18 +303,18 @@ public class OperationTemplateServiceImpl implements OperationTemplateService { private void validateGetOperationTemplate(String subTypeId, String deviceType, String operationCode) throws OperationTemplateMgtPluginException { - AssertUtils.hasText(subTypeId, "Invalid meter device subtype id: " + subTypeId); - AssertUtils.isTrue(Integer.valueOf(subTypeId)>0, "Invalid meter device subtype id: " + subTypeId); + AssertUtils.hasText(subTypeId, "Invalid device subtype id: " + subTypeId); + AssertUtils.isTrue(Integer.parseInt(subTypeId) > 0, "Invalid device subtype id: " + subTypeId); AssertUtils.hasText(operationCode, "Validation failed due to invalid operation code: " + operationCode); AssertUtils.hasText(deviceType, "Invalid device type."); - AssertUtils.isTrue(deviceType.equals("METER"), "Invalid device type. "); } /** * @param operationTemplate * @throws OperationTemplateMgtPluginException */ - private void validateAddOperationTemplate(OperationTemplate operationTemplate) throws OperationTemplateMgtPluginException { + private void validateAddOperationTemplate(OperationTemplate operationTemplate) + throws OperationTemplateMgtPluginException { AssertUtils.isNull(operationTemplate, "Operation Template can not be null"); AssertUtils.hasText(operationTemplate.getOperationDefinition(), "Operation definition can not be null"); diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/internal/OperationTemplateMgtDataHolder.java b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/internal/OperationTemplateMgtDataHolder.java index 1536feb87a..c0e8b1063b 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/internal/OperationTemplateMgtDataHolder.java +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/internal/OperationTemplateMgtDataHolder.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.operation.template.internal; -import io.entgra.device.mgt.core.operation.template.spi.OperationTemplateService; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import io.entgra.device.mgt.core.operation.template.spi.OperationTemplateService; import org.wso2.carbon.registry.core.service.RegistryService; /** diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/internal/OperationTemplateMgtServiceComponent.java b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/internal/OperationTemplateMgtServiceComponent.java index 0eae3ad301..50696cbd4c 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/internal/OperationTemplateMgtServiceComponent.java +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/internal/OperationTemplateMgtServiceComponent.java @@ -28,18 +28,12 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.ndatasource.core.DataSourceService; -/** - * @scr.component name="io.entgra.device.mgt.core.operation.template.internal.OperationTemplateMgtServiceComponent" immediate="true" - * immediate="true" - * @scr.reference name="org.wso2.carbon.ndatasource" - * interface="org.wso2.carbon.ndatasource.core.DataSourceService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDataSourceService" - * unbind="unsetDataSourceService" - */ +@Component( + name = "io.entgra.device.mgt.core.operation.template.internal.OperationTemplateMgtServiceComponent", + immediate = true) public class OperationTemplateMgtServiceComponent { private static final Log log = LogFactory.getLog(OperationTemplateMgtServiceComponent.class); @@ -48,6 +42,7 @@ public class OperationTemplateMgtServiceComponent { * * @param componentContext */ + @Activate protected void activate(ComponentContext componentContext) { if (log.isDebugEnabled()) { @@ -77,6 +72,7 @@ public class OperationTemplateMgtServiceComponent { * * @param componentContext */ + @Deactivate protected void deactivate(ComponentContext componentContext) { if (log.isDebugEnabled()) { log.debug("De-activating Operation Template Management Service Component"); @@ -94,6 +90,12 @@ public class OperationTemplateMgtServiceComponent { * * @param dataSourceService */ + @Reference( + name = "datasource.service", + service = org.wso2.carbon.ndatasource.core.DataSourceService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDataSourceService") protected void setDataSourceService(DataSourceService dataSourceService) { /* This is to avoid mobile device management component getting initialized before the underlying datasources are registered */ diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/util/ConnectionManagerUtils.java b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/util/ConnectionManagerUtils.java index 292690b24f..badb901565 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/util/ConnectionManagerUtils.java +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/util/ConnectionManagerUtils.java @@ -18,20 +18,19 @@ package io.entgra.device.mgt.core.operation.template.util; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; import io.entgra.device.mgt.core.operation.template.dao.impl.config.datasource.DataSourceConfig; import io.entgra.device.mgt.core.operation.template.dao.impl.config.datasource.JNDILookupDefinition; import io.entgra.device.mgt.core.operation.template.exception.DBConnectionException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import javax.naming.InitialContext; +import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.Hashtable; import java.util.List; -import javax.naming.InitialContext; -import javax.sql.DataSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; /** * Connection Manager Utils class. diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/ServiceNegativeTest.java b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/ServiceNegativeTest.java index 2c41d1ffc3..f85a69204f 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/ServiceNegativeTest.java +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/ServiceNegativeTest.java @@ -21,8 +21,8 @@ package io.entgra.device.mgt.core.operation.template; import io.entgra.device.mgt.core.operation.template.dto.OperationTemplate; import io.entgra.device.mgt.core.operation.template.exception.OperationTemplateMgtPluginException; import io.entgra.device.mgt.core.operation.template.impl.OperationTemplateServiceImpl; -import io.entgra.device.mgt.core.operation.template.spi.OperationTemplateService; import io.entgra.device.mgt.core.operation.template.mock.BaseOperationTemplatePluginTest; +import io.entgra.device.mgt.core.operation.template.spi.OperationTemplateService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.annotations.BeforeClass; @@ -49,7 +49,7 @@ public class ServiceNegativeTest extends BaseOperationTemplatePluginTest { @Test(description = "This method tests Add Operation template under negative circumstances while missing " + "required fields", expectedExceptions = {OperationTemplateMgtPluginException.class}, - expectedExceptionsMessageRegExp = "Invalid meter device subtype id: 0") + expectedExceptionsMessageRegExp = "Invalid device subtype id: 0") public void testAddOperationTemplates() throws OperationTemplateMgtPluginException { OperationTemplate operationTemplate = new OperationTemplate(); diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/BaseOperationTemplatePluginTest.java b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/BaseOperationTemplatePluginTest.java index 11ed63df6e..58c7e8b65f 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/BaseOperationTemplatePluginTest.java +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/BaseOperationTemplatePluginTest.java @@ -18,10 +18,13 @@ package io.entgra.device.mgt.core.operation.template.mock; +import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; import io.entgra.device.mgt.core.operation.template.DataSourceConfig; +import io.entgra.device.mgt.core.operation.template.TestUtils; import io.entgra.device.mgt.core.operation.template.dao.OperationTemplateDAOFactory; import io.entgra.device.mgt.core.operation.template.util.ConnectionManagerUtils; -import io.entgra.device.mgt.core.operation.template.TestUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tomcat.jdbc.pool.PoolProperties; @@ -32,9 +35,6 @@ import org.testng.annotations.Parameters; import org.w3c.dom.Document; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; import javax.sql.DataSource; import javax.xml.bind.JAXBContext; @@ -144,6 +144,7 @@ public abstract class BaseOperationTemplatePluginTest { conn = ConnectionManagerUtils.getDBConnection(); stmt = conn.createStatement(); stmt.executeUpdate("RUNSCRIPT FROM './src/test/resources/carbon-home/dbscripts/dm-db-h2.sql'"); + stmt.executeUpdate("RUNSCRIPT FROM './src/test/resources/carbon-home/dbscripts/insert-subtypes.sql'"); } finally { TestUtils.cleanupResources(conn, stmt, null); } diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/MockConnection.java b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/MockConnection.java index a29ad73fae..bd16dbac88 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/MockConnection.java +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/MockConnection.java @@ -18,21 +18,7 @@ package io.entgra.device.mgt.core.operation.template.mock; -import java.sql.CallableStatement; -import java.sql.SQLWarning; -import java.sql.Savepoint; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.Statement; -import java.sql.Clob; -import java.sql.Blob; -import java.sql.NClob; -import java.sql.SQLXML; -import java.sql.Struct; -import java.sql.Array; -import java.sql.SQLClientInfoException; -import java.sql.DatabaseMetaData; -import java.sql.SQLException; +import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Map; diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/MockDatabaseMetaData.java b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/MockDatabaseMetaData.java index 7320892182..fab59016ca 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/MockDatabaseMetaData.java +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/MockDatabaseMetaData.java @@ -20,11 +20,7 @@ package io.entgra.device.mgt.core.operation.template.mock; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.RowIdLifetime; -import java.sql.DatabaseMetaData; -import java.sql.SQLException; +import java.sql.*; public class MockDatabaseMetaData implements DatabaseMetaData { private final String url; diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/MockResultSet.java b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/MockResultSet.java index a77146b901..1549ac78b2 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/MockResultSet.java +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/MockResultSet.java @@ -22,21 +22,7 @@ import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; -import java.sql.ResultSet; -import java.sql.SQLWarning; -import java.sql.Date; -import java.sql.Time; -import java.sql.Timestamp; -import java.sql.Clob; -import java.sql.Blob; -import java.sql.NClob; -import java.sql.SQLXML; -import java.sql.Ref; -import java.sql.Array; -import java.sql.ResultSetMetaData; -import java.sql.RowId; -import java.sql.Statement; -import java.sql.SQLException; +import java.sql.*; import java.util.ArrayList; import java.util.Calendar; import java.util.List; diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/MockStatement.java b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/MockStatement.java index a749066de6..c4ced59a34 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/MockStatement.java +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/java/io/entgra/device/mgt/core/operation/template/mock/MockStatement.java @@ -22,23 +22,7 @@ import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLWarning; -import java.sql.Date; -import java.sql.Time; -import java.sql.Timestamp; -import java.sql.PreparedStatement; -import java.sql.ParameterMetaData; -import java.sql.Clob; -import java.sql.Blob; -import java.sql.NClob; -import java.sql.SQLXML; -import java.sql.Ref; -import java.sql.Array; -import java.sql.ResultSetMetaData; -import java.sql.RowId; -import java.sql.SQLException; +import java.sql.*; import java.util.ArrayList; import java.util.Calendar; import java.util.List; diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql index 17f334c78f..9b63adddad 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql @@ -23,7 +23,7 @@ CREATE TABLE IF NOT EXISTS DM_GROUP ( STATUS VARCHAR(50) DEFAULT NULL, DESCRIPTION TEXT DEFAULT NULL, OWNER VARCHAR(255) DEFAULT NULL, - PARENT_PATH VARCHAR(255) DEFAULT '/', + PARENT_PATH VARCHAR(255) DEFAULT NULL, TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (ID) ); @@ -42,7 +42,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE ( ID INTEGER auto_increment NOT NULL, DESCRIPTION TEXT DEFAULT NULL, NAME VARCHAR(100) DEFAULT NULL, - DEVICE_TYPE_ID INT(11) DEFAULT NULL, + DEVICE_TYPE_ID INT DEFAULT NULL, DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, TENANT_ID INTEGER DEFAULT 0, @@ -84,8 +84,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP ( CREATE TABLE IF NOT EXISTS DM_OPERATION ( ID INTEGER AUTO_INCREMENT NOT NULL, TYPE VARCHAR(50) NOT NULL, - CREATED_TIMESTAMP TIMESTAMP NOT NULL, - RECEIVED_TIMESTAMP TIMESTAMP NULL, + CREATED_TIMESTAMP BIGINT NOT NULL, + RECEIVED_TIMESTAMP BIGINT NULL, OPERATION_CODE VARCHAR(1000) NOT NULL, INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BLOB DEFAULT NULL, @@ -110,7 +110,19 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT uk_dm_device_enrolment UNIQUE (DEVICE_ID, OWNER, OWNERSHIP, TENANT_ID) ); - +CREATE TABLE IF NOT EXISTS DM_DEVICE_STATUS ( + ID INTEGER AUTO_INCREMENT NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, + DEVICE_ID INTEGER NOT NULL, + STATUS VARCHAR(50) DEFAULT NULL, + UPDATE_TIME TIMESTAMP DEFAULT NULL, + CHANGED_BY VARCHAR(255) NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_dm_device_status_device FOREIGN KEY (DEVICE_ID) REFERENCES + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_device_status_enrolment FOREIGN KEY (ENROLMENT_ID) REFERENCES + DM_ENROLMENT (ID) ON DELETE CASCADE ON UPDATE CASCADE +); CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING ( ID INTEGER AUTO_INCREMENT NOT NULL, ENROLMENT_ID INTEGER NOT NULL, @@ -178,17 +190,17 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE ( ); CREATE TABLE IF NOT EXISTS DM_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , + ID INT NOT NULL AUTO_INCREMENT , NAME VARCHAR(45) DEFAULT NULL , DESCRIPTION VARCHAR(1000) NULL, PAYLOAD_VERSION VARCHAR (45) NULL, - TENANT_ID INT(11) NOT NULL , - PROFILE_ID INT(11) NOT NULL , + TENANT_ID INT NOT NULL , + PROFILE_ID INT NOT NULL , OWNERSHIP_TYPE VARCHAR(45) NULL, COMPLIANCE VARCHAR(100) NULL, PRIORITY INT NOT NULL, - ACTIVE INT(2) NOT NULL, - UPDATED INT(1) NULL, + ACTIVE INT NOT NULL, + UPDATED INT NULL, POLICY_TYPE VARCHAR(45) NULL, PRIMARY KEY (ID) , CONSTRAINT FK_DM_PROFILE_DM_POLICY @@ -199,11 +211,11 @@ CREATE TABLE IF NOT EXISTS DM_POLICY ( ); CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , - DEVICE_ID INT(11) NOT NULL , - ENROLMENT_ID INT(11) NOT NULL, + ID INT NOT NULL AUTO_INCREMENT , + DEVICE_ID INT NOT NULL , + ENROLMENT_ID INT NOT NULL, DEVICE BLOB NOT NULL, - POLICY_ID INT(11) NOT NULL , + POLICY_ID INT NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_POLICY_DEVICE_POLICY FOREIGN KEY (POLICY_ID ) @@ -218,9 +230,9 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( ); CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( - ID INT(11) NOT NULL , + ID INT NOT NULL , DEVICE_TYPE VARCHAR(300) NOT NULL , - POLICY_ID INT(11) NOT NULL , + POLICY_ID INT NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_DEVICE_TYPE_POLICY FOREIGN KEY (POLICY_ID ) @@ -230,11 +242,11 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( ); CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( - ID INT(11) NOT NULL AUTO_INCREMENT, - PROFILE_ID INT(11) NOT NULL, + ID INT NOT NULL AUTO_INCREMENT, + PROFILE_ID INT NOT NULL, FEATURE_CODE VARCHAR(100) NOT NULL, DEVICE_TYPE VARCHAR(300) NOT NULL, - TENANT_ID INT(11) NOT NULL , + TENANT_ID INT NOT NULL , CONTENT BLOB NULL DEFAULT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES @@ -245,11 +257,11 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( ); CREATE TABLE IF NOT EXISTS DM_POLICY_CORRECTIVE_ACTION ( - ID INT(11) NOT NULL AUTO_INCREMENT, + ID INT NOT NULL AUTO_INCREMENT, ACTION_TYPE VARCHAR(45) NOT NULL, - CORRECTIVE_POLICY_ID INT(11) DEFAULT NULL, - POLICY_ID INT(11) NOT NULL, - FEATURE_ID INT(11) DEFAULT NULL, + CORRECTIVE_POLICY_ID INT DEFAULT NULL, + POLICY_ID INT NOT NULL, + FEATURE_ID INT DEFAULT NULL, IS_REACTIVE BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (ID), CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION @@ -260,9 +272,9 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CORRECTIVE_ACTION ( ); CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , + ID INT NOT NULL AUTO_INCREMENT , ROLE_NAME VARCHAR(45) NOT NULL , - POLICY_ID INT(11) NOT NULL , + POLICY_ID INT NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_ROLE_POLICY_POLICY FOREIGN KEY (POLICY_ID ) @@ -286,11 +298,11 @@ CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( ID INT NOT NULL AUTO_INCREMENT , DEVICE_ID INT NOT NULL , - ENROLMENT_ID INT(11) NOT NULL, + ENROLMENT_ID INT NOT NULL, POLICY_ID INT NOT NULL , POLICY_CONTENT TEXT NULL , TENANT_ID INT NOT NULL, - APPLIED TINYINT(1) NULL , + APPLIED TINYINT NULL , CREATED_TIME TIMESTAMP NULL , UPDATED_TIME TIMESTAMP NULL , APPLIED_TIME TIMESTAMP NULL , @@ -343,7 +355,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES ( CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( ID INT NOT NULL AUTO_INCREMENT, DEVICE_ID INT NOT NULL, - ENROLMENT_ID INT(11) NOT NULL, + ENROLMENT_ID INT NOT NULL, POLICY_ID INT NOT NULL, TENANT_ID INT NOT NULL, STATUS INT NULL, @@ -358,7 +370,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( ID INT NOT NULL AUTO_INCREMENT, POLICY_ID INT NOT NULL, DEVICE_TYPE VARCHAR(300) NOT NULL , - TENANT_ID INT(11) NOT NULL, + TENANT_ID INT NOT NULL, PRIMARY KEY (ID) ); @@ -387,7 +399,7 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION ( LOCATION_URL VARCHAR(100) DEFAULT NULL, IMAGE_URL VARCHAR(100) DEFAULT NULL, APP_PROPERTIES BLOB NULL, - MEMORY_USAGE INTEGER(10) NULL, + MEMORY_USAGE INTEGER NULL, IS_ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, DEVICE_ID INTEGER NOT NULL, ENROLMENT_ID INTEGER NOT NULL, @@ -407,6 +419,16 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION ( -- POLICY RELATED TABLES FINISHED -- +CREATE TABLE IF NOT EXISTS DM_APP_ICONS ( + ID INTEGER AUTO_INCREMENT NOT NULL, + ICON_PATH VARCHAR(150) DEFAULT NULL, + PACKAGE_NAME VARCHAR(150) NOT NULL, + VERSION VARCHAR(50) DEFAULT '1.1.0', + CREATED_TIMESTAMP TIMESTAMP NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY (ID) +); + -- NOTIFICATION TABLE -- CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( NOTIFICATION_ID INTEGER AUTO_INCREMENT NOT NULL, @@ -427,7 +449,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( DEVICE_ID INT NULL, ENROLMENT_ID INT NOT NULL, KEY_FIELD VARCHAR(45) NULL, - VALUE_FIELD VARCHAR(1000) NULL, + VALUE_FIELD VARCHAR(1500) NULL, PRIMARY KEY (ID), CONSTRAINT DM_DEVICE_INFO_DEVICE FOREIGN KEY (DEVICE_ID) @@ -456,7 +478,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( STATE VARCHAR(45) NULL, COUNTRY VARCHAR(45) NULL, GEO_HASH VARCHAR(45) NULL, - UPDATE_TIMESTAMP BIGINT(15) NOT NULL, + UPDATE_TIMESTAMP BIGINT NOT NULL, ALTITUDE DOUBLE NULL, SPEED FLOAT NULL, BEARING FLOAT NULL, @@ -493,8 +515,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( CPU_USAGE DECIMAL(5) NULL, TOTAL_RAM_MEMORY DECIMAL(30,3) NULL, AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL, - PLUGGED_IN INT(1) NULL, - UPDATE_TIMESTAMP BIGINT(15) NOT NULL, + PLUGGED_IN INT NULL, + UPDATE_TIMESTAMP BIGINT NOT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE FOREIGN KEY (DEVICE_ID) @@ -521,7 +543,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_HISTORY_LAST_SEVEN_DAYS LONGITUDE DOUBLE NULL, SPEED FLOAT NULL, HEADING FLOAT NULL, - TIMESTAMP BIGINT(15) NOT NULL, + TIMESTAMP BIGINT NOT NULL, GEO_HASH VARCHAR(45) NULL, DEVICE_OWNER VARCHAR(45) NULL, DEVICE_ALTITUDE DOUBLE NULL, @@ -590,8 +612,7 @@ CREATE TABLE IF NOT EXISTS DM_OTP_DATA ( CREATED_AT TIMESTAMP NOT NULL, EXPIRY_TIME INT NOT NULL DEFAULT 3600, IS_EXPIRED BOOLEAN DEFAULT false, - PRIMARY KEY (ID), - CONSTRAINT email_type_uk UNIQUE (EMAIL, EMAIL_TYPE) + PRIMARY KEY (ID) ); -- END OF DM_OTP_DATA TABLE -- @@ -727,52 +748,94 @@ CREATE TABLE IF NOT EXISTS DM_GEOFENCE_EVENT_MAPPING ( -- END OF DM_GEOFENCE_GROUP_MAPPING TABLE-- +-- DM_EXT_GROUP_MAPPING TABLE-- +CREATE TABLE IF NOT EXISTS DM_EXT_GROUP_MAPPING ( + ID INT NOT NULL AUTO_INCREMENT, + TRACCAR_GROUP_ID INT DEFAULT 0, + GROUP_ID INT NOT NULL, + TENANT_ID INT NOT NULL, + STATUS INT DEFAULT 0, + PRIMARY KEY (ID) +); +-- END OF DM_EXT_GROUP_MAPPING TABLE-- + +-- END OF DM_EXT_DEVICE_MAPPING TABLE-- +CREATE TABLE IF NOT EXISTS DM_EXT_DEVICE_MAPPING ( + ID INT NOT NULL AUTO_INCREMENT, + TRACCAR_DEVICE_ID INT DEFAULT 0, + DEVICE_ID INT NOT NULL, + TENANT_ID INT NOT NULL, + STATUS INT DEFAULT 0, + PRIMARY KEY (ID) +); +-- END OF DM_EXT_DEVICE_MAPPING TABLE-- + +-- END OF DM_EXT_PERMISSION_MAPPING TABLE-- +CREATE TABLE IF NOT EXISTS DM_EXT_PERMISSION_MAPPING ( + TRACCAR_DEVICE_ID INT DEFAULT 0, + TRACCAR_USER_ID INT DEFAULT 0 +); +-- END OF DM_EXT_PERMISSION_MAPPING TABLE-- + +-- DYNAMIC TASK TABLES-- +CREATE TABLE IF NOT EXISTS DYNAMIC_TASK ( + DYNAMIC_TASK_ID INTEGER AUTO_INCREMENT NOT NULL, + NAME VARCHAR(300) DEFAULT NULL , + CRON VARCHAR(8000) DEFAULT NULL, + IS_ENABLED BOOLEAN NOT NULL DEFAULT FALSE, + TASK_CLASS_NAME VARCHAR(8000) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (DYNAMIC_TASK_ID) +); + +CREATE TABLE IF NOT EXISTS DYNAMIC_TASK_PROPERTIES ( + DYNAMIC_TASK_ID INTEGER NOT NULL, + PROPERTY_NAME VARCHAR(100) DEFAULT 0, + PROPERTY_VALUE VARCHAR(100) DEFAULT NULL, + TENANT_ID VARCHAR(100), + PRIMARY KEY (DYNAMIC_TASK_ID, PROPERTY_NAME, TENANT_ID), + CONSTRAINT FK_DYNAMIC_TASK_TASK_PROPERTIES FOREIGN KEY (DYNAMIC_TASK_ID) REFERENCES + DYNAMIC_TASK (DYNAMIC_TASK_ID) ON DELETE CASCADE ON UPDATE CASCADE +); +-- END OF DYNAMIC TASK TABLE-- + -- DM_DEVICE_SUB_TYPE TABLE-- CREATE TABLE IF NOT EXISTS DM_DEVICE_SUB_TYPE ( TENANT_ID INT DEFAULT 0, - SUB_TYPE_ID INT NOT NULL, + SUB_TYPE_ID VARCHAR(45) NOT NULL, DEVICE_TYPE VARCHAR(25) NOT NULL, SUB_TYPE_NAME VARCHAR(45) NOT NULL, TYPE_DEFINITION TEXT NOT NULL, PRIMARY KEY (SUB_TYPE_ID,DEVICE_TYPE) ); - -- END OF DM_DEVICE_SUB_TYPE TABLE-- +-- DM_TRACCAR_UNSYNCED_DEVICES TABLE -- +CREATE TABLE IF NOT EXISTS DM_TRACCAR_UNSYNCED_DEVICES ( + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_NAME VARCHAR(100) NOT NULL, + IOTS_DEVICE_IDENTIFIER VARCHAR(300) DEFAULT NULL UNIQUE, + TRACCAR_DEVICE_UNIQUE_ID INT NOT NULL, + TRACCAR_USENAME VARCHAR(100) NULL, + STATUS VARCHAR(100) NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID) +); +-- END OF DM_TRACCAR_UNSYNCED_DEVICES TABLE -- + -- SUB_OPERATION_TEMPLATE TABLE-- -CREATE TABLE SUB_OPERATION_TEMPLATE ( - SUB_OPERATION_TEMPLATE_ID int NOT NULL AUTO_INCREMENT, +CREATE TABLE IF NOT EXISTS SUB_OPERATION_TEMPLATE ( + SUB_OPERATION_TEMPLATE_ID INT NOT NULL AUTO_INCREMENT, OPERATION_DEFINITION TEXT NOT NULL, - OPERATION_CODE varchar(100) NOT NULL, - SUB_TYPE_ID int NOT NULL, + OPERATION_CODE VARCHAR(100) NOT NULL, + SUB_TYPE_ID INT NOT NULL, DEVICE_TYPE VARCHAR(25) NOT NULL, - CREATE_TIMESTAMP timestamp NULL DEFAULT NULL, - UPDATE_TIMESTAMP timestamp NULL DEFAULT NULL, + CREATE_TIMESTAMP TIMESTAMP NULL DEFAULT NULL, + UPDATE_TIMESTAMP TIMESTAMP NULL DEFAULT NULL, PRIMARY KEY (SUB_OPERATION_TEMPLATE_ID), - UNIQUE KEY SUB_OPERATION_TEMPLATE (SUB_TYPE_ID,OPERATION_CODE, DEVICE_TYPE), + CONSTRAINT uk_sub_operation_template UNIQUE (SUB_TYPE_ID, OPERATION_CODE, DEVICE_TYPE), +-- UNIQUE KEY SUB_OPERATION_TEMPLATE (SUB_TYPE_ID, OPERATION_CODE, DEVICE_TYPE), CONSTRAINT fk_SUB_OPERATION_TEMPLATE_DM_DEVICE_SUB_TYPE FOREIGN KEY (SUB_TYPE_ID, DEVICE_TYPE) REFERENCES DM_DEVICE_SUB_TYPE (SUB_TYPE_ID, DEVICE_TYPE) ); -/* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you 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. - */ - -- END OF SUB_OPERATION_TEMPLATE TABLE-- - -INSERT INTO DM_DEVICE_SUB_TYPE (SUB_TYPE_ID, TENANT_ID, DEVICE_TYPE, SUB_TYPE_NAME, TYPE_DEFINITION) VALUES -(3,-1234,'METER','TestSubType','{"make": "TestSubType", "model": "ATx-Mega SIM800", "subTypeId": 3, "hasSMSSupport": true, "hasICMPSupport": true, "socketServerPort": 8071}'), -(4,-1234,'METER','TestSubType','{"make": "TestSubType", "model": "ATx-Mega SIM800", "subTypeId": 4, "hasSMSSupport": true, "hasICMPSupport": true, "socketServerPort": 8071}'); diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/dbscripts/insert-subtypes.sql b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/dbscripts/insert-subtypes.sql new file mode 100644 index 0000000000..ffa001a086 --- /dev/null +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/dbscripts/insert-subtypes.sql @@ -0,0 +1,3 @@ +INSERT INTO DM_DEVICE_SUB_TYPE (SUB_TYPE_ID, TENANT_ID, DEVICE_TYPE, SUB_TYPE_NAME, TYPE_DEFINITION) VALUES +(3,-1234,'METER','TestSubType','{"make": "TestSubType", "model": "ATx-Mega SIM800", "subTypeId": 3, "hasSMSSupport": true, "hasICMPSupport": true, "socketServerPort": 8071}'), +(4,-1234,'METER','TestSubType','{"make": "TestSubType", "model": "ATx-Mega SIM800", "subTypeId": 4, "hasSMSSupport": true, "hasICMPSupport": true, "socketServerPort": 8071}'); \ No newline at end of file diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/repository/conf/cdm-config.xml b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/repository/conf/cdm-config.xml index b6c2900db7..3ce48daefe 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/repository/conf/cdm-config.xml +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/repository/conf/cdm-config.xml @@ -31,18 +31,10 @@ 60000 true - - io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.FCMBasedPushNotificationProvider - - - io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.MQTTBasedPushNotificationProvider - - - io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.HTTPBasedPushNotificationProvider - - - io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.XMPPBasedPushNotificationProvider - + io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.FCMBasedPushNotificationProvider + io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.MQTTBasedPushNotificationProvider + io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.HTTPBasedPushNotificationProvider + io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.XMPPBasedPushNotificationProvider @@ -50,16 +42,16 @@ https://localhost:9443 - admin - admin + ${admin.username} + ${admin.username} https://localhost:9443 - admin - admin + ${admin.username} + ${admin.username} - org.wso2.carbon.policy.mgt + io.entgra.device.mgt.core.policy.mgt true 60000 5 @@ -90,7 +82,7 @@ device caching for upto configured expiry-time in seconds. In clustered setup all worker nodes can enable the device-cache to improve performance. --> - false + true 600 10000 + + true + 600 + 10000 + true - false + true 86400 @@ -120,6 +114,11 @@ false + false + + DM_DB + ARCHIVAL_DB + io.entgra.device.mgt.core.device.mgt.core.task.impl.ArchivalTask 0 0 0 1/1 * ? * @@ -159,7 +158,7 @@ true - wss://localhost:9443 + ws://localhost:9763 2 100 20 @@ -167,5 +166,50 @@ 640 BYOD,COPE + + false + false + io.entgra.device.mgt.core.device.mgt.common.enrollment.notification.EnrollmentNotifier + http://localhost:8280 + + + false + + + test_role + + /permission/admin/Login + + + + + + + + <a href='https://entgra.io' target='_blank'> + Entgra + </a> + IoT Server 5.2.0 | © 2023 + , All Rights Reserved. + + Entgra + + repository/resources/whitelabel + favicon.png + logo.png + icon.png + default + + + + + + + + + + false + Replace with mail + diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/repository/conf/datasources/data-source-config.xml b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/repository/conf/datasources/data-source-config.xml index ad8165fc67..2e591b07c9 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/repository/conf/datasources/data-source-config.xml +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/repository/conf/datasources/data-source-config.xml @@ -18,7 +18,7 @@ --> - jdbc:h2:mem:smart-meter-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true + jdbc:h2:mem:smart-meter-test-db;DB_CLOSE_ON_EXIT=FALSE org.h2.Driver wso2carbon wso2carbon diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/pom.xml b/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/pom.xml index 8eebe210c7..4c5d2b9fc1 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/pom.xml +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/pom.xml @@ -30,18 +30,21 @@ bundle WSO2 Carbon - Policy Decision Point WSO2 Carbon - Policy Decision Point - http://wso2.org + https://entgra.io - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix maven-bundle-plugin - 1.4.0 true @@ -51,14 +54,18 @@ Policy Decision Point Bundle io.entgra.device.mgt.core.policy.decision.point.internal - org.wso2.carbon.context;version="${carbon.kernel.version.range}", + io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.policy.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.policy.decision.point.internal, + io.entgra.device.mgt.core.policy.decision.point.merged, + io.entgra.device.mgt.core.policy.decision.point.simple, + io.entgra.device.mgt.core.policy.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.policy.mgt.core;version="[5.0,6)", + org.apache.commons.logging;version="[1.2,2)", org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.apache.commons.logging, - io.entgra.device.mgt.core.policy.mgt.common.*, - io.entgra.device.mgt.core.policy.mgt.core.*, - org.wso2.carbon.user.core.*, - io.entgra.device.mgt.core.device.mgt.common.* + org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.user.core.service;version="[4.8,5)" io.entgra.device.mgt.core.policy.decision.point.* @@ -96,16 +103,14 @@ - org.eclipse.osgi - org.eclipse.osgi + org.apache.felix + org.apache.felix.scr.ds-annotations + provided - org.eclipse.equinox - org.eclipse.equinox.common - - - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api + provided io.entgra.device.mgt.core @@ -115,5 +120,14 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.policy.mgt.core + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.device.mgt.common + + + org.wso2.carbon + org.wso2.carbon.user.core + provided + diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/internal/MergedPolicyEvaluationServiceComponent.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/internal/MergedPolicyEvaluationServiceComponent.java index 5157146f0a..0a13209c21 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/internal/MergedPolicyEvaluationServiceComponent.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/internal/MergedPolicyEvaluationServiceComponent.java @@ -19,33 +19,22 @@ package io.entgra.device.mgt.core.policy.decision.point.internal; import io.entgra.device.mgt.core.policy.decision.point.merged.MergedEvaluationPoint; +import io.entgra.device.mgt.core.policy.mgt.common.PolicyEvaluationPoint; +import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; -import io.entgra.device.mgt.core.policy.mgt.common.PolicyEvaluationPoint; -import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.user.core.service.RealmService; -/** - * @scr.component name="org.wso2.carbon.policy.decision.MergedPolicyEvaluationServiceComponent" immediate="true" - * @scr.reference name="user.realmservice.default" - * interface="org.wso2.carbon.user.core.service.RealmService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRealmService" - * unbind="unsetRealmService" - * @scr.reference name="org.wso2.carbon.devicemgt.policy.manager" - * interface="io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService" - * cardinality="0..1" - * policy="dynamic" - * bind="setPolicyManagerService" - * unbind="unsetPolicyManagerService" - */ - +@Component( + name = "io.entgra.device.mgt.core.policy.decision.point.internal.MergedPolicyEvaluationServiceComponent", + immediate = true) public class MergedPolicyEvaluationServiceComponent { private static Log log = LogFactory.getLog(MergedPolicyEvaluationServiceComponent.class); + @Activate protected void activate(ComponentContext componentContext) { if (log.isDebugEnabled()) { log.debug("Activating the policy evaluation bundle."); @@ -59,6 +48,7 @@ public class MergedPolicyEvaluationServiceComponent { } } + @Deactivate protected void deactivate(ComponentContext componentContext) { if (log.isDebugEnabled()) { log.debug("De-activating the policy evaluation bundle."); @@ -70,6 +60,12 @@ public class MergedPolicyEvaluationServiceComponent { * * @param realmService An instance of RealmService */ + @Reference( + name = "realm.service", + service = org.wso2.carbon.user.core.service.RealmService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRealmService") protected void setRealmService(RealmService realmService) { if (log.isDebugEnabled()) { @@ -90,6 +86,12 @@ public class MergedPolicyEvaluationServiceComponent { PolicyDecisionPointDataHolder.getInstance().setRealmService(null); } + @Reference( + name = "policy.mgt.service", + service = io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetPolicyManagerService") protected void setPolicyManagerService(PolicyManagerService policyManagerService) { if (log.isDebugEnabled()) { log.debug("Unsetting PolicyManagerService Service"); diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/internal/PolicyEvaluationServiceComponent.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/internal/PolicyEvaluationServiceComponent.java index 46d1855776..2697e10b51 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/internal/PolicyEvaluationServiceComponent.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/internal/PolicyEvaluationServiceComponent.java @@ -19,33 +19,22 @@ package io.entgra.device.mgt.core.policy.decision.point.internal; import io.entgra.device.mgt.core.policy.decision.point.simple.PolicyEvaluationServiceImpl; +import io.entgra.device.mgt.core.policy.mgt.common.PolicyEvaluationPoint; +import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; -import io.entgra.device.mgt.core.policy.mgt.common.PolicyEvaluationPoint; -import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.user.core.service.RealmService; -/** - * @scr.component name="org.wso2.carbon.simple.policy.decision.PolicyEvaluationServiceComponent" immediate="true" - * @scr.reference name="user.realmservice.default" - * interface="org.wso2.carbon.user.core.service.RealmService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRealmService" - * unbind="unsetRealmService" - * @scr.reference name="org.wso2.carbon.devicemgt.policy.manager" - * interface="io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService" - * cardinality="0..1" - * policy="dynamic" - * bind="setPolicyManagerService" - * unbind="unsetPolicyManagerService" - */ - +@Component( + name = "io.entgra.device.mgt.core.policy.decision.point.internal.PolicyEvaluationServiceComponent", + immediate = true) public class PolicyEvaluationServiceComponent { private static Log log = LogFactory.getLog(PolicyEvaluationServiceComponent.class); + @Activate protected void activate(ComponentContext componentContext) { if (log.isDebugEnabled()) { log.debug("Activating the policy evaluation bundle."); @@ -58,7 +47,7 @@ public class PolicyEvaluationServiceComponent { log.error("Error occurred while initializing the policy evaluation bundle"); } } - + @Deactivate protected void deactivate(ComponentContext componentContext) { if (log.isDebugEnabled()) { log.debug("De-activating the policy evaluation bundle."); @@ -70,6 +59,12 @@ public class PolicyEvaluationServiceComponent { * * @param realmService An instance of RealmService */ + @Reference( + name = "realm.service", + service = org.wso2.carbon.user.core.service.RealmService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRealmService") protected void setRealmService(RealmService realmService) { if (log.isDebugEnabled()) { @@ -90,6 +85,12 @@ public class PolicyEvaluationServiceComponent { PolicyDecisionPointDataHolder.getInstance().setRealmService(null); } + @Reference( + name = "policy.mgt.service", + service = io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetPolicyManagerService") protected void setPolicyManagerService(PolicyManagerService policyManagerService) { if (log.isDebugEnabled()) { diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/merged/MergedEvaluationPoint.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/merged/MergedEvaluationPoint.java index e675994e41..9ddc449742 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/merged/MergedEvaluationPoint.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/merged/MergedEvaluationPoint.java @@ -18,16 +18,16 @@ package io.entgra.device.mgt.core.policy.decision.point.merged; -import io.entgra.device.mgt.core.policy.decision.point.internal.PolicyDecisionPointDataHolder; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Profile; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; +import io.entgra.device.mgt.core.policy.decision.point.internal.PolicyDecisionPointDataHolder; import io.entgra.device.mgt.core.policy.mgt.common.*; import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.sql.Timestamp; import java.util.*; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/simple/PolicyEvaluationServiceImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/simple/PolicyEvaluationServiceImpl.java index fd978d94e5..181705e792 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/simple/PolicyEvaluationServiceImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/simple/PolicyEvaluationServiceImpl.java @@ -20,9 +20,9 @@ package io.entgra.device.mgt.core.policy.decision.point.simple; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; import io.entgra.device.mgt.core.policy.mgt.common.PolicyEvaluationException; import io.entgra.device.mgt.core.policy.mgt.common.PolicyEvaluationPoint; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; import java.util.List; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/simple/SimpleEvaluationImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/simple/SimpleEvaluationImpl.java index 05f78e6874..28f63374b9 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/simple/SimpleEvaluationImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/src/main/java/io/entgra/device/mgt/core/policy/decision/point/simple/SimpleEvaluationImpl.java @@ -18,13 +18,13 @@ package io.entgra.device.mgt.core.policy.decision.point.simple; -import io.entgra.device.mgt.core.policy.decision.point.internal.PolicyDecisionPointDataHolder; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; +import io.entgra.device.mgt.core.policy.decision.point.internal.PolicyDecisionPointDataHolder; import io.entgra.device.mgt.core.policy.mgt.common.*; import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.util.ArrayList; import java.util.Collections; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/pom.xml b/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/pom.xml index 1c00d6dc5d..3e1678406c 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/pom.xml +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/pom.xml @@ -31,19 +31,22 @@ bundle WSO2 Carbon - Policy Information Point WSO2 Carbon - Policy Information Point - http://wso2.org + https://entgra.io - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix maven-bundle-plugin - 1.4.0 true @@ -56,6 +59,14 @@ io.entgra.device.mgt.core.policy.information.point.* + + io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.policy.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.policy.information.point, + io.entgra.device.mgt.core.policy.mgt.common;version="[5.0,6)", + org.apache.commons.logging;version="[1.2,2)", + org.osgi.framework.*;version="${imp.package.version.osgi.framework}" + @@ -89,20 +100,22 @@ - org.eclipse.osgi - org.eclipse.osgi + org.apache.felix + org.apache.felix.scr.ds-annotations + provided - org.eclipse.equinox - org.eclipse.equinox.common + org.ops4j.pax.logging + pax-logging-api + provided - org.wso2.carbon - org.wso2.carbon.logging + io.entgra.device.mgt.core + io.entgra.device.mgt.core.policy.mgt.common io.entgra.device.mgt.core - io.entgra.device.mgt.core.policy.mgt.common + io.entgra.device.mgt.core.device.mgt.common diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/src/main/java/io/entgra/device/mgt/core/policy/information/point/PolicyInformationServiceImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/src/main/java/io/entgra/device/mgt/core/policy/information/point/PolicyInformationServiceImpl.java index 752baf00e5..fab3d9b7a2 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/src/main/java/io/entgra/device/mgt/core/policy/information/point/PolicyInformationServiceImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/src/main/java/io/entgra/device/mgt/core/policy/information/point/PolicyInformationServiceImpl.java @@ -20,8 +20,8 @@ package io.entgra.device.mgt.core.policy.information.point; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.Feature; -import io.entgra.device.mgt.core.policy.mgt.common.PIPDevice; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; +import io.entgra.device.mgt.core.policy.mgt.common.PIPDevice; import io.entgra.device.mgt.core.policy.mgt.common.PolicyInformationPoint; import java.util.List; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/src/main/java/io/entgra/device/mgt/core/policy/information/point/internal/PolicyInformationPointBundleActivator.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/src/main/java/io/entgra/device/mgt/core/policy/information/point/internal/PolicyInformationPointBundleActivator.java index c4b944befe..a01841f2da 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/src/main/java/io/entgra/device/mgt/core/policy/information/point/internal/PolicyInformationPointBundleActivator.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/src/main/java/io/entgra/device/mgt/core/policy/information/point/internal/PolicyInformationPointBundleActivator.java @@ -18,13 +18,13 @@ package io.entgra.device.mgt.core.policy.information.point.internal; +import io.entgra.device.mgt.core.policy.information.point.PolicyInformationServiceImpl; +import io.entgra.device.mgt.core.policy.mgt.common.PolicyInformationPoint; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; -import io.entgra.device.mgt.core.policy.information.point.PolicyInformationServiceImpl; -import io.entgra.device.mgt.core.policy.mgt.common.PolicyInformationPoint; public class PolicyInformationPointBundleActivator implements BundleActivator { diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/pom.xml b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/pom.xml index 4655687a6a..70346d54d1 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/pom.xml +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/pom.xml @@ -31,18 +31,21 @@ bundle WSO2 Carbon - Policy Management Common WSO2 Carbon - Policy Management Common - http://wso2.org + https://entgra.io - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix maven-bundle-plugin - 1.4.0 true @@ -51,11 +54,11 @@ ${io.entgra.device.mgt.core.version} Policy Management Common Bundle - javax.xml.bind.annotation, - io.swagger.annotations.*;resolution:=optional, - io.entgra.device.mgt.core.device.mgt.common.*, - io.entgra.device.mgt.core.device.mgt.core.dto.*, - javax.xml.bind.*, + io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.group.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.policy.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.dto;version="[5.0,6)" io.entgra.device.mgt.core.policy.mgt.common.* @@ -94,16 +97,14 @@ - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.equinox - org.eclipse.equinox.common + org.apache.felix + org.apache.felix.scr.ds-annotations + provided - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api + provided org.testng diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/src/main/java/io/entgra/device/mgt/core/policy/mgt/common/PolicyAdministratorPoint.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/src/main/java/io/entgra/device/mgt/core/policy/mgt/common/PolicyAdministratorPoint.java index 0d8219b290..7101bc6c78 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/src/main/java/io/entgra/device/mgt/core/policy/mgt/common/PolicyAdministratorPoint.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/src/main/java/io/entgra/device/mgt/core/policy/mgt/common/PolicyAdministratorPoint.java @@ -17,8 +17,8 @@ */ package io.entgra.device.mgt.core.policy.mgt.common; + import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.DynamicTaskContext; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.PolicyPaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/src/main/java/io/entgra/device/mgt/core/policy/mgt/common/monitor/ComplianceDecisionPoint.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/src/main/java/io/entgra/device/mgt/core/policy/mgt/common/monitor/ComplianceDecisionPoint.java index c56387094d..0ff1d5b766 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/src/main/java/io/entgra/device/mgt/core/policy/mgt/common/monitor/ComplianceDecisionPoint.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/src/main/java/io/entgra/device/mgt/core/policy/mgt/common/monitor/ComplianceDecisionPoint.java @@ -22,9 +22,9 @@ package io.entgra.device.mgt.core.policy.mgt.common.monitor; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.NonComplianceData; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import java.util.List; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml index cd41a8e17f..ccfca465fd 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml @@ -31,18 +31,21 @@ bundle WSO2 Carbon - Policy Management Core WSO2 Carbon - Policy Management Core - http://wso2.org + https://entgra.io - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix maven-bundle-plugin - 1.4.0 true @@ -52,24 +55,53 @@ Policy Management Core Bundle io.entgra.device.mgt.core.policy.mgt.core.internal + com.google.gson;version="[2.9,3)", + io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.configuration.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.exceptions;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.group.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.operation.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.policy.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.config;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.config.policy;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.config.tenant;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.dto;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.operation.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.service;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.task.impl;version="[5.0,6)", + io.entgra.device.mgt.core.policy.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.policy.mgt.common.monitor;version="[5.0,6)", + io.entgra.device.mgt.core.policy.mgt.core.cache, + io.entgra.device.mgt.core.policy.mgt.core.cache.impl, + io.entgra.device.mgt.core.policy.mgt.core.config, + io.entgra.device.mgt.core.policy.mgt.core.config.datasource, + io.entgra.device.mgt.core.policy.mgt.core.dao, + io.entgra.device.mgt.core.policy.mgt.core.dao.impl, + io.entgra.device.mgt.core.policy.mgt.core.dao.impl.feature, + io.entgra.device.mgt.core.policy.mgt.core.dao.impl.policy, + io.entgra.device.mgt.core.policy.mgt.core.dao.util, + io.entgra.device.mgt.core.policy.mgt.core.mgt, + io.entgra.device.mgt.core.policy.mgt.core.mgt.bean, + io.entgra.device.mgt.core.policy.mgt.core.util, + javax.cache;version="[1.0,2)", + javax.naming, + javax.sql, + javax.xml.bind;version="[0.0,1)", + javax.xml.bind.annotation;version="[0.0,1)", + javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}", + org.apache.commons.lang;version="[2.6,3)", + org.apache.commons.logging;version="[1.2,2)", org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.apache.commons.logging, - javax.sql, - javax.cache, - javax.naming, - javax.xml.*, - javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, org.w3c.dom, - io.entgra.device.mgt.core.policy.mgt.common.*, - org.wso2.carbon.user.core.*, - org.wso2.carbon.utils.*, - org.wso2.carbon.context.*, - org.wso2.carbon.user.api.*, - io.entgra.device.mgt.core.device.mgt.core.*, - io.entgra.device.mgt.core.device.mgt.common.*, - org.wso2.carbon.ntask.*, - org.wso2.carbon.caching.* + org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.ntask.common;version="[4.9,5)", + org.wso2.carbon.ntask.core;version="[4.9,5)", + org.wso2.carbon.ntask.core.service;version="[4.9,5)", + org.wso2.carbon.user.api;version="[1.0,2)", + org.wso2.carbon.user.core.service;version="[4.8,5)", + org.wso2.carbon.utils;version="[4.8,5)" !io.entgra.device.mgt.core.policy.mgt.core.internal, @@ -83,8 +115,11 @@ org.apache.maven.plugins maven-surefire-plugin - 2.18 + + --add-opens=java.xml/jdk.xml.internal=ALL-UNNAMED + --add-opens=java.base/jdk.internal.loader=ALL-UNNAMED + file:src/test/resources/log4j.properties @@ -124,25 +159,19 @@ - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.equinox - org.eclipse.equinox.common + org.apache.felix + org.apache.felix.scr.ds-annotations + provided - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api + provided org.wso2.carbon org.wso2.carbon.utils - - - - org.wso2.carbon org.wso2.carbon.core @@ -185,6 +214,15 @@ gson + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.device.mgt.common + + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.device.mgt.core + + @@ -193,46 +231,37 @@ test - org.apache.tomcat.wso2 + org.wso2.orbit.org.apache.tomcat jdbc-pool - mysql mysql-connector-java - 5.1.34 test - com.h2database.wso2 - h2-database-engine + org.wso2.orbit.com.h2database + h2 test - - - - - commons-dbcp.wso2 commons-dbcp - 1.4.0.wso2v1 test commons-pool.wso2 commons-pool - 1.5.6.wso2v1 test org.powermock - powermock-api-mockito + powermock-api-mockito2 test @@ -250,6 +279,20 @@ io.entgra.device.mgt.core.server.bootup.heartbeat.beacon test + + org.wso2.orbit.javax.xml.bind + jaxb-api + + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.notification.logger + provided + + + org.wso2.orbit.javax.xml.bind + jaxb-api + provided + diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyManagerService.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyManagerService.java index 176987eb54..648a5e9cd8 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyManagerService.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyManagerService.java @@ -19,18 +19,15 @@ package io.entgra.device.mgt.core.policy.mgt.core; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.Feature; -import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; -import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; +import io.entgra.device.mgt.core.device.mgt.common.*; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Profile; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; -import io.entgra.device.mgt.core.policy.mgt.common.*; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.NonComplianceData; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.ComplianceFeature; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.NonComplianceData; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; +import io.entgra.device.mgt.core.policy.mgt.common.*; import io.entgra.device.mgt.core.policy.mgt.core.task.TaskScheduleService; import java.util.List; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyManagerServiceImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyManagerServiceImpl.java index e7a919d969..48b392ebe0 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyManagerServiceImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyManagerServiceImpl.java @@ -18,22 +18,17 @@ package io.entgra.device.mgt.core.policy.mgt.core; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.Feature; -import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; -import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; +import io.entgra.device.mgt.core.device.mgt.common.*; import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidDeviceException; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManagementException; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Profile; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; -import io.entgra.device.mgt.core.policy.mgt.common.*; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.NonComplianceData; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.ComplianceFeature; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.NonComplianceData; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; +import io.entgra.device.mgt.core.policy.mgt.common.*; import io.entgra.device.mgt.core.policy.mgt.core.impl.PolicyAdministratorPointImpl; import io.entgra.device.mgt.core.policy.mgt.core.impl.PolicyInformationPointImpl; import io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementDataHolder; @@ -44,6 +39,8 @@ import io.entgra.device.mgt.core.policy.mgt.core.mgt.impl.PolicyManagerImpl; import io.entgra.device.mgt.core.policy.mgt.core.task.TaskScheduleService; import io.entgra.device.mgt.core.policy.mgt.core.task.TaskScheduleServiceImpl; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagerUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.util.ArrayList; import java.util.List; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/cache/PolicyCacheManager.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/cache/PolicyCacheManager.java index 7361ad0466..ec402a96d1 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/cache/PolicyCacheManager.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/cache/PolicyCacheManager.java @@ -19,7 +19,6 @@ package io.entgra.device.mgt.core.policy.mgt.core.cache; -import io.entgra.device.mgt.core.device.mgt.common.DynamicTaskContext; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java index 9dfc2839c4..187d711da5 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java @@ -19,9 +19,6 @@ package io.entgra.device.mgt.core.policy.mgt.core.cache.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.DynamicTaskContext; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; import io.entgra.device.mgt.core.policy.mgt.core.cache.PolicyCacheManager; @@ -29,6 +26,8 @@ import io.entgra.device.mgt.core.policy.mgt.core.mgt.PolicyManager; import io.entgra.device.mgt.core.policy.mgt.core.mgt.impl.PolicyManagerImpl; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagementConstants; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagerUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.cache.Cache; import java.util.ArrayList; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/config/PolicyConfigurationManager.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/config/PolicyConfigurationManager.java index a475162a57..fff3995214 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/config/PolicyConfigurationManager.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/config/PolicyConfigurationManager.java @@ -18,11 +18,11 @@ package io.entgra.device.mgt.core.policy.mgt.core.config; -import org.w3c.dom.Document; import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; import io.entgra.device.mgt.core.policy.mgt.core.config.datasource.DataSourceConfig; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagementConstants; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagerUtil; +import org.w3c.dom.Document; import org.wso2.carbon.utils.CarbonUtils; import javax.xml.bind.JAXBContext; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/MonitoringDAO.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/MonitoringDAO.java index 6e11d63965..a3bf9343a6 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/MonitoringDAO.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/MonitoringDAO.java @@ -21,8 +21,8 @@ package io.entgra.device.mgt.core.policy.mgt.core.dao; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.ComplianceData; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.NonComplianceData; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.ComplianceFeature; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.NonComplianceData; import io.entgra.device.mgt.core.policy.mgt.common.monitor.PolicyDeviceWrapper; import java.util.List; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/PolicyDAO.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/PolicyDAO.java index a755a5c6b3..f5d7f4c238 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/PolicyDAO.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/PolicyDAO.java @@ -22,10 +22,10 @@ import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.PolicyPaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.CorrectiveAction; -import io.entgra.device.mgt.core.policy.mgt.common.Criterion; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.DeviceGroupWrapper; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.PolicyCriterion; +import io.entgra.device.mgt.core.policy.mgt.common.Criterion; import java.util.HashMap; import java.util.List; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/PolicyManagementDAOFactory.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/PolicyManagementDAOFactory.java index 74b692543a..ea58d00b92 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/PolicyManagementDAOFactory.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/PolicyManagementDAOFactory.java @@ -18,8 +18,6 @@ package io.entgra.device.mgt.core.policy.mgt.core.dao; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.UnsupportedDatabaseEngineException; @@ -35,6 +33,8 @@ import io.entgra.device.mgt.core.policy.mgt.core.dao.impl.policy.OraclePolicyDAO import io.entgra.device.mgt.core.policy.mgt.core.dao.impl.policy.PostgreSQLPolicyDAOImpl; import io.entgra.device.mgt.core.policy.mgt.core.dao.impl.policy.SQLServerPolicyDAOImpl; import io.entgra.device.mgt.core.policy.mgt.core.dao.util.PolicyManagementDAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.sql.DataSource; import java.sql.Connection; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/MonitoringDAOImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/MonitoringDAOImpl.java index 885c80bd41..a003fac641 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/MonitoringDAOImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/MonitoringDAOImpl.java @@ -19,19 +19,19 @@ package io.entgra.device.mgt.core.policy.mgt.core.dao.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.ComplianceData; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.NonComplianceData; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.ComplianceFeature; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.NonComplianceData; import io.entgra.device.mgt.core.policy.mgt.common.monitor.PolicyDeviceWrapper; import io.entgra.device.mgt.core.policy.mgt.core.dao.MonitoringDAO; import io.entgra.device.mgt.core.policy.mgt.core.dao.MonitoringDAOException; import io.entgra.device.mgt.core.policy.mgt.core.dao.PolicyManagementDAOFactory; import io.entgra.device.mgt.core.policy.mgt.core.dao.util.PolicyManagementDAOUtil; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagerUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.sql.*; import java.util.*; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/ProfileDAOImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/ProfileDAOImpl.java index 05bf17ed16..5845104f3b 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/ProfileDAOImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/ProfileDAOImpl.java @@ -18,15 +18,14 @@ package io.entgra.device.mgt.core.policy.mgt.core.dao.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.DynamicTaskContext; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Profile; import io.entgra.device.mgt.core.policy.mgt.core.dao.PolicyManagementDAOFactory; import io.entgra.device.mgt.core.policy.mgt.core.dao.ProfileDAO; import io.entgra.device.mgt.core.policy.mgt.core.dao.ProfileManagerDAOException; import io.entgra.device.mgt.core.policy.mgt.core.dao.util.PolicyManagementDAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/feature/AbstractFeatureDAO.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/feature/AbstractFeatureDAO.java index 71b4a3a728..7c1ac4d3f2 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/feature/AbstractFeatureDAO.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/feature/AbstractFeatureDAO.java @@ -18,9 +18,6 @@ package io.entgra.device.mgt.core.policy.mgt.core.dao.impl.feature; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Feature; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Profile; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; @@ -29,6 +26,9 @@ import io.entgra.device.mgt.core.policy.mgt.core.dao.FeatureManagerDAOException; import io.entgra.device.mgt.core.policy.mgt.core.dao.PolicyManagementDAOFactory; import io.entgra.device.mgt.core.policy.mgt.core.dao.util.PolicyManagementDAOUtil; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagerUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.io.ByteArrayInputStream; import java.io.IOException; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/feature/GenericFeatureDAOImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/feature/GenericFeatureDAOImpl.java index b9b1799e13..34d23a569a 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/feature/GenericFeatureDAOImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/feature/GenericFeatureDAOImpl.java @@ -18,14 +18,14 @@ package io.entgra.device.mgt.core.policy.mgt.core.dao.impl.feature; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; import io.entgra.device.mgt.core.policy.mgt.core.dao.FeatureManagerDAOException; import io.entgra.device.mgt.core.policy.mgt.core.dao.PolicyManagementDAOFactory; import io.entgra.device.mgt.core.policy.mgt.core.dao.util.PolicyManagementDAOUtil; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagerUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.io.IOException; import java.sql.Connection; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/feature/OracleServerFeatureDAOImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/feature/OracleServerFeatureDAOImpl.java index ee439bc07e..e9962c6cf7 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/feature/OracleServerFeatureDAOImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/feature/OracleServerFeatureDAOImpl.java @@ -17,12 +17,12 @@ */ package io.entgra.device.mgt.core.policy.mgt.core.dao.impl.feature; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; import io.entgra.device.mgt.core.policy.mgt.core.dao.FeatureManagerDAOException; import io.entgra.device.mgt.core.policy.mgt.core.dao.PolicyManagementDAOFactory; import io.entgra.device.mgt.core.policy.mgt.core.dao.util.PolicyManagementDAOUtil; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagerUtil; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.io.IOException; import java.sql.Connection; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/feature/SQLServerFeatureDAOImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/feature/SQLServerFeatureDAOImpl.java index 617867ef8b..1237236174 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/feature/SQLServerFeatureDAOImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/feature/SQLServerFeatureDAOImpl.java @@ -18,14 +18,14 @@ package io.entgra.device.mgt.core.policy.mgt.core.dao.impl.feature; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; import io.entgra.device.mgt.core.policy.mgt.core.dao.FeatureManagerDAOException; import io.entgra.device.mgt.core.policy.mgt.core.dao.PolicyManagementDAOFactory; import io.entgra.device.mgt.core.policy.mgt.core.dao.util.PolicyManagementDAOUtil; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagerUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.io.IOException; import java.sql.Connection; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/AbstractPolicyDAOImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/AbstractPolicyDAOImpl.java index 9a7dcc8cb8..92b1040d31 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/AbstractPolicyDAOImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/AbstractPolicyDAOImpl.java @@ -19,9 +19,6 @@ package io.entgra.device.mgt.core.policy.mgt.core.dao.impl.policy; import com.google.gson.Gson; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.CorrectiveAction; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.DeviceGroupWrapper; @@ -35,6 +32,9 @@ import io.entgra.device.mgt.core.policy.mgt.core.dao.PolicyManagerDAOException; import io.entgra.device.mgt.core.policy.mgt.core.dao.util.PolicyManagementDAOUtil; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagerUtil; import io.entgra.device.mgt.core.policy.mgt.core.util.SetReferenceTransformer; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.io.ByteArrayInputStream; import java.io.IOException; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/enforcement/DelegationTask.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/enforcement/DelegationTask.java index dfa5ae4f5e..0b499f30e1 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/enforcement/DelegationTask.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/enforcement/DelegationTask.java @@ -18,8 +18,6 @@ package io.entgra.device.mgt.core.policy.mgt.core.enforcement; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; @@ -33,6 +31,8 @@ import io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementDataHo import io.entgra.device.mgt.core.policy.mgt.core.mgt.PolicyManager; import io.entgra.device.mgt.core.policy.mgt.core.mgt.bean.UpdatedPolicyDeviceListBean; import io.entgra.device.mgt.core.policy.mgt.core.mgt.impl.PolicyManagerImpl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.util.ArrayList; import java.util.List; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java index bbb8413ad6..a56eee3ab2 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java @@ -17,8 +17,6 @@ */ package io.entgra.device.mgt.core.policy.mgt.core.enforcement; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidDeviceException; @@ -36,6 +34,8 @@ import io.entgra.device.mgt.core.policy.mgt.common.PolicyTransformException; import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; import io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementDataHolder; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagerUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.util.ArrayList; import java.util.List; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/ComplianceDecisionPointImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/ComplianceDecisionPointImpl.java index 07380972d2..7767844778 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/ComplianceDecisionPointImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/ComplianceDecisionPointImpl.java @@ -19,24 +19,26 @@ package io.entgra.device.mgt.core.policy.mgt.core.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.*; +import io.entgra.device.mgt.core.device.mgt.common.Device; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidDeviceException; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManagementException; -import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.PolicyOperation; -import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.ProfileOperation; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.NonComplianceData; -import io.entgra.device.mgt.core.policy.mgt.common.monitor.ComplianceDecisionPoint; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.ComplianceFeature; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.NonComplianceData; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; +import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.PolicyOperation; +import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.ProfileOperation; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import io.entgra.device.mgt.core.policy.mgt.common.monitor.ComplianceDecisionPoint; import io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementDataHolder; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagementConstants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.util.ArrayList; import java.util.List; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/PolicyAdministratorPointImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/PolicyAdministratorPointImpl.java index cf06ff2668..df059cb714 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/PolicyAdministratorPointImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/PolicyAdministratorPointImpl.java @@ -26,17 +26,14 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.DynamicTaskContext; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Profile; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.config.policy.PolicyConfiguration; -import org.wso2.carbon.ntask.common.TaskException; -import org.wso2.carbon.ntask.core.TaskInfo; -import org.wso2.carbon.ntask.core.TaskManager; -import org.wso2.carbon.ntask.core.service.TaskService; -import io.entgra.device.mgt.core.policy.mgt.common.*; +import io.entgra.device.mgt.core.policy.mgt.common.PolicyAdministratorPoint; +import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; +import io.entgra.device.mgt.core.policy.mgt.common.ProfileManagementException; import io.entgra.device.mgt.core.policy.mgt.core.cache.PolicyCacheManager; import io.entgra.device.mgt.core.policy.mgt.core.cache.impl.PolicyCacheManagerImpl; import io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementDataHolder; @@ -45,6 +42,13 @@ import io.entgra.device.mgt.core.policy.mgt.core.mgt.ProfileManager; import io.entgra.device.mgt.core.policy.mgt.core.mgt.impl.PolicyManagerImpl; import io.entgra.device.mgt.core.policy.mgt.core.mgt.impl.ProfileManagerImpl; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagementConstants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.ntask.common.TaskException; +import org.wso2.carbon.ntask.core.TaskInfo; +import org.wso2.carbon.ntask.core.TaskManager; +import org.wso2.carbon.ntask.core.service.TaskService; import java.util.HashMap; import java.util.List; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/PolicyFilterImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/PolicyFilterImpl.java index 6d856d049b..94a5082c1a 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/PolicyFilterImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/PolicyFilterImpl.java @@ -19,13 +19,13 @@ package io.entgra.device.mgt.core.policy.mgt.core.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.DeviceGroupWrapper; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.entgra.device.mgt.core.policy.mgt.common.PolicyFilter; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagementConstants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.util.ArrayList; import java.util.HashMap; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/PolicyInformationPointImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/PolicyInformationPointImpl.java index 657a2bd923..6b164e2803 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/PolicyInformationPointImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/PolicyInformationPointImpl.java @@ -18,9 +18,6 @@ package io.entgra.device.mgt.core.policy.mgt.core.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.Feature; @@ -31,16 +28,15 @@ import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderService; -import io.entgra.device.mgt.core.policy.mgt.common.FeatureManagementException; -import io.entgra.device.mgt.core.policy.mgt.common.PIPDevice; -import io.entgra.device.mgt.core.policy.mgt.common.PolicyFilter; -import io.entgra.device.mgt.core.policy.mgt.common.PolicyInformationPoint; -import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; +import io.entgra.device.mgt.core.policy.mgt.common.*; import io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementDataHolder; import io.entgra.device.mgt.core.policy.mgt.core.mgt.FeatureManager; import io.entgra.device.mgt.core.policy.mgt.core.mgt.PolicyManager; import io.entgra.device.mgt.core.policy.mgt.core.mgt.impl.FeatureManagerImpl; import io.entgra.device.mgt.core.policy.mgt.core.mgt.impl.PolicyManagerImpl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/internal/PolicyManagementDataHolder.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/internal/PolicyManagementDataHolder.java index 27965ba21e..eb1e8f960d 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/internal/PolicyManagementDataHolder.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/internal/PolicyManagementDataHolder.java @@ -18,17 +18,17 @@ package io.entgra.device.mgt.core.policy.mgt.core.internal; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.config.policy.PolicyConfiguration; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderService; -import org.wso2.carbon.ntask.core.service.TaskService; import io.entgra.device.mgt.core.policy.mgt.common.PolicyEvaluationPoint; import io.entgra.device.mgt.core.policy.mgt.common.PolicyInformationPoint; import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; import io.entgra.device.mgt.core.policy.mgt.core.mgt.MonitoringManager; import io.entgra.device.mgt.core.policy.mgt.core.mgt.PolicyManager; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.ntask.core.service.TaskService; import org.wso2.carbon.user.core.service.RealmService; import java.util.HashMap; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/internal/PolicyManagementServiceComponent.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/internal/PolicyManagementServiceComponent.java index 05bb07ee70..e9b7489428 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/internal/PolicyManagementServiceComponent.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/internal/PolicyManagementServiceComponent.java @@ -18,13 +18,9 @@ package io.entgra.device.mgt.core.policy.mgt.core.internal; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.config.policy.PolicyConfiguration; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.ntask.core.service.TaskService; import io.entgra.device.mgt.core.policy.mgt.common.PolicyEvaluationPoint; import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerServiceImpl; @@ -35,40 +31,22 @@ import io.entgra.device.mgt.core.policy.mgt.core.dao.PolicyManagementDAOFactory; import io.entgra.device.mgt.core.policy.mgt.core.task.TaskScheduleService; import io.entgra.device.mgt.core.policy.mgt.core.task.TaskScheduleServiceImpl; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagerUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; +import org.wso2.carbon.ntask.core.service.TaskService; import org.wso2.carbon.user.core.service.RealmService; -/** - * @scr.component name="org.wso2.carbon.devicemgt.policy.manager" immediate="true" - * @scr.reference name="user.realmservice.default" - * interface="org.wso2.carbon.user.core.service.RealmService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRealmService" - * unbind="unsetRealmService" - * @scr.reference name="org.wso2.carbon.devicemgt.policy.evaluation.manager" - * interface="io.entgra.device.mgt.core.policy.mgt.common.PolicyEvaluationPoint" - * cardinality="1..n" - * policy="dynamic" - * bind="setPEPService" - * unbind="unsetPEPService" - * @scr.reference name="org.wso2.carbon.device.manager" - * interface="io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDeviceManagementService" - * unbind="unsetDeviceManagementService" - * @scr.reference name="ntask.component" - * interface="org.wso2.carbon.ntask.core.service.TaskService" - * cardinality="1..1" - * policy="dynamic" - * bind="setTaskService" - * unbind="unsetTaskService" - */ @SuppressWarnings("unused") +@Component( + name = "io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementServiceComponent", + immediate = true) public class PolicyManagementServiceComponent { private static final Log log = LogFactory.getLog(PolicyManagementServiceComponent.class); + @Activate protected void activate(ComponentContext componentContext) { try { @@ -95,6 +73,7 @@ public class PolicyManagementServiceComponent { } @SuppressWarnings("unused") + @Deactivate protected void deactivate(ComponentContext componentContext) { try { PolicyConfiguration policyConfiguration = @@ -114,6 +93,12 @@ public class PolicyManagementServiceComponent { * * @param realmService An instance of RealmService */ + @Reference( + name = "realm.service", + service = org.wso2.carbon.user.core.service.RealmService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRealmService") protected void setRealmService(RealmService realmService) { if (log.isDebugEnabled()) { @@ -149,7 +134,12 @@ public class PolicyManagementServiceComponent { PolicyManagementDataHolder.getInstance().setPolicyInformationPoint(null); }*/ - + @Reference( + name = "pep.service", + service = io.entgra.device.mgt.core.policy.mgt.common.PolicyEvaluationPoint.class, + cardinality = ReferenceCardinality.MULTIPLE, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetPEPService") protected void setPEPService(PolicyEvaluationPoint pepService) { if (log.isDebugEnabled()) { log.debug("Setting Policy Information Service"); @@ -164,6 +154,12 @@ public class PolicyManagementServiceComponent { PolicyManagementDataHolder.getInstance().removePolicyEvaluationPoint(pepService); } + @Reference( + name = "device.mgt.provider.service", + service = io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDeviceManagementService") protected void setDeviceManagementService(DeviceManagementProviderService deviceManagerService) { if (log.isDebugEnabled()) { log.debug("Setting Device Management Service"); @@ -178,6 +174,12 @@ public class PolicyManagementServiceComponent { PolicyManagementDataHolder.getInstance().setDeviceManagementService(null); } + @Reference( + name = "task.service", + service = org.wso2.carbon.ntask.core.service.TaskService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetTaskService") protected void setTaskService(TaskService taskService) { if (log.isDebugEnabled()) { log.debug("Setting the task service."); diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/MonitoringManager.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/MonitoringManager.java index 96356359c5..d62d3536ae 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/MonitoringManager.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/MonitoringManager.java @@ -22,8 +22,8 @@ import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.NonComplianceData; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.ComplianceFeature; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.NonComplianceData; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; import java.util.List; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/PolicyManager.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/PolicyManager.java index abecb53712..dc066033ce 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/PolicyManager.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/PolicyManager.java @@ -19,7 +19,6 @@ package io.entgra.device.mgt.core.policy.mgt.core.mgt; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.DynamicTaskContext; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.PolicyPaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/FeatureManagerImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/FeatureManagerImpl.java index 23c8d2e629..ea4e71f526 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/FeatureManagerImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/FeatureManagerImpl.java @@ -18,19 +18,14 @@ package io.entgra.device.mgt.core.policy.mgt.core.mgt.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.Feature; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Profile; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; import io.entgra.device.mgt.core.policy.mgt.common.FeatureManagementException; -import io.entgra.device.mgt.core.policy.mgt.core.dao.FeatureDAO; -import io.entgra.device.mgt.core.policy.mgt.core.dao.FeatureManagerDAOException; -import io.entgra.device.mgt.core.policy.mgt.core.dao.PolicyManagementDAOFactory; -import io.entgra.device.mgt.core.policy.mgt.core.dao.PolicyManagerDAOException; -import io.entgra.device.mgt.core.policy.mgt.core.dao.ProfileDAO; -import io.entgra.device.mgt.core.policy.mgt.core.dao.ProfileManagerDAOException; +import io.entgra.device.mgt.core.policy.mgt.core.dao.*; import io.entgra.device.mgt.core.policy.mgt.core.mgt.FeatureManager; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.SQLException; import java.util.List; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java index cc451c10d5..a93662775d 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java @@ -18,8 +18,6 @@ package io.entgra.device.mgt.core.policy.mgt.core.mgt.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; @@ -40,15 +38,13 @@ import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProvide import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; import io.entgra.device.mgt.core.policy.mgt.common.monitor.ComplianceDecisionPoint; import io.entgra.device.mgt.core.policy.mgt.common.monitor.PolicyDeviceWrapper; -import io.entgra.device.mgt.core.policy.mgt.core.dao.MonitoringDAO; -import io.entgra.device.mgt.core.policy.mgt.core.dao.MonitoringDAOException; -import io.entgra.device.mgt.core.policy.mgt.core.dao.PolicyDAO; -import io.entgra.device.mgt.core.policy.mgt.core.dao.PolicyManagementDAOFactory; -import io.entgra.device.mgt.core.policy.mgt.core.dao.PolicyManagerDAOException; +import io.entgra.device.mgt.core.policy.mgt.core.dao.*; import io.entgra.device.mgt.core.policy.mgt.core.impl.ComplianceDecisionPointImpl; import io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementDataHolder; import io.entgra.device.mgt.core.policy.mgt.core.mgt.MonitoringManager; import io.entgra.device.mgt.core.policy.mgt.core.mgt.PolicyManager; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.SQLException; import java.util.ArrayList; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/PolicyManagerImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/PolicyManagerImpl.java index cf6e0da5a8..38d9a7f007 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/PolicyManagerImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/PolicyManagerImpl.java @@ -19,15 +19,9 @@ package io.entgra.device.mgt.core.policy.mgt.core.mgt.impl; import com.google.gson.Gson; -import io.entgra.device.mgt.core.device.mgt.common.PolicyPaginationRequest; -import io.entgra.device.mgt.core.device.mgt.extensions.logger.spi.EntgraLogger; -import io.entgra.device.mgt.core.notification.logger.PolicyLogContext; -import io.entgra.device.mgt.core.notification.logger.impl.EntgraPolicyLoggerImpl; -import org.apache.commons.lang.StringUtils; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.DynamicTaskContext; -import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; +import io.entgra.device.mgt.core.device.mgt.common.PolicyPaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.InvalidDeviceException; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; @@ -46,6 +40,9 @@ import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.CommandOperation; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationMgtConstants; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderService; +import io.entgra.device.mgt.core.device.mgt.extensions.logger.spi.EntgraLogger; +import io.entgra.device.mgt.core.notification.logger.PolicyLogContext; +import io.entgra.device.mgt.core.notification.logger.impl.EntgraPolicyLoggerImpl; import io.entgra.device.mgt.core.policy.mgt.common.Criterion; import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; import io.entgra.device.mgt.core.policy.mgt.common.ProfileManagementException; @@ -63,6 +60,7 @@ import io.entgra.device.mgt.core.policy.mgt.core.mgt.ProfileManager; import io.entgra.device.mgt.core.policy.mgt.core.mgt.bean.UpdatedPolicyDeviceListBean; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagementConstants; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagerUtil; +import org.apache.commons.lang.StringUtils; import org.wso2.carbon.context.PrivilegedCarbonContext; import java.sql.SQLException; @@ -644,8 +642,8 @@ public class PolicyManagerImpl implements PolicyManager { @Override public void activatePolicy(int policyId) throws PolicyManagementException { + Policy policy = this.getPolicy(policyId); try { - Policy policy = this.getPolicy(policyId); PolicyManagementDAOFactory.beginTransaction(); policyDAO.activatePolicy(policyId); policyDAO.recordUpdatedPolicy(policy); @@ -1480,7 +1478,7 @@ public class PolicyManagerImpl implements PolicyManager { * @return */ private List getSingleCorrectiveAction - (List allCorrectiveActions, int policyId) { + (List allCorrectiveActions, int policyId) { List correctiveActionsOfPolicy = new ArrayList<>(); for (CorrectiveAction correctiveAction : allCorrectiveActions) { if (correctiveAction.getAssociatedGeneralPolicyId() != null && diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/ProfileManagerImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/ProfileManagerImpl.java index 96979f7aca..f41ea1ffa1 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/ProfileManagerImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/ProfileManagerImpl.java @@ -18,19 +18,13 @@ package io.entgra.device.mgt.core.policy.mgt.core.mgt.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.DynamicTaskContext; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Profile; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; import io.entgra.device.mgt.core.policy.mgt.common.ProfileManagementException; -import io.entgra.device.mgt.core.policy.mgt.core.dao.FeatureDAO; -import io.entgra.device.mgt.core.policy.mgt.core.dao.FeatureManagerDAOException; -import io.entgra.device.mgt.core.policy.mgt.core.dao.PolicyManagementDAOFactory; -import io.entgra.device.mgt.core.policy.mgt.core.dao.PolicyManagerDAOException; -import io.entgra.device.mgt.core.policy.mgt.core.dao.ProfileDAO; -import io.entgra.device.mgt.core.policy.mgt.core.dao.ProfileManagerDAOException; +import io.entgra.device.mgt.core.policy.mgt.core.dao.*; import io.entgra.device.mgt.core.policy.mgt.core.mgt.ProfileManager; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.SQLException; import java.sql.Timestamp; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/task/MonitoringTask.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/task/MonitoringTask.java index 42b6e745ab..62286e40b9 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/task/MonitoringTask.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/task/MonitoringTask.java @@ -18,10 +18,6 @@ package io.entgra.device.mgt.core.policy.mgt.core.task; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.PolicyMonitoringManager; @@ -31,6 +27,10 @@ import io.entgra.device.mgt.core.device.mgt.core.task.impl.DynamicPartitionedSch import io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementDataHolder; import io.entgra.device.mgt.core.policy.mgt.core.mgt.MonitoringManager; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagementConstants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.util.ArrayList; import java.util.List; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/task/TaskScheduleServiceImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/task/TaskScheduleServiceImpl.java index c6fd1fd469..5a20f38cef 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/task/TaskScheduleServiceImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/task/TaskScheduleServiceImpl.java @@ -19,19 +19,19 @@ package io.entgra.device.mgt.core.policy.mgt.core.task; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; +import io.entgra.device.mgt.core.device.mgt.core.config.policy.PolicyConfiguration; +import io.entgra.device.mgt.core.policy.mgt.common.PolicyMonitoringTaskException; +import io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementDataHolder; +import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagementConstants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; -import io.entgra.device.mgt.core.device.mgt.core.config.policy.PolicyConfiguration; import org.wso2.carbon.ntask.common.TaskException; import org.wso2.carbon.ntask.core.TaskInfo; +import org.wso2.carbon.ntask.core.TaskInfo.TriggerInfo; import org.wso2.carbon.ntask.core.TaskManager; import org.wso2.carbon.ntask.core.service.TaskService; -import io.entgra.device.mgt.core.policy.mgt.common.PolicyMonitoringTaskException; -import io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementDataHolder; -import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagementConstants; -import org.wso2.carbon.ntask.core.TaskInfo.TriggerInfo; import java.util.HashMap; import java.util.Map; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/util/PolicyManagerUtil.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/util/PolicyManagerUtil.java index 1aa7947e8e..1b900e03d9 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/util/PolicyManagerUtil.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/util/PolicyManagerUtil.java @@ -19,13 +19,6 @@ package io.entgra.device.mgt.core.policy.mgt.core.util; import com.google.gson.Gson; -import org.apache.commons.lang.StringUtils; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationEntry; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationManagementException; @@ -34,20 +27,24 @@ import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformCon import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.CorrectiveAction; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.config.policy.PolicyConfiguration; import io.entgra.device.mgt.core.device.mgt.core.config.tenant.PlatformConfigurationManagementServiceImpl; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.PolicyOperation; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.ProfileOperation; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.entgra.device.mgt.core.policy.mgt.common.PolicyAdministratorPoint; import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; import io.entgra.device.mgt.core.policy.mgt.common.PolicyTransformException; import io.entgra.device.mgt.core.policy.mgt.core.config.datasource.DataSourceConfig; import io.entgra.device.mgt.core.policy.mgt.core.config.datasource.JNDILookupDefinition; import io.entgra.device.mgt.core.policy.mgt.core.dao.util.PolicyManagementDAOUtil; import io.entgra.device.mgt.core.policy.mgt.core.impl.PolicyAdministratorPointImpl; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; import javax.cache.Cache; import javax.cache.CacheManager; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/BasePolicyManagementDAOTest.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/BasePolicyManagementDAOTest.java index 0e58ef2c11..af0cddd87f 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/BasePolicyManagementDAOTest.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/BasePolicyManagementDAOTest.java @@ -17,24 +17,6 @@ */ package io.entgra.device.mgt.core.policy.mgt.core; -import io.entgra.device.mgt.core.policy.mgt.common.PolicyEvaluationPoint; -import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; -import io.entgra.device.mgt.core.policy.mgt.core.common.DataSourceConfig; -import io.entgra.device.mgt.core.policy.mgt.core.dao.PolicyManagementDAOFactory; -import io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementDataHolder; -import io.entgra.device.mgt.core.policy.mgt.core.mgt.ProfileManager; -import io.entgra.device.mgt.core.policy.mgt.core.mgt.impl.ProfileManagerImpl; -import io.entgra.device.mgt.core.policy.mgt.core.services.SimplePolicyEvaluationTest; -import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagerUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.tomcat.jdbc.pool.PoolProperties; -import org.testng.Assert; -import org.testng.annotations.BeforeSuite; -import org.testng.internal.collections.Pair; -import org.w3c.dom.Document; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; @@ -56,6 +38,24 @@ import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProvide import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderServiceImpl; +import io.entgra.device.mgt.core.policy.mgt.common.PolicyEvaluationPoint; +import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; +import io.entgra.device.mgt.core.policy.mgt.core.common.DataSourceConfig; +import io.entgra.device.mgt.core.policy.mgt.core.dao.PolicyManagementDAOFactory; +import io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementDataHolder; +import io.entgra.device.mgt.core.policy.mgt.core.mgt.ProfileManager; +import io.entgra.device.mgt.core.policy.mgt.core.mgt.impl.ProfileManagerImpl; +import io.entgra.device.mgt.core.policy.mgt.core.services.SimplePolicyEvaluationTest; +import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagerUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.tomcat.jdbc.pool.PoolProperties; +import org.testng.Assert; +import org.testng.annotations.BeforeSuite; +import org.testng.internal.collections.Pair; +import org.w3c.dom.Document; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.registry.core.config.RegistryContext; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.internal.RegistryDataHolder; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/MonitoringTestCase.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/MonitoringTestCase.java index 89ed6d8df9..8758454341 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/MonitoringTestCase.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/MonitoringTestCase.java @@ -19,17 +19,6 @@ package io.entgra.device.mgt.core.policy.mgt.core; -import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; -import io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementDataHolder; -import io.entgra.device.mgt.core.policy.mgt.core.mgt.MonitoringManager; -import io.entgra.device.mgt.core.policy.mgt.core.mgt.PolicyManager; -import io.entgra.device.mgt.core.policy.mgt.core.mgt.impl.MonitoringManagerImpl; -import io.entgra.device.mgt.core.policy.mgt.core.mgt.impl.PolicyManagerImpl; -import io.entgra.device.mgt.core.policy.mgt.core.services.PolicyMonitoringManagerTest; -import junit.framework.Assert; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.testng.annotations.Test; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; @@ -42,6 +31,17 @@ import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationManagerI import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderServiceImpl; +import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; +import io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementDataHolder; +import io.entgra.device.mgt.core.policy.mgt.core.mgt.MonitoringManager; +import io.entgra.device.mgt.core.policy.mgt.core.mgt.PolicyManager; +import io.entgra.device.mgt.core.policy.mgt.core.mgt.impl.MonitoringManagerImpl; +import io.entgra.device.mgt.core.policy.mgt.core.mgt.impl.PolicyManagerImpl; +import io.entgra.device.mgt.core.policy.mgt.core.services.PolicyMonitoringManagerTest; +import junit.framework.Assert; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.annotations.Test; import java.util.List; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyDAOTestCase.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyDAOTestCase.java index c6a7e0f03d..b9a0d71d36 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyDAOTestCase.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyDAOTestCase.java @@ -17,18 +17,6 @@ */ package io.entgra.device.mgt.core.policy.mgt.core; -import io.entgra.device.mgt.core.policy.mgt.common.FeatureManagementException; -import io.entgra.device.mgt.core.policy.mgt.common.PolicyAdministratorPoint; -import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; -import io.entgra.device.mgt.core.policy.mgt.common.ProfileManagementException; -import io.entgra.device.mgt.core.policy.mgt.core.impl.PolicyAdministratorPointImpl; -import io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementDataHolder; -import io.entgra.device.mgt.core.policy.mgt.core.util.*; -import junit.framework.Assert; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.Feature; @@ -42,6 +30,18 @@ import io.entgra.device.mgt.core.device.mgt.core.dao.*; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import io.entgra.device.mgt.core.policy.mgt.common.FeatureManagementException; +import io.entgra.device.mgt.core.policy.mgt.common.PolicyAdministratorPoint; +import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; +import io.entgra.device.mgt.core.policy.mgt.common.ProfileManagementException; +import io.entgra.device.mgt.core.policy.mgt.core.impl.PolicyAdministratorPointImpl; +import io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementDataHolder; +import io.entgra.device.mgt.core.policy.mgt.core.util.*; +import junit.framework.Assert; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyEvaluationTestCase.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyEvaluationTestCase.java index 36f4604c4b..608af3b541 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyEvaluationTestCase.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyEvaluationTestCase.java @@ -19,6 +19,12 @@ package io.entgra.device.mgt.core.policy.mgt.core; +import io.entgra.device.mgt.core.device.mgt.common.Device; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; import io.entgra.device.mgt.core.policy.mgt.common.PolicyAdministratorPoint; import io.entgra.device.mgt.core.policy.mgt.common.PolicyEvaluationException; import io.entgra.device.mgt.core.policy.mgt.common.PolicyEvaluationPoint; @@ -31,12 +37,6 @@ import org.apache.commons.logging.LogFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; import org.wso2.carbon.ntask.common.TaskException; import java.util.Collections; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyManagerServiceImplTest.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyManagerServiceImplTest.java index 8158bb8052..37cec7717a 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyManagerServiceImplTest.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/PolicyManagerServiceImplTest.java @@ -17,26 +17,6 @@ */ package io.entgra.device.mgt.core.policy.mgt.core; -import io.entgra.device.mgt.core.policy.mgt.common.FeatureManagementException; -import io.entgra.device.mgt.core.policy.mgt.common.PolicyEvaluationException; -import io.entgra.device.mgt.core.policy.mgt.common.PolicyEvaluationPoint; -import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; -import io.entgra.device.mgt.core.policy.mgt.core.enforcement.DelegationTask; -import io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementDataHolder; -import io.entgra.device.mgt.core.policy.mgt.core.mgt.MonitoringManager; -import io.entgra.device.mgt.core.policy.mgt.core.mgt.impl.MonitoringManagerImpl; -import io.entgra.device.mgt.core.policy.mgt.core.mock.TestHeartBeatManagementService; -import io.entgra.device.mgt.core.policy.mgt.core.mock.TypeXDeviceManagementService; -import io.entgra.device.mgt.core.policy.mgt.core.task.MonitoringTask; -import io.entgra.device.mgt.core.policy.mgt.core.task.TaskScheduleService; -import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagementConstants; -import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; @@ -59,6 +39,26 @@ import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHo import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationManagerImpl; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.PolicyOperation; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.ProfileOperation; +import io.entgra.device.mgt.core.policy.mgt.common.FeatureManagementException; +import io.entgra.device.mgt.core.policy.mgt.common.PolicyEvaluationException; +import io.entgra.device.mgt.core.policy.mgt.common.PolicyEvaluationPoint; +import io.entgra.device.mgt.core.policy.mgt.common.PolicyManagementException; +import io.entgra.device.mgt.core.policy.mgt.core.enforcement.DelegationTask; +import io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementDataHolder; +import io.entgra.device.mgt.core.policy.mgt.core.mgt.MonitoringManager; +import io.entgra.device.mgt.core.policy.mgt.core.mgt.impl.MonitoringManagerImpl; +import io.entgra.device.mgt.core.policy.mgt.core.mock.TestHeartBeatManagementService; +import io.entgra.device.mgt.core.policy.mgt.core.mock.TypeXDeviceManagementService; +import io.entgra.device.mgt.core.policy.mgt.core.task.MonitoringTask; +import io.entgra.device.mgt.core.policy.mgt.core.task.TaskScheduleService; +import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagementConstants; +import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.sql.Timestamp; import java.util.ArrayList; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/FeatureManagerImplTest.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/FeatureManagerImplTest.java index f939231650..8671f74508 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/FeatureManagerImplTest.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/FeatureManagerImplTest.java @@ -17,6 +17,14 @@ */ package io.entgra.device.mgt.core.policy.mgt.core.mgt.impl; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManager; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Profile; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; +import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService; +import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationManagerImpl; import io.entgra.device.mgt.core.policy.mgt.common.FeatureManagementException; import io.entgra.device.mgt.core.policy.mgt.core.BasePolicyManagementDAOTest; import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerServiceImpl; @@ -33,14 +41,6 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.internal.collections.Pair; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManager; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Profile; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; -import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService; -import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationManagerImpl; import javax.sql.DataSource; import java.sql.Connection; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/MonitoringManagerImplTest.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/MonitoringManagerImplTest.java index 37bf27d664..26d834ffd2 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/MonitoringManagerImplTest.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/MonitoringManagerImplTest.java @@ -18,6 +18,21 @@ package io.entgra.device.mgt.core.policy.mgt.core.mgt.impl; +import io.entgra.device.mgt.core.device.mgt.common.Device; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManager; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.DeviceGroupWrapper; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Profile; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.ComplianceFeature; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; +import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService; +import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationManagerImpl; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.policy.mgt.core.BasePolicyManagementDAOTest; import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerServiceImpl; @@ -42,21 +57,6 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.internal.collections.Pair; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManager; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.DeviceGroupWrapper; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Profile; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.ComplianceFeature; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; -import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService; -import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationManagerImpl; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import javax.sql.DataSource; import java.lang.reflect.Field; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/ProfileManagerImplTest.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/ProfileManagerImplTest.java index 3fe0cad3cf..afcf4b82d3 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/ProfileManagerImplTest.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/ProfileManagerImplTest.java @@ -17,6 +17,14 @@ */ package io.entgra.device.mgt.core.policy.mgt.core.mgt.impl; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManager; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Profile; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; +import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService; +import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationManagerImpl; import io.entgra.device.mgt.core.policy.mgt.common.ProfileManagementException; import io.entgra.device.mgt.core.policy.mgt.core.BasePolicyManagementDAOTest; import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerServiceImpl; @@ -32,14 +40,6 @@ import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.internal.collections.Pair; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; -import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; -import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManager; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Profile; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; -import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService; -import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationManagerImpl; import javax.sql.DataSource; import java.sql.Connection; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mock/TestHeartBeatManagementService.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mock/TestHeartBeatManagementService.java index 2254ea57ee..305368ac79 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mock/TestHeartBeatManagementService.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mock/TestHeartBeatManagementService.java @@ -18,11 +18,11 @@ package io.entgra.device.mgt.core.policy.mgt.core.mock; +import io.entgra.device.mgt.core.device.mgt.common.ServerCtxInfo; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.dto.ServerContext; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; -import io.entgra.device.mgt.core.device.mgt.common.ServerCtxInfo; import java.util.Map; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mock/TestPolicyMonitoringManager.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mock/TestPolicyMonitoringManager.java index 6a7f83499d..739aedda49 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mock/TestPolicyMonitoringManager.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mock/TestPolicyMonitoringManager.java @@ -17,14 +17,14 @@ */ package io.entgra.device.mgt.core.policy.mgt.core.mock; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.PolicyMonitoringManager; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.ComplianceFeature; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.NonComplianceData; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.util.ArrayList; import java.util.List; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/services/PolicyMonitoringManagerTest.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/services/PolicyMonitoringManagerTest.java index ea01630c29..f65a23fc21 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/services/PolicyMonitoringManagerTest.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/services/PolicyMonitoringManagerTest.java @@ -19,8 +19,6 @@ package io.entgra.device.mgt.core.policy.mgt.core.services; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.PolicyMonitoringManager; @@ -28,6 +26,8 @@ import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.ComplianceFeature; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.NonComplianceData; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.util.ArrayList; import java.util.List; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/services/SimplePolicyEvaluationTest.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/services/SimplePolicyEvaluationTest.java index ed712b40dd..2846432c6b 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/services/SimplePolicyEvaluationTest.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/services/SimplePolicyEvaluationTest.java @@ -19,14 +19,14 @@ package io.entgra.device.mgt.core.policy.mgt.core.services; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; import io.entgra.device.mgt.core.policy.mgt.common.*; import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerService; import io.entgra.device.mgt.core.policy.mgt.core.PolicyManagerServiceImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; import java.util.Collections; import java.util.List; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/task/TaskSchedulerServiceImplTest.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/task/TaskSchedulerServiceImplTest.java index 23fc0ab994..8235774c6e 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/task/TaskSchedulerServiceImplTest.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/task/TaskSchedulerServiceImplTest.java @@ -18,6 +18,8 @@ package io.entgra.device.mgt.core.policy.mgt.core.task; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; +import io.entgra.device.mgt.core.device.mgt.core.config.policy.PolicyConfiguration; import io.entgra.device.mgt.core.policy.mgt.common.PolicyMonitoringTaskException; import io.entgra.device.mgt.core.policy.mgt.core.internal.PolicyManagementDataHolder; import io.entgra.device.mgt.core.policy.mgt.core.util.PolicyManagementConstants; @@ -27,8 +29,6 @@ import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; -import io.entgra.device.mgt.core.device.mgt.core.config.policy.PolicyConfiguration; import org.wso2.carbon.ntask.common.TaskException; import org.wso2.carbon.ntask.core.TaskInfo; import org.wso2.carbon.ntask.core.TaskManager; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql index 0086d545d2..57d0c487cc 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql @@ -1,3 +1,51 @@ + DROP VIEW IF EXISTS FEATURE_NON_COMPLIANCE_INFO; + ALTER TABLE IF EXISTS DM_DEVICE DROP CONSTRAINT IF EXISTS fk_DM_DEVICE_DM_DEVICE_TYPE2; +-- ALTER TABLE IF EXISTS DM_DEVICE_TYPE_PLATFORM DROP CONSTRAINT IF EXISTS DM_DEVICE_TYPE_DM_DEVICE_TYPE_PLATFORM_MAPPING; + ALTER TABLE IF EXISTS DM_ROLE_GROUP_MAP DROP CONSTRAINT IF EXISTS FK_DM_ROLE_GROUP_MAP_DM_GROUP2; + ALTER TABLE IF EXISTS DM_DEVICE_GROUP_MAP DROP CONSTRAINT IF EXISTS FK_DM_DEVICE_GROUP_MAP_DM_GROUP2; + ALTER TABLE IF EXISTS DM_DEVICE_GROUP_POLICY DROP CONSTRAINT IF EXISTS FK_DM_DEVICE_GROUP_POLICY; +-- ALTER TABLE IF EXISTS DM_GEOFENCE_GROUP_MAPPING DROP CONSTRAINT IF EXISTS FK_DM_GEOFENCE_GROUP_MAPPING_GROUP; +-- ALTER TABLE IF EXISTS DM_DEVICE_EVENT_GROUP_MAPPING DROP CONSTRAINT IF EXISTS FK_DM_EVENT_GROUP_MAPPING_GROUP; + + ALTER TABLE IF EXISTS DM_DEVICE_GROUP_MAP DROP CONSTRAINT IF EXISTS FK_DM_DEVICE_GROUP_MAP_DM_DEVICE2; + ALTER TABLE IF EXISTS DM_ENROLMENT DROP CONSTRAINT IF EXISTS FK_DM_DEVICE_ENROLMENT; + ALTER TABLE IF EXISTS DM_DEVICE_STATUS DROP CONSTRAINT IF EXISTS FK_DM_DEVICE_STATUS_DEVICE; + ALTER TABLE IF EXISTS DM_DEVICE_POLICY DROP CONSTRAINT IF EXISTS FK_DEVICE_DEVICE_POLICY; + ALTER TABLE IF EXISTS DM_DEVICE_POLICY_APPLIED DROP CONSTRAINT IF EXISTS FK_DM_POLICY_DEVCIE_APPLIED; + ALTER TABLE IF EXISTS DM_APPLICATION DROP CONSTRAINT IF EXISTS FK_DM_DEVICE; + ALTER TABLE IF EXISTS DM_NOTIFICATION DROP CONSTRAINT IF EXISTS FK_DM_DEVICE_NOTIFICATION; + ALTER TABLE IF EXISTS DM_DEVICE_INFO DROP CONSTRAINT IF EXISTS DM_DEVICE_INFO_DEVICE; + ALTER TABLE IF EXISTS DM_DEVICE_LOCATION DROP CONSTRAINT IF EXISTS DM_DEVICE_LOCATION_DEVICE; + ALTER TABLE IF EXISTS DM_DEVICE_DETAIL DROP CONSTRAINT IF EXISTS FK_DM_DEVICE_DETAILS_DEVICE; + + ALTER TABLE IF EXISTS DM_ENROLMENT_OP_MAPPING DROP CONSTRAINT IF EXISTS FK_DM_DEVICE_OPERATION_MAPPING_OPERATION; + ALTER TABLE IF EXISTS DM_DEVICE_OPERATION_RESPONSE DROP CONSTRAINT IF EXISTS FK_DM_DEVICE_OPERATION_RESPONSE_OPERATION; + + ALTER TABLE IF EXISTS DM_DEVICE_STATUS DROP CONSTRAINT IF EXISTS FK_DM_DEVICE_STATUS_ENROLMENT; + ALTER TABLE IF EXISTS DM_ENROLMENT_OP_MAPPING DROP CONSTRAINT IF EXISTS FK_DM_DEVICE_OPERATION_MAPPING_DEVICE; + ALTER TABLE IF EXISTS DM_DEVICE_OPERATION_RESPONSE DROP CONSTRAINT IF EXISTS FK_DM_DEVICE_OPERATION_RESPONSE_ENROLLMENT; + ALTER TABLE IF EXISTS DM_APPLICATION DROP CONSTRAINT IF EXISTS FK_DM_ENROLEMENT; + ALTER TABLE IF EXISTS DM_DEVICE_INFO DROP CONSTRAINT IF EXISTS DM_DEVICE_INFO_DEVICE_ENROLLMENT; + ALTER TABLE IF EXISTS DM_DEVICE_LOCATION DROP CONSTRAINT IF EXISTS DM_DEVICE_LOCATION_DM_ENROLLMENT; + ALTER TABLE IF EXISTS DM_DEVICE_DETAIL DROP CONSTRAINT IF EXISTS FK_DM_ENROLMENT_DEVICE_DETAILS; + ALTER TABLE IF EXISTS DM_DEVICE_OPERATION_RESPONSE DROP CONSTRAINT IF EXISTS FK_DM_EN_OP_MAP_RESPONSE; + ALTER TABLE IF EXISTS DM_DEVICE_OPERATION_RESPONSE_LARGE DROP CONSTRAINT IF EXISTS FK_DM_EN_OP_MAP_RESPONSE_LARGE; + ALTER TABLE IF EXISTS DM_DEVICE_OPERATION_RESPONSE_LARGE DROP CONSTRAINT IF EXISTS FK_DM_DEVICE_OPERATION_RESPONSE_LARGE_MAPPING; +-- + ALTER TABLE IF EXISTS DM_POLICY DROP CONSTRAINT IF EXISTS FK_DM_PROFILE_DM_POLICY; + ALTER TABLE IF EXISTS DM_PROFILE_FEATURES DROP CONSTRAINT IF EXISTS FK_DM_PROFILE_DM_POLICY_FEATURES; +-- + ALTER TABLE IF EXISTS DM_DEVICE_POLICY DROP CONSTRAINT IF EXISTS FK_POLICY_DEVICE_POLICY; + ALTER TABLE IF EXISTS DM_DEVICE_TYPE_POLICY DROP CONSTRAINT IF EXISTS FK_DEVICE_TYPE_POLICY; + ALTER TABLE IF EXISTS DM_POLICY_CORRECTIVE_ACTION DROP CONSTRAINT IF EXISTS FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION; + ALTER TABLE IF EXISTS DM_ROLE_POLICY DROP CONSTRAINT IF EXISTS FK_ROLE_POLICY_POLICY; + ALTER TABLE IF EXISTS DM_USER_POLICY DROP CONSTRAINT IF EXISTS DM_POLICY_USER_POLICY; + ALTER TABLE IF EXISTS DM_POLICY_CRITERIA DROP CONSTRAINT IF EXISTS FK_POLICY_POLICY_CRITERIA; + ALTER TABLE IF EXISTS DM_DEVICE_GROUP_POLICY DROP CONSTRAINT IF EXISTS FK_DM_DEVICE_GROUP_DM_POLICY; + ALTER TABLE IF EXISTS DM_POLICY_CRITERIA DROP CONSTRAINT IF EXISTS FK_CRITERIA_POLICY_CRITERIA; + ALTER TABLE IF EXISTS DM_POLICY_CRITERIA_PROPERTIES DROP CONSTRAINT IF EXISTS FK_POLICY_CRITERIA_PROPERTIES; + ALTER TABLE IF EXISTS DM_POLICY_COMPLIANCE_FEATURES DROP CONSTRAINT IF EXISTS FK_COMPLIANCE_FEATURES_STATUS; + DROP TABLE IF EXISTS DM_DEVICE_TYPE; CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( ID INT AUTO_INCREMENT NOT NULL, @@ -17,12 +65,22 @@ CREATE TABLE IF NOT EXISTS DM_GROUP ( STATUS VARCHAR(50) DEFAULT NULL, DATE_OF_CREATE BIGINT DEFAULT NULL, DATE_OF_LAST_UPDATE BIGINT DEFAULT NULL, - OWNER VARCHAR(45) DEFAULT NULL, + OWNER VARCHAR(255) DEFAULT NULL, PARENT_PATH VARCHAR(255) DEFAULT NULL, TENANT_ID INTEGER DEFAULT 0, PARENT_GROUP_ID INTEGER DEFAULT 0, PRIMARY KEY (ID) ); + DROP TABLE IF EXISTS DM_ROLE_GROUP_MAP; + CREATE TABLE IF NOT EXISTS DM_ROLE_GROUP_MAP ( + ID INTEGER AUTO_INCREMENT NOT NULL, + GROUP_ID INTEGER DEFAULT NULL, + ROLE VARCHAR(45) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID), + CONSTRAINT fk_DM_ROLE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID) + REFERENCES DM_GROUP (ID) ON DELETE CASCADE ON UPDATE CASCADE + ); DROP TABLE IF EXISTS DM_DEVICE_CERTIFICATE; CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( @@ -39,13 +97,14 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE ( ID INTEGER auto_increment NOT NULL, DESCRIPTION TEXT DEFAULT NULL, NAME VARCHAR(100) DEFAULT NULL, - DEVICE_TYPE_ID INT(11) DEFAULT NULL, + DEVICE_TYPE_ID INT DEFAULT NULL, DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (ID), - CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID ) - REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION + CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID) + REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT uk_DM_DEVICE UNIQUE (NAME, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, TENANT_ID) ); DROP TABLE IF EXISTS DM_DEVICE_PROPERTIES; @@ -54,8 +113,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_PROPERTIES ( DEVICE_IDENTIFICATION VARCHAR(300) NOT NULL, PROPERTY_NAME VARCHAR(100) DEFAULT 0, PROPERTY_VALUE VARCHAR(100) DEFAULT NULL, - TENANT_ID VARCHAR(100) DEFAULT NULL, - PRIMARY KEY (DEVICE_TYPE_NAME, DEVICE_IDENTIFICATION, PROPERTY_NAME) + TENANT_ID VARCHAR(100), + PRIMARY KEY (DEVICE_TYPE_NAME, DEVICE_IDENTIFICATION, PROPERTY_NAME, TENANT_ID) ); DROP TABLE IF EXISTS GROUP_PROPERTIES; @@ -75,9 +134,9 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP ( TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (ID), CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_DEVICE2 FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + REFERENCES DM_DEVICE (ID) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID) - REFERENCES DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION + REFERENCES DM_GROUP (ID) ON DELETE CASCADE ON UPDATE CASCADE ); DROP TABLE IF EXISTS DM_OPERATION; @@ -101,7 +160,7 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( DEVICE_ID INTEGER NOT NULL, DEVICE_TYPE VARCHAR(300) NOT NULL, DEVICE_IDENTIFICATION VARCHAR(300) NOT NULL, - OWNER VARCHAR(50) NOT NULL, + OWNER VARCHAR(255) NOT NULL, OWNERSHIP VARCHAR(45) DEFAULT NULL, STATUS VARCHAR(50) NULL, IS_TRANSFERRED BOOLEAN NOT NULL DEFAULT FALSE, @@ -110,7 +169,8 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( TENANT_ID INT NOT NULL, PRIMARY KEY (ID), CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT uk_dm_device_enrolment UNIQUE (DEVICE_ID, OWNER, OWNERSHIP, TENANT_ID) ); DROP TABLE IF EXISTS DM_DEVICE_STATUS; CREATE TABLE IF NOT EXISTS DM_DEVICE_STATUS ( @@ -124,7 +184,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_STATUS ( CONSTRAINT fk_dm_device_status_device FOREIGN KEY (DEVICE_ID) REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT fk_dm_device_status_enrolment FOREIGN KEY (ENROLMENT_ID) REFERENCES - DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION + DM_ENROLMENT (ID) ON DELETE CASCADE ON UPDATE CASCADE ); DROP TABLE IF EXISTS DM_ENROLMENT_OP_MAPPING; CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING ( @@ -172,10 +232,14 @@ CREATE TABLE DM_DEVICE_OPERATION_RESPONSE_LARGE ( ID INTEGER NOT NULL, OPERATION_RESPONSE LONGBLOB DEFAULT NULL, OPERATION_ID INTEGER NOT NULL, + EN_OP_MAP_ID INTEGER NOT NULL, RECEIVED_TIMESTAMP TIMESTAMP NULL, DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, CONSTRAINT fk_dm_device_operation_response_large_mapping FOREIGN KEY (ID) REFERENCES DM_DEVICE_OPERATION_RESPONSE (ID) + ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_en_op_map_response_large FOREIGN KEY (EN_OP_MAP_ID) + REFERENCES DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); @@ -186,30 +250,25 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE ( ID INT NOT NULL AUTO_INCREMENT , PROFILE_NAME VARCHAR(45) NOT NULL , TENANT_ID INT NOT NULL , - DEVICE_TYPE VARCHAR(20) NOT NULL , + DEVICE_TYPE VARCHAR(300) NOT NULL , CREATED_TIME DATETIME NOT NULL , UPDATED_TIME DATETIME NOT NULL , - PRIMARY KEY (ID) , - CONSTRAINT DM_PROFILE_DEVICE_TYPE - FOREIGN KEY (DEVICE_TYPE ) - REFERENCES DM_DEVICE_TYPE (NAME ) - ON DELETE NO ACTION - ON UPDATE NO ACTION + PRIMARY KEY (ID) ); DROP TABLE IF EXISTS DM_POLICY; CREATE TABLE IF NOT EXISTS DM_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , + ID INT NOT NULL AUTO_INCREMENT , NAME VARCHAR(45) DEFAULT NULL , PAYLOAD_VERSION VARCHAR (45) DEFAULT NULL, DESCRIPTION VARCHAR(1000) NULL, - TENANT_ID INT(11) NOT NULL , - PROFILE_ID INT(11) NOT NULL , + TENANT_ID INT NOT NULL , + PROFILE_ID INT NOT NULL , OWNERSHIP_TYPE VARCHAR(45) NULL, COMPLIANCE VARCHAR(100) NULL, PRIORITY INT NOT NULL, - ACTIVE INT(2) NOT NULL, - UPDATED INT(1) NULL, + ACTIVE INT NOT NULL, + UPDATED INT NULL, POLICY_TYPE VARCHAR(45) NULL, PRIMARY KEY (ID) , CONSTRAINT FK_DM_PROFILE_DM_POLICY @@ -221,11 +280,11 @@ CREATE TABLE IF NOT EXISTS DM_POLICY ( DROP TABLE IF EXISTS DM_POLICY_CORRECTIVE_ACTION; CREATE TABLE IF NOT EXISTS DM_POLICY_CORRECTIVE_ACTION ( - ID INT(11) NOT NULL AUTO_INCREMENT, + ID INT NOT NULL AUTO_INCREMENT, ACTION_TYPE VARCHAR(45) NOT NULL, - CORRECTIVE_POLICY_ID INT(11) DEFAULT NULL, - POLICY_ID INT(11) NOT NULL, - FEATURE_ID INT(11) DEFAULT NULL, + CORRECTIVE_POLICY_ID INT DEFAULT NULL, + POLICY_ID INT NOT NULL, + FEATURE_ID INT DEFAULT NULL, IS_REACTIVE BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (ID), CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION @@ -238,11 +297,11 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CORRECTIVE_ACTION ( DROP TABLE IF EXISTS DM_DEVICE_POLICY; CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , - DEVICE_ID INT(11) NOT NULL , - ENROLMENT_ID INT(11) NOT NULL, + ID INT NOT NULL AUTO_INCREMENT , + DEVICE_ID INT NOT NULL , + ENROLMENT_ID INT NOT NULL, DEVICE BLOB NOT NULL, - POLICY_ID INT(11) NOT NULL , + POLICY_ID INT NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_POLICY_DEVICE_POLICY FOREIGN KEY (POLICY_ID ) @@ -258,29 +317,24 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( DROP TABLE IF EXISTS DM_DEVICE_TYPE_POLICY; CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( - ID INT(11) NOT NULL , - DEVICE_TYPE VARCHAR(20) NOT NULL , - POLICY_ID INT(11) NOT NULL , + ID INT NOT NULL , + DEVICE_TYPE VARCHAR(300) NOT NULL , + POLICY_ID INT NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_DEVICE_TYPE_POLICY FOREIGN KEY (POLICY_ID ) REFERENCES DM_POLICY (ID ) ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT FK_DEVICE_TYPE_POLICY_DEVICE_TYPE - FOREIGN KEY (DEVICE_TYPE ) - REFERENCES DM_DEVICE_TYPE (NAME) - ON DELETE NO ACTION ON UPDATE NO ACTION ); DROP TABLE IF EXISTS DM_PROFILE_FEATURES; CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( - ID INT(11) NOT NULL AUTO_INCREMENT, - PROFILE_ID INT(11) NOT NULL, + ID INT NOT NULL AUTO_INCREMENT, + PROFILE_ID INT NOT NULL, FEATURE_CODE VARCHAR(100) NOT NULL, - DEVICE_TYPE VARCHAR(20) NOT NULL, - TENANT_ID INT(11) NOT NULL , + DEVICE_TYPE VARCHAR(300) NOT NULL, + TENANT_ID INT NOT NULL , CONTENT BLOB NULL DEFAULT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES @@ -292,9 +346,9 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( DROP TABLE IF EXISTS DM_ROLE_POLICY; CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , + ID INT NOT NULL AUTO_INCREMENT , ROLE_NAME VARCHAR(45) NOT NULL , - POLICY_ID INT(11) NOT NULL , + POLICY_ID INT NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_ROLE_POLICY_POLICY FOREIGN KEY (POLICY_ID ) @@ -320,11 +374,11 @@ DROP TABLE IF EXISTS DM_DEVICE_POLICY_APPLIED; CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( ID INT NOT NULL AUTO_INCREMENT , DEVICE_ID INT NOT NULL , - ENROLMENT_ID INT(11) NOT NULL, + ENROLMENT_ID INT NOT NULL, POLICY_ID INT NOT NULL , POLICY_CONTENT TEXT NULL , TENANT_ID INT NOT NULL, - APPLIED TINYINT(1) NULL , + APPLIED TINYINT NULL , CREATED_TIME TIMESTAMP NULL , UPDATED_TIME TIMESTAMP NULL , APPLIED_TIME TIMESTAMP NULL , @@ -381,7 +435,7 @@ DROP TABLE IF EXISTS DM_POLICY_COMPLIANCE_STATUS; CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( ID INT NOT NULL AUTO_INCREMENT, DEVICE_ID INT NOT NULL, - ENROLMENT_ID INT(11) NOT NULL, + ENROLMENT_ID INT NOT NULL, POLICY_ID INT NOT NULL, TENANT_ID INT NOT NULL, STATUS INT NULL, @@ -396,8 +450,8 @@ DROP TABLE IF EXISTS DM_POLICY_CHANGE_MGT; CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( ID INT NOT NULL AUTO_INCREMENT, POLICY_ID INT NOT NULL, - DEVICE_TYPE VARCHAR(20) NOT NULL, - TENANT_ID INT(11) NOT NULL, + DEVICE_TYPE VARCHAR(300) NOT NULL, + TENANT_ID INT NOT NULL, PRIMARY KEY (ID) ); @@ -428,7 +482,7 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION ( LOCATION_URL VARCHAR(100) DEFAULT NULL, IMAGE_URL VARCHAR(100) DEFAULT NULL, APP_PROPERTIES BLOB NULL, - MEMORY_USAGE INTEGER(10) NULL, + MEMORY_USAGE INTEGER NULL, IS_ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, DEVICE_ID INTEGER NOT NULL, ENROLMENT_ID INTEGER NOT NULL, @@ -439,7 +493,7 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION ( REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT FK_DM_APP_MAP_DM_ENROL + CONSTRAINT fk_dm_enrolement FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT (ID) ON DELETE NO ACTION @@ -456,12 +510,11 @@ CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( OPERATION_ID INTEGER NOT NULL, TENANT_ID INTEGER NOT NULL, STATUS VARCHAR(10) NULL, - DESCRIPTION VARCHAR(100) NULL, + DESCRIPTION VARCHAR(1000) NULL, + LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, PRIMARY KEY (NOTIFICATION_ID), CONSTRAINT fk_dm_device_notification FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT fk_dm_operation_notification FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); -- NOTIFICATION TABLE END -- @@ -499,7 +552,11 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( STATE VARCHAR(45) NULL, COUNTRY VARCHAR(45) NULL, GEO_HASH VARCHAR(45) NULL, - UPDATE_TIMESTAMP BIGINT(15) NOT NULL, + UPDATE_TIMESTAMP BIGINT NOT NULL, + ALTITUDE DOUBLE NULL, + SPEED FLOAT NULL, + BEARING FLOAT NULL, + DISTANCE DOUBLE NULL, PRIMARY KEY (ID), CONSTRAINT DM_DEVICE_LOCATION_DEVICE FOREIGN KEY (DEVICE_ID) @@ -512,6 +569,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( ON DELETE NO ACTION ON UPDATE NO ACTION ); +DROP INDEX IF EXISTS DM_DEVICE_LOCATION_GEO_hashx; +CREATE INDEX DM_DEVICE_LOCATION_GEO_hashx ON DM_DEVICE_LOCATION(GEO_HASH ASC); DROP TABLE IF EXISTS DM_DEVICE_DETAIL; CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( @@ -532,8 +591,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( CPU_USAGE DECIMAL(5) NULL, TOTAL_RAM_MEMORY DECIMAL(30,3) NULL, AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL, - PLUGGED_IN INT(1) NULL, - UPDATE_TIMESTAMP BIGINT(15) NOT NULL, + PLUGGED_IN INT NULL, + UPDATE_TIMESTAMP BIGINT NOT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE FOREIGN KEY (DEVICE_ID) @@ -558,15 +617,14 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY ( CONSTRAINT FK_DM_DEVICE_GROUP_POLICY FOREIGN KEY (DEVICE_GROUP_ID) REFERENCES DM_GROUP (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION, + ON DELETE CASCADE + ON UPDATE CASCADE , CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY FOREIGN KEY (POLICY_ID) REFERENCES DM_POLICY (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION + ON DELETE CASCADE + ON UPDATE CASCADE ); - -- END OF POLICY AND DEVICE GROUP MAPPING -- -- DASHBOARD RELATED VIEWS -- diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/user-test/user-mgt-registry-test.xml b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/user-test/user-mgt-registry-test.xml index fc32a2698d..96fd6acfff 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/user-test/user-mgt-registry-test.xml +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/user-test/user-mgt-registry-test.xml @@ -27,7 +27,7 @@ everyone false 500 - jdbc:h2:target/databasetest/CARBON_TEST + jdbc:h2:./target/databasetest/CARBON_TEST org.h2.Driver 50 60000 diff --git a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/pom.xml b/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/pom.xml deleted file mode 100644 index 55d6b6e3a1..0000000000 --- a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/pom.xml +++ /dev/null @@ -1,110 +0,0 @@ - - - - - - - io.entgra.device.mgt.core - policy-mgt - 5.0.0-SNAPSHOT - ../pom.xml - - - 4.0.0 - io.entgra.device.mgt.core - org.wso2.carbon.complex.policy.decision.point - bundle - WSO2 Carbon - Policy Decision Point - WSO2 Carbon - Policy Decision Point - http://wso2.org - - - - - org.apache.felix - maven-scr-plugin - - - org.apache.felix - maven-bundle-plugin - 1.4.0 - true - - - ${project.artifactId} - ${project.artifactId} - ${io.entgra.device.mgt.core.version} - Complex Policy Decision Point Bundle - org.wso2.carbon.complex.policy.decision.point.internal - - org.wso2.carbon.complex.policy.decision.point.* - - - - - - org.jacoco - jacoco-maven-plugin - - ${basedir}/target/coverage-reports/jacoco-unit.exec - - - - jacoco-initialize - - prepare-agent - - - - jacoco-site - test - - report - - - ${basedir}/target/coverage-reports/jacoco-unit.exec - ${basedir}/target/coverage-reports/site - - - - - - - - - - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.equinox - org.eclipse.equinox.common - - - org.wso2.carbon - org.wso2.carbon.logging - - - io.entgra.device.mgt.core - io.entgra.device.mgt.core.policy.mgt.common - - - - - diff --git a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/FeatureFilter.java b/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/FeatureFilter.java deleted file mode 100644 index 50fb7a54a4..0000000000 --- a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/FeatureFilter.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you 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.wso2.carbon.policy.evaluator; - -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; - -import java.util.List; - -public interface FeatureFilter { - - List evaluate(List policyList, List featureRulesList); - - List extractFeatures(List policyList); - - List evaluateFeatures(List featureList, List featureRulesList); - - void getDenyOverridesFeatures(String featureName, List featureList, List effectiveFeatureList); - - void getPermitOverridesFeatures(String featureName, List featureList, List effectiveFeatureList); - - void getFirstApplicableFeatures(String featureName, List featureList, List effectiveFeatureList); - - void getLastApplicableFeatures(String featureName, List featureList, List effectiveFeatureList); - - void getAllApplicableFeatures(String featureName, List featureList, List effectiveFeatureList); - - void getHighestApplicableFeatures(String featureName, List featureList, List effectiveFeatureList); - - void getLowestApplicableFeatures(String featureName, List featureList, List effectiveFeatureList); -} diff --git a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/FeatureFilterImpl.java b/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/FeatureFilterImpl.java deleted file mode 100644 index e6eb914312..0000000000 --- a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/FeatureFilterImpl.java +++ /dev/null @@ -1,250 +0,0 @@ -/* -* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you 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.wso2.carbon.policy.evaluator; - -import org.wso2.carbon.policy.evaluator.utils.Constants; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature; - -import java.util.ArrayList; -import java.util.List; - -/** - * This class is responsible for evaluating the policy (Configurations sets) and returning - * the effective features set. - */ - -public class FeatureFilterImpl implements FeatureFilter { - - /** - * This method returns the effective feature list when policy list and feature aggregation rules are supplied. - * @param policyList - * @param featureRulesList - * @return - */ - @Override - public List evaluate(List policyList, List featureRulesList) { - return evaluateFeatures(extractFeatures(policyList), featureRulesList); - } - - /** - * This method extract the features from the given policy list in the order they are provided in the list. - * @param policyList - * @return - */ - public List extractFeatures(List policyList) { - List featureList = new ArrayList(); - for (Policy policy : policyList) { - featureList.addAll(policy.getProfile().getProfileFeaturesList()); - } - return featureList; - } - - /** - * This method is responsible for supplying tasks to other methods to evaluate given features. - * @param featureList - * @param featureRulesList - * @return - */ - public List evaluateFeatures(List featureList, List featureRulesList) { - List effectiveFeatureList = new ArrayList(); - for (FeatureRules rule : featureRulesList) { - String ruleName = rule.getEvaluationCriteria(); - String featureName = rule.getName(); - if (Constants.DENY_OVERRIDES.equalsIgnoreCase(ruleName)) { - getDenyOverridesFeatures(featureName, featureList, effectiveFeatureList); - } - if (Constants.PERMIT_OVERRIDES.equalsIgnoreCase(ruleName)) { - getPermitOverridesFeatures(featureName, featureList, effectiveFeatureList); - } - if (Constants.FIRST_APPLICABLE.equalsIgnoreCase(ruleName)) { - getFirstApplicableFeatures(featureName, featureList, effectiveFeatureList); - } - if (Constants.LAST_APPLICABLE.equalsIgnoreCase(ruleName)) { - getLastApplicableFeatures(featureName, featureList, effectiveFeatureList); - } - if (Constants.ALL_APPLICABLE.equalsIgnoreCase(ruleName)) { - getAllApplicableFeatures(featureName, featureList, effectiveFeatureList); - } - if (Constants.HIGHEST_APPLICABLE.equalsIgnoreCase(ruleName)) { - getHighestApplicableFeatures(featureName, featureList, effectiveFeatureList); - } - if (Constants.LOWEST_APPLICABLE.equalsIgnoreCase(ruleName)) { - getLowestApplicableFeatures(featureName, featureList, effectiveFeatureList); - } - } - return effectiveFeatureList; - } - - /** - * This method picks up denied features, if there is no denied features it will add to the list, the final permitted feature. - * But if given policies do not have features of given type, it will not add anything. - * - * @param featureName - * @param featureList - * @param effectiveFeatureList - */ - public void getDenyOverridesFeatures(String featureName, List featureList, List effectiveFeatureList) { - ProfileFeature evaluatedFeature = null; -// for (ProfileFeature feature : featureList) { -// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) { -// if (feature.getFeature().getRuleValue().equalsIgnoreCase("Deny")) { -// evaluatedFeature = feature; -// effectiveFeatureList.add(evaluatedFeature); -// return; -// } else { -// evaluatedFeature = feature; -// } -// } -// } - if (evaluatedFeature != null) { - effectiveFeatureList.add(evaluatedFeature); - } - - } - - /** - * This method picks up permitted features, if there is no permitted features it will add to the list, the final denied feature. - * But if given policies do not have features of given type, it will not add anything. - * - * @param featureName - * @param featureList - * @param effectiveFeatureList - */ - public void getPermitOverridesFeatures(String featureName, List featureList, List effectiveFeatureList) { - ProfileFeature evaluatedFeature = null; -// for (ProfileFeature feature : featureList) { -// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) { -// if (feature.getFeature().getRuleValue().equalsIgnoreCase("Permit")) { -// evaluatedFeature = feature; -// effectiveFeatureList.add(evaluatedFeature); -// return; -// } else { -// evaluatedFeature = feature; -// } -// } -// } - if (evaluatedFeature != null) { - effectiveFeatureList.add(evaluatedFeature); - } - - } - - /** - * This method picks the first features of the give type. - * But if given policies do not have features of given type, it will not add anything. - * - * @param featureName - * @param featureList - * @param effectiveFeatureList - */ - public void getFirstApplicableFeatures(String featureName, List featureList, List effectiveFeatureList) { - for (ProfileFeature feature : featureList) { -// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) { -// effectiveFeatureList.add(feature); -// return; -// -// } - } - } - - /** - * This method picks the last features of the give type. - * But if given policies do not have features of given type, it will not add anything. - * - * @param featureName - * @param featureList - * @param effectiveFeatureList - */ - public void getLastApplicableFeatures(String featureName, List featureList, List effectiveFeatureList) { - ProfileFeature evaluatedFeature = null; -// for (ProfileFeature feature : featureList) { -// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) { -// evaluatedFeature = feature; -// } -// } - if (evaluatedFeature != null) { - effectiveFeatureList.add(evaluatedFeature); - } - } - - /** - * This method picks the all features of the give type. - * But if given policies do not have features of given type, it will not add anything. - * - * @param featureName - * @param featureList - * @param effectiveFeatureList - */ - public void getAllApplicableFeatures(String featureName, List featureList, List effectiveFeatureList) { - for (ProfileFeature feature : featureList) { -// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) { -// effectiveFeatureList.add(feature); -// } - } - } - - /** - * This method picks the feature with the highest value of given type. - * But if given policies do not have features of given type, it will not add anything. - * - * @param featureName - * @param featureList - * @param effectiveFeatureList - */ - public void getHighestApplicableFeatures(String featureName, List featureList, List effectiveFeatureList) { - ProfileFeature evaluatedFeature = null; - int intValve = 0; -// for (ProfileFeature feature : featureList) { -// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) { -// if (Integer.parseInt(feature.getFeature().getRuleValue()) > intValve) { -// intValve = Integer.parseInt(feature.getFeature().getRuleValue()); -// evaluatedFeature = feature; -// } -// } -// } - if (evaluatedFeature != null) { - effectiveFeatureList.add(evaluatedFeature); - } - } - - /** - * This method picks the feature with the lowest value of given type. - * But if given policies do not have features of given type, it will not add anything. - * - * @param featureName - * @param featureList - * @param effectiveFeatureList - */ - public void getLowestApplicableFeatures(String featureName, List featureList, List effectiveFeatureList) { - ProfileFeature evaluatedFeature = null; -// int intValve = 0; -// for (ProfileFeature feature : featureList) { -// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) { -// if (Integer.parseInt(feature.getFeature().getRuleValue()) < intValve) { -// intValve = Integer.parseInt(feature.getFeature().getRuleValue()); -// evaluatedFeature = feature; -// } -// } -// } - if (evaluatedFeature != null) { - effectiveFeatureList.add(evaluatedFeature); - } - } -} diff --git a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/FeatureRules.java b/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/FeatureRules.java deleted file mode 100644 index f706cf947f..0000000000 --- a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/FeatureRules.java +++ /dev/null @@ -1,41 +0,0 @@ -/* -* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you 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.wso2.carbon.policy.evaluator; - -public class FeatureRules { - - private String name; - private String evaluationCriteria; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getEvaluationCriteria() { - return evaluationCriteria; - } - - public void setEvaluationCriteria(String evaluationCriteria) { - this.evaluationCriteria = evaluationCriteria; - } -} diff --git a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/PDPException.java b/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/PDPException.java deleted file mode 100644 index 571f9c6848..0000000000 --- a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/PDPException.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.policy.evaluator; - -public class PDPException extends Exception { - - private String pdpErrorMessage; - - public String getPdpErrorMessage() { - return pdpErrorMessage; - } - - public void setPdpErrorMessage(String pdpErrorMessage) { - this.pdpErrorMessage = pdpErrorMessage; - } - - public PDPException(String message) { - setPdpErrorMessage(message); - } - - public PDPException(String message, Exception ex) { - super(message, ex); - setPdpErrorMessage(message); - } - - public PDPException(String message, Throwable cause) { - super(message, cause); - setPdpErrorMessage(message); - } - - public PDPException(Throwable cause) { - super(cause); - } - - public PDPException(){ - super(); - } -} diff --git a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/PDPServiceImpl.java b/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/PDPServiceImpl.java deleted file mode 100644 index 82421c9f03..0000000000 --- a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/PDPServiceImpl.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.policy.evaluator; - -import org.wso2.carbon.policy.evaluator.spi.PDPService; -import io.entgra.device.mgt.core.policy.mgt.common.Feature; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; - -import java.util.List; - -public class PDPServiceImpl implements PDPService { - @Override - public List getEffectivePolicyList(List policies, List roles, String deviceType) { - return null; - } - - @Override - public List getEffectiveFeatureList(List policies, List featureRulesList) { - return null; - } -} diff --git a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/PolicyFilter.java b/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/PolicyFilter.java deleted file mode 100644 index 84b6cac51e..0000000000 --- a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/PolicyFilter.java +++ /dev/null @@ -1,43 +0,0 @@ -/* -* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you 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.wso2.carbon.policy.evaluator; - -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; - -import java.util.List; - -public interface PolicyFilter { - - /** - * This method will extract the policies related a given roles list from the policy list available. - * @param policyList - * @param roles - * @return - */ - public List extractPoliciesRelatedToRoles(List policyList, List roles); - - /** - * This mehtod extract the policies related to a given device type from policy list. - * @param policyList - * @param deviceType - * @return - */ - public List extractPoliciesRelatedToDeviceType(List policyList, String deviceType); -} diff --git a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/PolicyFilterImpl.java b/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/PolicyFilterImpl.java deleted file mode 100644 index 37818b7461..0000000000 --- a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/PolicyFilterImpl.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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.wso2.carbon.policy.evaluator; - -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; - -import java.util.ArrayList; -import java.util.List; - -public class PolicyFilterImpl implements PolicyFilter { - - - /** - * This method will extract the policies related a given roles list from the policy list available. - * - * @param policyList - * @param roles - * @return - */ - @Override - public List extractPoliciesRelatedToRoles(List policyList, List roles) { - - List policies = new ArrayList<>(); - - for (Policy policy : policyList) { - List roleList = policy.getRoles(); - - for (String role : roleList) { - if (roles.contains(role)) { - policies.add(policy); - break; - } - } - } - return policies; - } - - /** - * This mehtod extract the policies related to a given device type from policy list. - * - * @param policyList - * @param deviceType - * @return - */ - @Override - public List extractPoliciesRelatedToDeviceType(List policyList, String deviceType) { - List policies = new ArrayList<>(); - - for (Policy policy : policyList) { - if (policy.getProfile().getDeviceType().equalsIgnoreCase(deviceType)) { - policies.add(policy); - } - } - return policies; - } -} diff --git a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/spi/PDPService.java b/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/spi/PDPService.java deleted file mode 100644 index ea43abb397..0000000000 --- a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/spi/PDPService.java +++ /dev/null @@ -1,34 +0,0 @@ -/* -* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you 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.wso2.carbon.policy.evaluator.spi; - - -import org.wso2.carbon.policy.evaluator.FeatureRules; -import io.entgra.device.mgt.core.policy.mgt.common.Feature; -import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; - -import java.util.List; - -public interface PDPService { - - List getEffectivePolicyList(List policies, List roles, String deviceType); - - List getEffectiveFeatureList(List policies, List featureRulesList); - -} diff --git a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/utils/Constants.java b/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/utils/Constants.java deleted file mode 100644 index 790fa7f246..0000000000 --- a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/utils/Constants.java +++ /dev/null @@ -1,30 +0,0 @@ -/* -* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you 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.wso2.carbon.policy.evaluator.utils; - -public class Constants { - - public static final String DENY_OVERRIDES = "deny_overrides"; - public static final String PERMIT_OVERRIDES = "permit_overrides"; - public static final String FIRST_APPLICABLE = "first_applicable"; - public static final String LAST_APPLICABLE = "last_applicable"; - public static final String ALL_APPLICABLE = "all_applicable"; - public static final String HIGHEST_APPLICABLE = "highest_applicable"; - public static final String LOWEST_APPLICABLE = "lowest_applicable"; -} diff --git a/components/policy-mgt/pom.xml b/components/policy-mgt/pom.xml index 835a0be06a..f45e96501e 100644 --- a/components/policy-mgt/pom.xml +++ b/components/policy-mgt/pom.xml @@ -31,34 +31,14 @@ policy-mgt pom WSO2 Carbon - Policy Management Component - http://wso2.org + https://entgra.io io.entgra.device.mgt.core.policy.mgt.common io.entgra.device.mgt.core.policy.mgt.core io.entgra.device.mgt.core.policy.information.point io.entgra.device.mgt.core.policy.decision.point - - - - - - org.apache.felix - maven-scr-plugin - 1.7.2 - - - generate-scr-scrdescriptor - - scr - - - - - - - diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/pom.xml b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/pom.xml index f6e0ffab5f..6785609ff1 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/pom.xml +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/pom.xml @@ -33,13 +33,13 @@ - - org.apache.felix - maven-scr-plugin - org.apache.maven.plugins maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -53,37 +53,29 @@ Subtype Management Bundle io.entgra.device.mgt.core.subtype.mgt.internal + com.fasterxml.jackson.core;version="[2.14,3)", + com.google.common.cache;version="[32.1,33)";resolution:=optional, + io.entgra.device.mgt.core.device.mgt.common.exceptions;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.config;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.config.datasource;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.service;version="[5.0,6)", + io.entgra.device.mgt.core.subtype.mgt.cache, + io.entgra.device.mgt.core.subtype.mgt.dao, + io.entgra.device.mgt.core.subtype.mgt.dao.impl, + io.entgra.device.mgt.core.subtype.mgt.dao.util, + io.entgra.device.mgt.core.subtype.mgt.dto, + io.entgra.device.mgt.core.subtype.mgt.exception, + io.entgra.device.mgt.core.subtype.mgt.impl, + io.entgra.device.mgt.core.subtype.mgt.spi, + io.entgra.device.mgt.core.subtype.mgt.util, + javax.naming, + javax.sql, + org.apache.commons.logging;version="[1.2,2)", org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.apache.commons.logging, - org.apache.commons.lang, - javax.xml, - javax.xml.stream, - javax.xml.bind.*, - javax.sql, - javax.xml.parsers; version=0.0.0, - org.w3c.dom, - javax.naming, - org.wso2.carbon.context, - org.wso2.carbon.base, - org.wso2.carbon.utils.*, - io.entgra.device.mgt.core.device.mgt.common.*, - io.entgra.device.mgt.core.device.mgt.core.*, - org.wso2.carbon.ndatasource.core, - org.wso2.carbon.registry.core, - org.wso2.carbon.registry.core.session, - org.wso2.carbon.registry.core.service, - org.wso2.carbon.registry.api, - io.entgra.device.mgt.core.device.mgt.extensions.license.mgt.registry, - javax.net.ssl, - org.wso2.carbon.core.util, - okhttp3, - org.json.*, - com.google.gson.*, - com.fasterxml.jackson.core.*, - com.fasterxml.jackson.databind.*, - com.fasterxml.jackson.annotation.*, - com.google.common.cache.*, + org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.ndatasource.core;version="[4.8,5)", + org.wso2.carbon.registry.core.service;version="[1.0,2)" !io.entgra.device.mgt.core.subtype.mgt.internal, @@ -122,6 +114,10 @@ org.apache.maven.plugins maven-surefire-plugin + + --add-opens=java.xml/jdk.xml.internal=ALL-UNNAMED + --add-opens=java.base/jdk.internal.loader=ALL-UNNAMED + file:src/test/resources/carbon-home/repository/conf/log4j.properties @@ -129,12 +125,20 @@ src/test/resources/testng.xml + + org.ops4j.pax.logging + + + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + io.entgra.device.mgt.core io.entgra.device.mgt.core.device.mgt.common @@ -164,10 +168,6 @@ org.codehaus.woodstox wstx-asl - - - - org.wso2.carbon.analytics org.wso2.carbon.analytics.api @@ -227,24 +227,14 @@ - - org.eclipse.osgi - org.eclipse.osgi - provided - - - org.eclipse.osgi - org.eclipse.osgi.services - provided - org.wso2.carbon org.wso2.carbon.core provided - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api provided @@ -268,7 +258,7 @@ provided - org.apache.tomcat.wso2 + org.wso2.orbit.org.apache.tomcat jdbc-pool provided @@ -340,19 +330,16 @@ com.google.guava guava - ${guava.version} provided - org.json + org.json.wso2 json - ${json.version} provided com.fasterxml.jackson.core jackson-databind - ${fasterxml.jackson.version} provided @@ -362,7 +349,7 @@ org.powermock - powermock-api-mockito + powermock-api-mockito2 test @@ -371,8 +358,8 @@ test - com.h2database.wso2 - h2-database-engine + org.wso2.orbit.com.h2database + h2 test @@ -406,7 +393,7 @@ test - javax.xml.bind + org.wso2.orbit.javax.xml.bind jaxb-api test diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/cache/GetDeviceSubTypeCacheLoader.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/cache/DeviceSubTypeCacheLoader.java similarity index 93% rename from components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/cache/GetDeviceSubTypeCacheLoader.java rename to components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/cache/DeviceSubTypeCacheLoader.java index 7bf985e5b9..1ac3cd593f 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/cache/GetDeviceSubTypeCacheLoader.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/cache/DeviceSubTypeCacheLoader.java @@ -31,13 +31,13 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -public class GetDeviceSubTypeCacheLoader extends CacheLoader { +public class DeviceSubTypeCacheLoader extends CacheLoader { - private static final Log log = LogFactory.getLog(GetDeviceSubTypeCacheLoader.class); + private static final Log log = LogFactory.getLog(DeviceSubTypeCacheLoader.class); private final DeviceSubTypeDAO deviceSubTypeDAO; - public GetDeviceSubTypeCacheLoader() { + public DeviceSubTypeCacheLoader() { this.deviceSubTypeDAO = DeviceSubTypeDAOFactory.getDeviceSubTypeDAO(); } diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/DeviceSubTypeDAO.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/DeviceSubTypeDAO.java index 20fa6fdd09..18e9ddba68 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/DeviceSubTypeDAO.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/DeviceSubTypeDAO.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.subtype.mgt.dao; -import io.entgra.device.mgt.core.subtype.mgt.exception.SubTypeMgtDAOException; import io.entgra.device.mgt.core.subtype.mgt.dto.DeviceSubType; +import io.entgra.device.mgt.core.subtype.mgt.exception.SubTypeMgtDAOException; import java.util.List; diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/DeviceSubTypeDAOFactory.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/DeviceSubTypeDAOFactory.java index d83558cd59..7c1d951859 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/DeviceSubTypeDAOFactory.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/DeviceSubTypeDAOFactory.java @@ -18,13 +18,13 @@ package io.entgra.device.mgt.core.subtype.mgt.dao; +import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; +import io.entgra.device.mgt.core.device.mgt.core.config.datasource.DataSourceConfig; import io.entgra.device.mgt.core.subtype.mgt.dao.impl.DeviceSubTypeDAOImpl; import io.entgra.device.mgt.core.subtype.mgt.dao.impl.DeviceSubTypeMySQLDAOImpl; +import io.entgra.device.mgt.core.subtype.mgt.dao.util.ConnectionManagerUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; -import io.entgra.device.mgt.core.subtype.mgt.dao.util.ConnectionManagerUtil; -import io.entgra.device.mgt.core.device.mgt.core.config.datasource.DataSourceConfig; import javax.sql.DataSource; import java.sql.SQLException; diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/impl/DeviceSubTypeDAOImpl.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/impl/DeviceSubTypeDAOImpl.java index 6cc2c7cac7..f3aafa5d28 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/impl/DeviceSubTypeDAOImpl.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/impl/DeviceSubTypeDAOImpl.java @@ -101,8 +101,9 @@ public class DeviceSubTypeDAOImpl implements DeviceSubTypeDAO { public DeviceSubType getDeviceSubType(String subTypeId, int tenantId, String deviceType) throws SubTypeMgtDAOException { try { - String sql = "SELECT s.*, o.OPERATION_CODE FROM DM_DEVICE_SUB_TYPE s " + - "LEFT JOIN SUB_OPERATION_TEMPLATE o on s.SUB_TYPE_ID = o.SUB_TYPE_ID " + + String sql = "SELECT s.*, o.OPERATION_CODE FROM DM_DEVICE_SUB_TYPE s " + + "LEFT JOIN SUB_OPERATION_TEMPLATE o ON s.SUB_TYPE_ID = o.SUB_TYPE_ID " + + "AND s.DEVICE_TYPE = o.DEVICE_TYPE " + "WHERE s.SUB_TYPE_ID = ? AND s.TENANT_ID = ? AND s.DEVICE_TYPE = ?"; Connection conn = ConnectionManagerUtil.getDBConnection(); @@ -143,8 +144,7 @@ public class DeviceSubTypeDAOImpl implements DeviceSubTypeDAO { stmt.setInt(1, tenantId); stmt.setString(2, deviceType); try (ResultSet rs = stmt.executeQuery()) { - List deviceSubTypes = DAOUtil.loadDeviceSubTypes(rs); - return deviceSubTypes; + return DAOUtil.loadDeviceSubTypes(rs); } } } catch (DBConnectionException e) { @@ -163,14 +163,14 @@ public class DeviceSubTypeDAOImpl implements DeviceSubTypeDAO { @Override public int getDeviceSubTypeCount(String deviceType) throws SubTypeMgtDAOException { try { - String sql = "SELECT COUNT(*) as DEVICE_COUNT FROM DM_DEVICE_SUB_TYPE WHERE DEVICE_TYPE = ? "; + String sql = "SELECT COUNT(*) as SUB_TYPE_COUNT FROM DM_DEVICE_SUB_TYPE WHERE DEVICE_TYPE = ? "; Connection conn = ConnectionManagerUtil.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, deviceType); try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { - return rs.getInt("DEVICE_COUNT"); + return rs.getInt("SUB_TYPE_COUNT"); } return 0; } @@ -252,4 +252,5 @@ public class DeviceSubTypeDAOImpl implements DeviceSubTypeDAO { throw new SubTypeMgtDAOException(msg, e); } } + } diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/util/ConnectionManagerUtil.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/util/ConnectionManagerUtil.java index 57ea6c7c1e..d7a0d31cf3 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/util/ConnectionManagerUtil.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/util/ConnectionManagerUtil.java @@ -18,12 +18,12 @@ package io.entgra.device.mgt.core.subtype.mgt.dao.util; -import io.entgra.device.mgt.core.subtype.mgt.exception.DBConnectionException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.exceptions.IllegalTransactionStateException; import io.entgra.device.mgt.core.device.mgt.core.config.datasource.DataSourceConfig; import io.entgra.device.mgt.core.device.mgt.core.config.datasource.JNDILookupDefinition; +import io.entgra.device.mgt.core.subtype.mgt.exception.DBConnectionException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import javax.naming.InitialContext; import javax.sql.DataSource; diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/util/DAOUtil.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/util/DAOUtil.java index f4569c6c36..3a1aa6fa67 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/util/DAOUtil.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dao/util/DAOUtil.java @@ -72,7 +72,7 @@ public class DAOUtil { deviceSubType = loadDeviceSubType(rs); } if (operationCode != null) { - deviceSubType.addOperationCode(operationCode); + deviceSubType.addSupportedOperation(operationCode); } deviceSubTypes.put(key, deviceSubType); } diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dto/DeviceSubType.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dto/DeviceSubType.java index cc27bb592e..e52ed3dbd0 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dto/DeviceSubType.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/dto/DeviceSubType.java @@ -24,7 +24,6 @@ import com.fasterxml.jackson.core.JsonProcessingException; import java.util.HashSet; import java.util.Set; - public abstract class DeviceSubType { private String subTypeId; @@ -32,22 +31,22 @@ public abstract class DeviceSubType { private String deviceType; private String subTypeName; private String typeDefinition; - private Set operationCodes = new HashSet<>(); + private final Set supportedOperations = new HashSet<>(); + public DeviceSubType() { } - public DeviceSubType(String subTypeId, int tenantId, String deviceType, String subTypeName, String typeDefinition, - Set operationCodes) { + public DeviceSubType(String subTypeId, int tenantId, String deviceType, + String subTypeName, String typeDefinition, + Set supportedOperations) { this.subTypeId = subTypeId; this.tenantId = tenantId; this.deviceType = deviceType; this.subTypeName = subTypeName; this.typeDefinition = typeDefinition; - if (operationCodes != null || !operationCodes.isEmpty()) { - this.operationCodes.addAll(operationCodes); + if (supportedOperations != null && !supportedOperations.isEmpty()) { + this.supportedOperations.addAll(supportedOperations); } - - } public String getSubTypeId() { @@ -94,10 +93,16 @@ public abstract class DeviceSubType { public abstract String parseSubTypeToJson() throws JsonProcessingException; - public void addOperationCode(String code) { - operationCodes.add(code); + public void setSupportedOperations(Set supportedOperations) { + this.supportedOperations.addAll(supportedOperations); } - public Set getOperationCodes() { - return operationCodes; + + public void addSupportedOperation(String code) { + supportedOperations.add(code); } + + public Set getSupportedOperations() { + return supportedOperations; + } + } diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/impl/DeviceSubTypeServiceImpl.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/impl/DeviceSubTypeServiceImpl.java index 4e5d855a23..b69664f086 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/impl/DeviceSubTypeServiceImpl.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/impl/DeviceSubTypeServiceImpl.java @@ -21,18 +21,18 @@ package io.entgra.device.mgt.core.subtype.mgt.impl; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; -import io.entgra.device.mgt.core.subtype.mgt.cache.GetDeviceSubTypeCacheLoader; +import io.entgra.device.mgt.core.subtype.mgt.cache.DeviceSubTypeCacheLoader; +import io.entgra.device.mgt.core.subtype.mgt.dao.DeviceSubTypeDAO; +import io.entgra.device.mgt.core.subtype.mgt.dao.DeviceSubTypeDAOFactory; +import io.entgra.device.mgt.core.subtype.mgt.dao.util.ConnectionManagerUtil; +import io.entgra.device.mgt.core.subtype.mgt.dto.DeviceSubType; import io.entgra.device.mgt.core.subtype.mgt.dto.DeviceSubTypeCacheKey; import io.entgra.device.mgt.core.subtype.mgt.exception.BadRequestException; import io.entgra.device.mgt.core.subtype.mgt.exception.DBConnectionException; import io.entgra.device.mgt.core.subtype.mgt.exception.SubTypeMgtDAOException; import io.entgra.device.mgt.core.subtype.mgt.exception.SubTypeMgtPluginException; -import io.entgra.device.mgt.core.subtype.mgt.util.DeviceSubTypeMgtUtil; -import io.entgra.device.mgt.core.subtype.mgt.dto.DeviceSubType; -import io.entgra.device.mgt.core.subtype.mgt.dao.DeviceSubTypeDAO; -import io.entgra.device.mgt.core.subtype.mgt.dao.DeviceSubTypeDAOFactory; -import io.entgra.device.mgt.core.subtype.mgt.dao.util.ConnectionManagerUtil; import io.entgra.device.mgt.core.subtype.mgt.spi.DeviceSubTypeService; +import io.entgra.device.mgt.core.subtype.mgt.util.DeviceSubTypeMgtUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; @@ -48,7 +48,7 @@ public class DeviceSubTypeServiceImpl implements DeviceSubTypeService { private static final LoadingCache deviceSubTypeCache = CacheBuilder.newBuilder() .expireAfterWrite(15, TimeUnit.MINUTES) - .build(new GetDeviceSubTypeCacheLoader()); + .build(new DeviceSubTypeCacheLoader()); private final DeviceSubTypeDAO deviceSubTypeDAO; public DeviceSubTypeServiceImpl() { @@ -166,7 +166,13 @@ public class DeviceSubTypeServiceImpl implements DeviceSubTypeService { throws SubTypeMgtPluginException { try { ConnectionManagerUtil.openDBConnection(); - return deviceSubTypeDAO.getAllDeviceSubTypes(tenantId, deviceType); + List subtypes = deviceSubTypeDAO.getAllDeviceSubTypes(tenantId, deviceType); + DeviceSubTypeCacheKey key; + for (DeviceSubType dst: subtypes) { + key = DeviceSubTypeMgtUtil.getDeviceSubTypeCacheKey(tenantId, dst.getSubTypeId(), deviceType); + deviceSubTypeCache.put(key, dst); + } + return subtypes; } catch (DBConnectionException e) { String msg = "Error occurred while obtaining the database connection to retrieve all device subtype for " + deviceType + " subtypes"; diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/internal/DeviceSubTypeMgtDataHolder.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/internal/DeviceSubTypeMgtDataHolder.java index e3cd330d19..8efcdac5f7 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/internal/DeviceSubTypeMgtDataHolder.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/internal/DeviceSubTypeMgtDataHolder.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.subtype.mgt.internal; -import io.entgra.device.mgt.core.subtype.mgt.spi.DeviceSubTypeService; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import io.entgra.device.mgt.core.subtype.mgt.spi.DeviceSubTypeService; import org.wso2.carbon.registry.core.service.RegistryService; public class DeviceSubTypeMgtDataHolder { diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/internal/DeviceSubTypeMgtServiceComponent.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/internal/DeviceSubTypeMgtServiceComponent.java index ab322c4db7..c0fc960352 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/internal/DeviceSubTypeMgtServiceComponent.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/internal/DeviceSubTypeMgtServiceComponent.java @@ -18,45 +18,29 @@ package io.entgra.device.mgt.core.subtype.mgt.internal; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; +import io.entgra.device.mgt.core.device.mgt.core.config.datasource.DataSourceConfig; +import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import io.entgra.device.mgt.core.subtype.mgt.dao.DeviceSubTypeDAOFactory; import io.entgra.device.mgt.core.subtype.mgt.impl.DeviceSubTypeServiceImpl; import io.entgra.device.mgt.core.subtype.mgt.spi.DeviceSubTypeService; -import io.entgra.device.mgt.core.subtype.mgt.dao.DeviceSubTypeDAOFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; -import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; -import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; -import io.entgra.device.mgt.core.device.mgt.core.config.datasource.DataSourceConfig; -import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.registry.core.service.RegistryService; -/** - * @scr.component name="io.entgra.device.mgt.core.subtype.mgt.internal.DeviceSubTypeMgtServiceComponent" immediate="true" - * @scr.reference name="org.wso2.carbon.device.manager" - * interface="io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDeviceManagementService" - * unbind="unsetDeviceManagementService" - * @scr.reference name="org.wso2.carbon.ndatasource" - * interface="org.wso2.carbon.ndatasource.core.DataSourceService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDataSourceService" - * unbind="unsetDataSourceService" - * @scr.reference name="registry.service" - * interface="org.wso2.carbon.registry.core.service.RegistryService" - * cardinality="0..1" - * policy="dynamic" - * bind="setRegistryService" - * unbind="unsetRegistryService" - */ +@Component( + name = "io.entgra.device.mgt.core.subtype.mgt.internal.DeviceSubTypeMgtServiceComponent", + immediate = true) public class DeviceSubTypeMgtServiceComponent { private static final Log log = LogFactory.getLog(DeviceSubTypeMgtServiceComponent.class); + @Activate protected void activate(ComponentContext componentContext) { if (log.isDebugEnabled()) { @@ -80,7 +64,7 @@ public class DeviceSubTypeMgtServiceComponent { log.error("Error occurred while activating Device SubType Management Service Component", e); } } - + @Deactivate protected void deactivate(ComponentContext componentContext) { if (log.isDebugEnabled()) { log.debug("De-activating Device SubType Management Service Component"); @@ -88,6 +72,12 @@ public class DeviceSubTypeMgtServiceComponent { } @SuppressWarnings("unused") + @Reference( + name = "data.mgt.provider.service", + service = io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDeviceManagementService") protected void setDeviceManagementService(DeviceManagementProviderService deviceManagementProviderService) { if (log.isDebugEnabled()) { log.debug("Setting Device Management Service to Device SubType Mgt SC"); @@ -103,6 +93,12 @@ public class DeviceSubTypeMgtServiceComponent { DeviceSubTypeMgtDataHolder.getInstance().setDeviceManagementProviderService(null); } + @Reference( + name = "datasource.service", + service = org.wso2.carbon.ndatasource.core.DataSourceService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDataSourceService") protected void setDataSourceService(DataSourceService dataSourceService) { /* This is to avoid mobile device management component getting initialized before the underlying datasources are registered */ @@ -118,7 +114,12 @@ public class DeviceSubTypeMgtServiceComponent { } } - + @Reference( + name = "registry.service", + service = org.wso2.carbon.registry.core.service.RegistryService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRegistryService") protected void setRegistryService(RegistryService registryService) { if (log.isDebugEnabled()) { log.debug("RegistryService set to Device SubType Mgt component"); diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/spi/DeviceSubTypeService.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/spi/DeviceSubTypeService.java index c77987f255..45d8b2715c 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/spi/DeviceSubTypeService.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/spi/DeviceSubTypeService.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.subtype.mgt.spi; -import io.entgra.device.mgt.core.subtype.mgt.exception.SubTypeMgtPluginException; import io.entgra.device.mgt.core.subtype.mgt.dto.DeviceSubType; +import io.entgra.device.mgt.core.subtype.mgt.exception.SubTypeMgtPluginException; import java.util.List; diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/BaseDeviceSubTypePluginTest.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/BaseDeviceSubTypePluginTest.java index 9c47c7ac22..ac11855263 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/BaseDeviceSubTypePluginTest.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/BaseDeviceSubTypePluginTest.java @@ -18,9 +18,12 @@ package io.entgra.device.mgt.core.subtype.mgt.mock; +import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; +import io.entgra.device.mgt.core.subtype.mgt.DataSourceConfig; import io.entgra.device.mgt.core.subtype.mgt.TestUtils; import io.entgra.device.mgt.core.subtype.mgt.dao.DeviceSubTypeDAOFactory; -import io.entgra.device.mgt.core.subtype.mgt.DataSourceConfig; import io.entgra.device.mgt.core.subtype.mgt.dao.util.ConnectionManagerUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -32,9 +35,6 @@ import org.testng.annotations.Parameters; import org.w3c.dom.Document; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; import javax.sql.DataSource; import javax.xml.bind.JAXBContext; diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/MockConnection.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/MockConnection.java index 8a758b4204..3c677e5f9d 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/MockConnection.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/MockConnection.java @@ -18,21 +18,7 @@ package io.entgra.device.mgt.core.subtype.mgt.mock; -import java.sql.CallableStatement; -import java.sql.SQLWarning; -import java.sql.Savepoint; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.Statement; -import java.sql.Clob; -import java.sql.Blob; -import java.sql.NClob; -import java.sql.SQLXML; -import java.sql.Struct; -import java.sql.Array; -import java.sql.SQLClientInfoException; -import java.sql.DatabaseMetaData; -import java.sql.SQLException; +import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Map; diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/MockDatabaseMetaData.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/MockDatabaseMetaData.java index 0eac68516e..4c31273fcb 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/MockDatabaseMetaData.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/MockDatabaseMetaData.java @@ -20,11 +20,7 @@ package io.entgra.device.mgt.core.subtype.mgt.mock; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.RowIdLifetime; -import java.sql.DatabaseMetaData; -import java.sql.SQLException; +import java.sql.*; public class MockDatabaseMetaData implements DatabaseMetaData { private final String url; diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/MockResultSet.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/MockResultSet.java index bb5d512925..4136297ce0 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/MockResultSet.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/MockResultSet.java @@ -22,21 +22,7 @@ import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; -import java.sql.ResultSet; -import java.sql.SQLWarning; -import java.sql.Date; -import java.sql.Time; -import java.sql.Timestamp; -import java.sql.Clob; -import java.sql.Blob; -import java.sql.NClob; -import java.sql.SQLXML; -import java.sql.Ref; -import java.sql.Array; -import java.sql.ResultSetMetaData; -import java.sql.RowId; -import java.sql.Statement; -import java.sql.SQLException; +import java.sql.*; import java.util.ArrayList; import java.util.Calendar; import java.util.List; diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/MockStatement.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/MockStatement.java index 40671beab9..2d9330360f 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/MockStatement.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/java/io/entgra/device/mgt/core/subtype/mgt/mock/MockStatement.java @@ -22,23 +22,7 @@ import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLWarning; -import java.sql.Date; -import java.sql.Time; -import java.sql.Timestamp; -import java.sql.PreparedStatement; -import java.sql.ParameterMetaData; -import java.sql.Clob; -import java.sql.Blob; -import java.sql.NClob; -import java.sql.SQLXML; -import java.sql.Ref; -import java.sql.Array; -import java.sql.ResultSetMetaData; -import java.sql.RowId; -import java.sql.SQLException; +import java.sql.*; import java.util.ArrayList; import java.util.Calendar; import java.util.List; diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql index 8ed0e91922..2d30cda428 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql @@ -23,7 +23,7 @@ CREATE TABLE IF NOT EXISTS DM_GROUP ( STATUS VARCHAR(50) DEFAULT NULL, DESCRIPTION TEXT DEFAULT NULL, OWNER VARCHAR(255) DEFAULT NULL, - PARENT_PATH VARCHAR(255) DEFAULT '/', + PARENT_PATH VARCHAR(255) DEFAULT NULL, TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (ID) ); @@ -42,7 +42,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE ( ID INTEGER auto_increment NOT NULL, DESCRIPTION TEXT DEFAULT NULL, NAME VARCHAR(100) DEFAULT NULL, - DEVICE_TYPE_ID INT(11) DEFAULT NULL, + DEVICE_TYPE_ID INT DEFAULT NULL, DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, TENANT_ID INTEGER DEFAULT 0, @@ -84,8 +84,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP ( CREATE TABLE IF NOT EXISTS DM_OPERATION ( ID INTEGER AUTO_INCREMENT NOT NULL, TYPE VARCHAR(50) NOT NULL, - CREATED_TIMESTAMP TIMESTAMP NOT NULL, - RECEIVED_TIMESTAMP TIMESTAMP NULL, + CREATED_TIMESTAMP BIGINT NOT NULL, + RECEIVED_TIMESTAMP BIGINT NULL, OPERATION_CODE VARCHAR(1000) NOT NULL, INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BLOB DEFAULT NULL, @@ -111,7 +111,19 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT uk_dm_device_enrolment UNIQUE (DEVICE_ID, OWNER, OWNERSHIP, TENANT_ID) ); - +CREATE TABLE IF NOT EXISTS DM_DEVICE_STATUS ( + ID INTEGER AUTO_INCREMENT NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, + DEVICE_ID INTEGER NOT NULL, + STATUS VARCHAR(50) DEFAULT NULL, + UPDATE_TIME TIMESTAMP DEFAULT NULL, + CHANGED_BY VARCHAR(255) NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_dm_device_status_device FOREIGN KEY (DEVICE_ID) REFERENCES + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_device_status_enrolment FOREIGN KEY (ENROLMENT_ID) REFERENCES + DM_ENROLMENT (ID) ON DELETE CASCADE ON UPDATE CASCADE +); CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING ( ID INTEGER AUTO_INCREMENT NOT NULL, ENROLMENT_ID INTEGER NOT NULL, @@ -179,17 +191,17 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE ( ); CREATE TABLE IF NOT EXISTS DM_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , + ID INT NOT NULL AUTO_INCREMENT , NAME VARCHAR(45) DEFAULT NULL , DESCRIPTION VARCHAR(1000) NULL, PAYLOAD_VERSION VARCHAR (45) NULL, - TENANT_ID INT(11) NOT NULL , - PROFILE_ID INT(11) NOT NULL , + TENANT_ID INT NOT NULL , + PROFILE_ID INT NOT NULL , OWNERSHIP_TYPE VARCHAR(45) NULL, COMPLIANCE VARCHAR(100) NULL, PRIORITY INT NOT NULL, - ACTIVE INT(2) NOT NULL, - UPDATED INT(1) NULL, + ACTIVE INT NOT NULL, + UPDATED INT NULL, POLICY_TYPE VARCHAR(45) NULL, PRIMARY KEY (ID) , CONSTRAINT FK_DM_PROFILE_DM_POLICY @@ -200,11 +212,11 @@ CREATE TABLE IF NOT EXISTS DM_POLICY ( ); CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , - DEVICE_ID INT(11) NOT NULL , - ENROLMENT_ID INT(11) NOT NULL, + ID INT NOT NULL AUTO_INCREMENT , + DEVICE_ID INT NOT NULL , + ENROLMENT_ID INT NOT NULL, DEVICE BLOB NOT NULL, - POLICY_ID INT(11) NOT NULL , + POLICY_ID INT NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_POLICY_DEVICE_POLICY FOREIGN KEY (POLICY_ID ) @@ -219,9 +231,9 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( ); CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( - ID INT(11) NOT NULL , + ID INT NOT NULL , DEVICE_TYPE VARCHAR(300) NOT NULL , - POLICY_ID INT(11) NOT NULL , + POLICY_ID INT NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_DEVICE_TYPE_POLICY FOREIGN KEY (POLICY_ID ) @@ -231,11 +243,11 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( ); CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( - ID INT(11) NOT NULL AUTO_INCREMENT, - PROFILE_ID INT(11) NOT NULL, + ID INT NOT NULL AUTO_INCREMENT, + PROFILE_ID INT NOT NULL, FEATURE_CODE VARCHAR(100) NOT NULL, DEVICE_TYPE VARCHAR(300) NOT NULL, - TENANT_ID INT(11) NOT NULL , + TENANT_ID INT NOT NULL , CONTENT BLOB NULL DEFAULT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES @@ -246,11 +258,11 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( ); CREATE TABLE IF NOT EXISTS DM_POLICY_CORRECTIVE_ACTION ( - ID INT(11) NOT NULL AUTO_INCREMENT, + ID INT NOT NULL AUTO_INCREMENT, ACTION_TYPE VARCHAR(45) NOT NULL, - CORRECTIVE_POLICY_ID INT(11) DEFAULT NULL, - POLICY_ID INT(11) NOT NULL, - FEATURE_ID INT(11) DEFAULT NULL, + CORRECTIVE_POLICY_ID INT DEFAULT NULL, + POLICY_ID INT NOT NULL, + FEATURE_ID INT DEFAULT NULL, IS_REACTIVE BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (ID), CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION @@ -261,9 +273,9 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CORRECTIVE_ACTION ( ); CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , + ID INT NOT NULL AUTO_INCREMENT , ROLE_NAME VARCHAR(45) NOT NULL , - POLICY_ID INT(11) NOT NULL , + POLICY_ID INT NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_ROLE_POLICY_POLICY FOREIGN KEY (POLICY_ID ) @@ -287,11 +299,11 @@ CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( ID INT NOT NULL AUTO_INCREMENT , DEVICE_ID INT NOT NULL , - ENROLMENT_ID INT(11) NOT NULL, + ENROLMENT_ID INT NOT NULL, POLICY_ID INT NOT NULL , POLICY_CONTENT TEXT NULL , TENANT_ID INT NOT NULL, - APPLIED TINYINT(1) NULL , + APPLIED TINYINT NULL , CREATED_TIME TIMESTAMP NULL , UPDATED_TIME TIMESTAMP NULL , APPLIED_TIME TIMESTAMP NULL , @@ -344,7 +356,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES ( CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( ID INT NOT NULL AUTO_INCREMENT, DEVICE_ID INT NOT NULL, - ENROLMENT_ID INT(11) NOT NULL, + ENROLMENT_ID INT NOT NULL, POLICY_ID INT NOT NULL, TENANT_ID INT NOT NULL, STATUS INT NULL, @@ -359,7 +371,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( ID INT NOT NULL AUTO_INCREMENT, POLICY_ID INT NOT NULL, DEVICE_TYPE VARCHAR(300) NOT NULL , - TENANT_ID INT(11) NOT NULL, + TENANT_ID INT NOT NULL, PRIMARY KEY (ID) ); @@ -388,7 +400,7 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION ( LOCATION_URL VARCHAR(100) DEFAULT NULL, IMAGE_URL VARCHAR(100) DEFAULT NULL, APP_PROPERTIES BLOB NULL, - MEMORY_USAGE INTEGER(10) NULL, + MEMORY_USAGE INTEGER NULL, IS_ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, DEVICE_ID INTEGER NOT NULL, ENROLMENT_ID INTEGER NOT NULL, @@ -408,6 +420,16 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION ( -- POLICY RELATED TABLES FINISHED -- +CREATE TABLE IF NOT EXISTS DM_APP_ICONS ( + ID INTEGER AUTO_INCREMENT NOT NULL, + ICON_PATH VARCHAR(150) DEFAULT NULL, + PACKAGE_NAME VARCHAR(150) NOT NULL, + VERSION VARCHAR(50) DEFAULT '1.1.0', + CREATED_TIMESTAMP TIMESTAMP NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY (ID) +); + -- NOTIFICATION TABLE -- CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( NOTIFICATION_ID INTEGER AUTO_INCREMENT NOT NULL, @@ -428,7 +450,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( DEVICE_ID INT NULL, ENROLMENT_ID INT NOT NULL, KEY_FIELD VARCHAR(45) NULL, - VALUE_FIELD VARCHAR(1000) NULL, + VALUE_FIELD VARCHAR(1500) NULL, PRIMARY KEY (ID), CONSTRAINT DM_DEVICE_INFO_DEVICE FOREIGN KEY (DEVICE_ID) @@ -457,7 +479,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( STATE VARCHAR(45) NULL, COUNTRY VARCHAR(45) NULL, GEO_HASH VARCHAR(45) NULL, - UPDATE_TIMESTAMP BIGINT(15) NOT NULL, + UPDATE_TIMESTAMP BIGINT NOT NULL, ALTITUDE DOUBLE NULL, SPEED FLOAT NULL, BEARING FLOAT NULL, @@ -494,8 +516,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( CPU_USAGE DECIMAL(5) NULL, TOTAL_RAM_MEMORY DECIMAL(30,3) NULL, AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL, - PLUGGED_IN INT(1) NULL, - UPDATE_TIMESTAMP BIGINT(15) NOT NULL, + PLUGGED_IN INT NULL, + UPDATE_TIMESTAMP BIGINT NOT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE FOREIGN KEY (DEVICE_ID) @@ -522,7 +544,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_HISTORY_LAST_SEVEN_DAYS LONGITUDE DOUBLE NULL, SPEED FLOAT NULL, HEADING FLOAT NULL, - TIMESTAMP BIGINT(15) NOT NULL, + TIMESTAMP BIGINT NOT NULL, GEO_HASH VARCHAR(45) NULL, DEVICE_OWNER VARCHAR(45) NULL, DEVICE_ALTITUDE DOUBLE NULL, @@ -747,24 +769,6 @@ CREATE TABLE IF NOT EXISTS DM_EXT_DEVICE_MAPPING ( STATUS INT DEFAULT 0, PRIMARY KEY (ID) ); -/* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you 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. - */ - -- END OF DM_EXT_DEVICE_MAPPING TABLE-- -- END OF DM_EXT_PERMISSION_MAPPING TABLE-- @@ -776,23 +780,23 @@ CREATE TABLE IF NOT EXISTS DM_EXT_PERMISSION_MAPPING ( -- DYNAMIC TASK TABLES-- CREATE TABLE IF NOT EXISTS DYNAMIC_TASK ( - DYNAMIC_TASK_ID INTEGER AUTO_INCREMENT NOT NULL, - NAME VARCHAR(300) DEFAULT NULL , - CRON VARCHAR(8000) DEFAULT NULL, - IS_ENABLED BOOLEAN NOT NULL DEFAULT FALSE, - TASK_CLASS_NAME VARCHAR(8000) DEFAULT NULL, - TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (DYNAMIC_TASK_ID) + DYNAMIC_TASK_ID INTEGER AUTO_INCREMENT NOT NULL, + NAME VARCHAR(300) DEFAULT NULL , + CRON VARCHAR(8000) DEFAULT NULL, + IS_ENABLED BOOLEAN NOT NULL DEFAULT FALSE, + TASK_CLASS_NAME VARCHAR(8000) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (DYNAMIC_TASK_ID) ); CREATE TABLE IF NOT EXISTS DYNAMIC_TASK_PROPERTIES ( - DYNAMIC_TASK_ID INTEGER NOT NULL, - PROPERTY_NAME VARCHAR(100) DEFAULT 0, - PROPERTY_VALUE VARCHAR(100) DEFAULT NULL, - TENANT_ID VARCHAR(100), - PRIMARY KEY (DYNAMIC_TASK_ID, PROPERTY_NAME, TENANT_ID), - CONSTRAINT FK_DYNAMIC_TASK_TASK_PROPERTIES FOREIGN KEY (DYNAMIC_TASK_ID) REFERENCES - DYNAMIC_TASK (DYNAMIC_TASK_ID) ON DELETE CASCADE ON UPDATE CASCADE + DYNAMIC_TASK_ID INTEGER NOT NULL, + PROPERTY_NAME VARCHAR(100) DEFAULT 0, + PROPERTY_VALUE VARCHAR(100) DEFAULT NULL, + TENANT_ID VARCHAR(100), + PRIMARY KEY (DYNAMIC_TASK_ID, PROPERTY_NAME, TENANT_ID), + CONSTRAINT FK_DYNAMIC_TASK_TASK_PROPERTIES FOREIGN KEY (DYNAMIC_TASK_ID) REFERENCES + DYNAMIC_TASK (DYNAMIC_TASK_ID) ON DELETE CASCADE ON UPDATE CASCADE ); -- END OF DYNAMIC TASK TABLE-- @@ -805,5 +809,34 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_SUB_TYPE ( TYPE_DEFINITION TEXT NOT NULL, PRIMARY KEY (SUB_TYPE_ID,DEVICE_TYPE) ); +-- END OF DM_DEVICE_SUB_TYPE TABLE-- + +-- DM_TRACCAR_UNSYNCED_DEVICES TABLE -- +CREATE TABLE IF NOT EXISTS DM_TRACCAR_UNSYNCED_DEVICES ( + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_NAME VARCHAR(100) NOT NULL, + IOTS_DEVICE_IDENTIFIER VARCHAR(300) DEFAULT NULL UNIQUE, + TRACCAR_DEVICE_UNIQUE_ID INT NOT NULL, + TRACCAR_USENAME VARCHAR(100) NULL, + STATUS VARCHAR(100) NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID) +); +-- END OF DM_TRACCAR_UNSYNCED_DEVICES TABLE -- + +-- SUB_OPERATION_TEMPLATE TABLE-- +CREATE TABLE IF NOT EXISTS SUB_OPERATION_TEMPLATE ( + SUB_OPERATION_TEMPLATE_ID INT NOT NULL AUTO_INCREMENT, + OPERATION_DEFINITION TEXT NOT NULL, + OPERATION_CODE VARCHAR(100) NOT NULL, + SUB_TYPE_ID INT NOT NULL, + DEVICE_TYPE VARCHAR(25) NOT NULL, + CREATE_TIMESTAMP TIMESTAMP NULL DEFAULT NULL, + UPDATE_TIMESTAMP TIMESTAMP NULL DEFAULT NULL, + PRIMARY KEY (SUB_OPERATION_TEMPLATE_ID), + CONSTRAINT uk_sub_operation_template UNIQUE (SUB_TYPE_ID, OPERATION_CODE, DEVICE_TYPE), +-- UNIQUE KEY SUB_OPERATION_TEMPLATE (SUB_TYPE_ID, OPERATION_CODE, DEVICE_TYPE), + CONSTRAINT fk_SUB_OPERATION_TEMPLATE_DM_DEVICE_SUB_TYPE FOREIGN KEY (SUB_TYPE_ID, DEVICE_TYPE) REFERENCES DM_DEVICE_SUB_TYPE (SUB_TYPE_ID, DEVICE_TYPE) +); --- END OF DM_DEVICE_SUB_TYPE TABLE-- \ No newline at end of file +-- END OF SUB_OPERATION_TEMPLATE TABLE-- diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/dbscripts/h2.sql b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/dbscripts/h2.sql index f3f22f381c..4069c6580a 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/dbscripts/h2.sql +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/dbscripts/h2.sql @@ -27,17 +27,18 @@ PRIMARY KEY (`SUB_TYPE_ID`,`DEVICE_TYPE`) ); -- SUB_OPERATION_TEMPLATE TABLE-- -CREATE TABLE SUB_OPERATION_TEMPLATE ( - SUB_OPERATION_TEMPLATE_ID int NOT NULL AUTO_INCREMENT, +CREATE TABLE IF NOT EXISTS SUB_OPERATION_TEMPLATE ( + SUB_OPERATION_TEMPLATE_ID INT NOT NULL AUTO_INCREMENT, OPERATION_DEFINITION TEXT NOT NULL, - OPERATION_CODE varchar(100) NOT NULL, - SUB_TYPE_ID int NOT NULL, - DEVICE_TYPE VARCHAR(25) NOT NULL, - CREATE_TIMESTAMP timestamp NULL DEFAULT NULL, - UPDATE_TIMESTAMP timestamp NULL DEFAULT NULL, + OPERATION_CODE VARCHAR (100) NOT NULL, + SUB_TYPE_ID INT NOT NULL, + DEVICE_TYPE VARCHAR (25) NOT NULL, + CREATE_TIMESTAMP TIMESTAMP NULL DEFAULT NULL, + UPDATE_TIMESTAMP TIMESTAMP NULL DEFAULT NULL, PRIMARY KEY (SUB_OPERATION_TEMPLATE_ID), - UNIQUE KEY SUB_OPERATION_TEMPLATE (SUB_TYPE_ID,OPERATION_CODE, DEVICE_TYPE), - CONSTRAINT fk_SUB_OPERATION_TEMPLATE_DM_DEVICE_SUB_TYPE FOREIGN KEY (SUB_TYPE_ID, DEVICE_TYPE) REFERENCES DM_DEVICE_SUB_TYPE (SUB_TYPE_ID, DEVICE_TYPE) + UNIQUE (SUB_TYPE_ID,OPERATION_CODE, DEVICE_TYPE), + CONSTRAINT fk_SUB_OPERATION_TEMPLATE_DM_DEVICE_SUB_TYPE FOREIGN KEY (SUB_TYPE_ID, DEVICE_TYPE) + REFERENCES DM_DEVICE_SUB_TYPE (SUB_TYPE_ID, DEVICE_TYPE) ); -- ----------------------------------------------------- -- Sample data for test cases diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/repository/conf/datasources/data-source-config.xml b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/repository/conf/datasources/data-source-config.xml index ad8165fc67..2e591b07c9 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/repository/conf/datasources/data-source-config.xml +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/repository/conf/datasources/data-source-config.xml @@ -18,7 +18,7 @@ --> - jdbc:h2:mem:smart-meter-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true + jdbc:h2:mem:smart-meter-test-db;DB_CLOSE_ON_EXIT=FALSE org.h2.Driver wso2carbon wso2carbon diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/pom.xml b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/pom.xml index 0be1640628..3186715314 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/pom.xml +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/pom.xml @@ -33,6 +33,14 @@ + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + org.apache.felix maven-bundle-plugin @@ -46,6 +54,10 @@ io.entgra.device.mgt.core.task.mgt.common.* + + io.entgra.device.mgt.core.task.mgt.common.bean, + io.entgra.device.mgt.core.task.mgt.common.exception + diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/src/main/java/io/entgra/device/mgt/core/task/mgt/common/spi/TaskManagementService.java b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/src/main/java/io/entgra/device/mgt/core/task/mgt/common/spi/TaskManagementService.java index ab8a02199f..968f73d0ec 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/src/main/java/io/entgra/device/mgt/core/task/mgt/common/spi/TaskManagementService.java +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/src/main/java/io/entgra/device/mgt/core/task/mgt/common/spi/TaskManagementService.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.task.mgt.common.spi; import io.entgra.device.mgt.core.task.mgt.common.bean.DynamicTask; -import io.entgra.device.mgt.core.task.mgt.common.exception.TaskNotFoundException; import io.entgra.device.mgt.core.task.mgt.common.exception.TaskManagementException; +import io.entgra.device.mgt.core.task.mgt.common.exception.TaskNotFoundException; import java.util.List; import java.util.Map; diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/pom.xml b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/pom.xml index 3a31447016..f5629cc955 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/pom.xml +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/pom.xml @@ -35,8 +35,12 @@ - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -50,26 +54,36 @@ Task Management Core Bundle io.entgra.device.mgt.core.task.mgt.core.internal + com.google.gson;version="[2.9,3)", + io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception;version="[5.0,6)", + io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service;version="[5.0,6)", + io.entgra.device.mgt.core.task.mgt.common.bean;version="[5.0,6)", + io.entgra.device.mgt.core.task.mgt.common.exception;version="[5.0,6)", + io.entgra.device.mgt.core.task.mgt.common.spi;version="[5.0,6)", + io.entgra.device.mgt.core.task.mgt.core.config, + io.entgra.device.mgt.core.task.mgt.core.config.datasource, + io.entgra.device.mgt.core.task.mgt.core.dao, + io.entgra.device.mgt.core.task.mgt.core.dao.common, + io.entgra.device.mgt.core.task.mgt.core.dao.impl, + io.entgra.device.mgt.core.task.mgt.core.dao.util, + javax.naming, + javax.sql, + javax.xml.bind;version="[0.0,1)", + javax.xml.bind.annotation;version="[0.0,1)", + javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}", + org.apache.commons.codec.digest;version="[1.4,2)", + org.apache.commons.lang;version="[2.4,3)", + org.apache.commons.logging;version="[1.2,2)", org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.apache.commons.logging, - org.wso2.carbon.ndatasource.core, org.w3c.dom, - javax.xml.bind.annotation, - javax.xml.bind, - javax.sql, - javax.naming, - io.entgra.device.mgt.core.task.mgt.common.*, - org.wso2.carbon.utils.*, - org.wso2.carbon.ntask.core.*, - org.wso2.carbon.ntask.common, - io.entgra.device.mgt.core.device.mgt.common.*, - org.wso2.carbon.context, - org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}", - org.apache.commons.codec.digest;version="${commons-codec.wso2.osgi.version.range}", - io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.dto, - io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception, - io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service, + org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.ndatasource.core;version="[4.8,5)", + org.wso2.carbon.ntask.common;version="[4.9,5)", + org.wso2.carbon.ntask.core;version="[4.9,5)", + org.wso2.carbon.ntask.core.service;version="[4.9,5)", + org.wso2.carbon.utils;version="[4.8,5)" !io.entgra.device.mgt.core.task.mgt.core.internal, @@ -83,13 +97,8 @@ - org.eclipse.osgi - org.eclipse.osgi - provided - - - org.eclipse.osgi - org.eclipse.osgi.services + org.apache.felix + org.apache.felix.scr.ds-annotations provided @@ -103,8 +112,8 @@ provided - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api provided @@ -134,6 +143,11 @@ org.wso2.carbon.ntask.core provided + + org.wso2.orbit.javax.xml.bind + jaxb-api + provided + \ No newline at end of file diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/config/TaskConfigurationManager.java b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/config/TaskConfigurationManager.java index a6e7c78895..69fa1605d0 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/config/TaskConfigurationManager.java +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/config/TaskConfigurationManager.java @@ -17,9 +17,9 @@ */ package io.entgra.device.mgt.core.task.mgt.core.config; -import io.entgra.device.mgt.core.task.mgt.core.util.TaskManagementUtil; import io.entgra.device.mgt.core.task.mgt.common.constant.TaskMgtConstants; import io.entgra.device.mgt.core.task.mgt.common.exception.TaskManagementException; +import io.entgra.device.mgt.core.task.mgt.core.util.TaskManagementUtil; import org.w3c.dom.Document; import org.wso2.carbon.utils.CarbonUtils; diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/common/TaskManagementDAOFactory.java b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/common/TaskManagementDAOFactory.java index e70e41689b..6eccde8d84 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/common/TaskManagementDAOFactory.java +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/common/TaskManagementDAOFactory.java @@ -17,7 +17,6 @@ */ package io.entgra.device.mgt.core.task.mgt.core.dao.common; -import io.entgra.device.mgt.core.task.mgt.core.dao.DynamicTaskPropDAO; import io.entgra.device.mgt.core.task.mgt.common.constant.TaskMgtConstants; import io.entgra.device.mgt.core.task.mgt.common.exception.IllegalTransactionStateException; import io.entgra.device.mgt.core.task.mgt.common.exception.TransactionManagementException; @@ -25,6 +24,7 @@ import io.entgra.device.mgt.core.task.mgt.common.exception.UnsupportedDatabaseEn import io.entgra.device.mgt.core.task.mgt.core.config.datasource.DataSourceConfig; import io.entgra.device.mgt.core.task.mgt.core.config.datasource.JNDILookupDefinition; import io.entgra.device.mgt.core.task.mgt.core.dao.DynamicTaskDAO; +import io.entgra.device.mgt.core.task.mgt.core.dao.DynamicTaskPropDAO; import io.entgra.device.mgt.core.task.mgt.core.dao.impl.DynamicTaskDAOImpl; import io.entgra.device.mgt.core.task.mgt.core.dao.impl.DynamicTaskPropDAOImpl; import io.entgra.device.mgt.core.task.mgt.core.dao.util.TaskManagementDAOUtil; diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/impl/DynamicTaskPropDAOImpl.java b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/impl/DynamicTaskPropDAOImpl.java index 5979832130..8b084bf04e 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/impl/DynamicTaskPropDAOImpl.java +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/impl/DynamicTaskPropDAOImpl.java @@ -17,11 +17,11 @@ */ package io.entgra.device.mgt.core.task.mgt.core.dao.impl; +import io.entgra.device.mgt.core.task.mgt.common.constant.TaskMgtConstants; +import io.entgra.device.mgt.core.task.mgt.common.exception.TaskManagementDAOException; import io.entgra.device.mgt.core.task.mgt.core.dao.DynamicTaskPropDAO; import io.entgra.device.mgt.core.task.mgt.core.dao.common.TaskManagementDAOFactory; import io.entgra.device.mgt.core.task.mgt.core.dao.util.TaskManagementDAOUtil; -import io.entgra.device.mgt.core.task.mgt.common.constant.TaskMgtConstants; -import io.entgra.device.mgt.core.task.mgt.common.exception.TaskManagementDAOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/internal/TaskManagerServiceComponent.java b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/internal/TaskManagerServiceComponent.java index 2bc5e41393..db189da85b 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/internal/TaskManagerServiceComponent.java +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/internal/TaskManagerServiceComponent.java @@ -17,12 +17,12 @@ */ package io.entgra.device.mgt.core.task.mgt.core.internal; -import io.entgra.device.mgt.core.task.mgt.core.dao.common.TaskManagementDAOFactory; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; -import io.entgra.device.mgt.core.task.mgt.core.config.TaskManagementConfig; -import io.entgra.device.mgt.core.task.mgt.core.config.datasource.DataSourceConfig; import io.entgra.device.mgt.core.task.mgt.common.spi.TaskManagementService; import io.entgra.device.mgt.core.task.mgt.core.config.TaskConfigurationManager; +import io.entgra.device.mgt.core.task.mgt.core.config.TaskManagementConfig; +import io.entgra.device.mgt.core.task.mgt.core.config.datasource.DataSourceConfig; +import io.entgra.device.mgt.core.task.mgt.core.dao.common.TaskManagementDAOFactory; import io.entgra.device.mgt.core.task.mgt.core.service.TaskManagementServiceImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -30,32 +30,16 @@ import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.ntask.core.service.TaskService; +import org.osgi.service.component.annotations.*; -/** - * @scr.component name="io.entgra.task.mgt.service" immediate="true" - * @scr.reference name="datasource.service" - * interface="org.wso2.carbon.ndatasource.core.DataSourceService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDataSourceService" - * unbind="unsetDataSourceService" - * @scr.reference name="app.mgt.ntask.component" - * interface="org.wso2.carbon.ntask.core.service.TaskService" - * cardinality="1..1" - * policy="dynamic" - * bind="setTaskService" - * unbind="unsetTaskService" - * @scr.reference name="entgra.heart.beat.service" - * interface="io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService" - * cardinality="0..1" - * policy="dynamic" - * bind="setHeartBeatService" - * unbind="unsetHeartBeatService" - */ +@Component( + name = "io.entgra.device.mgt.core.task.mgt.core.internal.TaskManagerServiceComponent", + immediate = true) public class TaskManagerServiceComponent { private static final Log log = LogFactory.getLog(TaskManagerServiceComponent.class); + @Activate protected void activate(ComponentContext ctx) { if (log.isDebugEnabled()) { @@ -80,13 +64,19 @@ public class TaskManagerServiceComponent { log.error("Error occurred while activating Task Manager Service Component", e); } } - + @Deactivate protected void deactivate(ComponentContext ctx) { if (log.isDebugEnabled()) { log.debug("De-activating Task Manager Service Component"); } } + @Reference( + name = "datasource.service", + service = org.wso2.carbon.ndatasource.core.DataSourceService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDataSourceService") protected void setDataSourceService(DataSourceService dataSourceService) { /* This is to avoid Task Manager Service Component getting initialized before the underlying datasources are registered */ @@ -99,6 +89,12 @@ public class TaskManagerServiceComponent { //do nothing } + @Reference( + name = "task.service", + service = org.wso2.carbon.ntask.core.service.TaskService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetTaskService") @SuppressWarnings("unused") public void setTaskService(TaskService taskService) { if (log.isDebugEnabled()) { @@ -115,6 +111,12 @@ public class TaskManagerServiceComponent { TaskManagerDataHolder.getInstance().setnTaskService(null); } + @Reference( + name = "heartbeat.service", + service = io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetHeartBeatService") @SuppressWarnings("unused") protected void setHeartBeatService(HeartBeatManagementService heartBeatService) { if (log.isDebugEnabled()) { diff --git a/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/pom.xml b/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/pom.xml index 790af68e92..cc3b6f2684 100755 --- a/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/pom.xml +++ b/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/pom.xml @@ -35,8 +35,12 @@ - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -50,18 +54,27 @@ Task Watcher Bundle io.entgra.device.mgt.core.task.mgt.watcher.internal - io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.*, - io.entgra.device.mgt.core.task.mgt.common.*, - io.entgra.device.mgt.core.task.mgt.core.*, - org.apache.commons.logging, + io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception;version="[5.0,6)", + io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service;version="[5.0,6)", + io.entgra.device.mgt.core.task.mgt.common.bean;version="[5.0,6)", + io.entgra.device.mgt.core.task.mgt.common.exception;version="[5.0,6)", + io.entgra.device.mgt.core.task.mgt.common.spi;version="[5.0,6)", + io.entgra.device.mgt.core.task.mgt.core.config;version="[5.0,6)", + io.entgra.device.mgt.core.task.mgt.core.util;version="[5.0,6)", + io.entgra.device.mgt.core.task.mgt.watcher, + io.entgra.device.mgt.core.task.mgt.watcher.internal, + org.apache.commons.logging;version="[1.2,2)", org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.wso2.carbon.context, - org.wso2.carbon.core, - io.entgra.device.mgt.core.device.mgt.common.*, - org.wso2.carbon.ntask.*, - org.wso2.carbon.user.api, - org.wso2.carbon.user.core.*, + org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.core;version="[4.8,5)", + org.wso2.carbon.ntask.common;version="[4.9,5)", + org.wso2.carbon.ntask.core;version="[4.9,5)", + org.wso2.carbon.ntask.core.service;version="[4.9,5)", + org.wso2.carbon.user.api;version="[1.0,2)", + org.wso2.carbon.user.core.service;version="[4.8,5)", + org.wso2.carbon.user.core.tenant;version="[4.8,5)" io.entgra.device.mgt.core.task.mgt.watcher.* @@ -74,18 +87,13 @@ - org.eclipse.osgi - org.eclipse.osgi + org.apache.felix + org.apache.felix.scr.ds-annotations provided - org.eclipse.osgi - org.eclipse.osgi.services - provided - - - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api provided diff --git a/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/src/main/java/io/entgra/device/mgt/core/task/mgt/watcher/internal/TaskWatcherServiceComponent.java b/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/src/main/java/io/entgra/device/mgt/core/task/mgt/watcher/internal/TaskWatcherServiceComponent.java index a84e3e5f42..138269395f 100755 --- a/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/src/main/java/io/entgra/device/mgt/core/task/mgt/watcher/internal/TaskWatcherServiceComponent.java +++ b/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/src/main/java/io/entgra/device/mgt/core/task/mgt/watcher/internal/TaskWatcherServiceComponent.java @@ -17,11 +17,11 @@ */ package io.entgra.device.mgt.core.task.mgt.watcher.internal; +import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; import io.entgra.device.mgt.core.task.mgt.common.spi.TaskManagementService; import io.entgra.device.mgt.core.task.mgt.core.config.TaskConfigurationManager; import io.entgra.device.mgt.core.task.mgt.core.config.TaskManagementConfig; import io.entgra.device.mgt.core.task.mgt.watcher.IoTSStartupHandler; -import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; @@ -29,39 +29,16 @@ import org.osgi.service.component.ComponentContext; import org.wso2.carbon.core.ServerStartupObserver; import org.wso2.carbon.ntask.core.service.TaskService; import org.wso2.carbon.user.core.service.RealmService; +import org.osgi.service.component.annotations.*; -/** - * @scr.component - * name="io.entgra.device.mgt.core.task.mgt.watcher" immediate="true" - * @scr.reference name="app.mgt.ntask.component" - * interface="org.wso2.carbon.ntask.core.service.TaskService" - * cardinality="1..1" - * policy="dynamic" - * bind="setTaskService" - * unbind="unsetTaskService" - * @scr.reference name="io.entgra.task.mgt.service" - * interface="io.entgra.device.mgt.core.task.mgt.common.spi.TaskManagementService" - * cardinality="1..1" - * policy="dynamic" - * bind="setTaskMgtService" - * unbind="unsetTaskMgtService" - * @scr.reference name="entgra.heart.beat.service" - * interface="io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService" - * cardinality="0..1" - * policy="dynamic" - * bind="setHeartBeatService" - * unbind="unsetHeartBeatService" - * @scr.reference name="user.realmservice.default" - * interface="org.wso2.carbon.user.core.service.RealmService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRealmService" - * unbind="unsetRealmService" - */ +@Component( + name = "io.entgra.device.mgt.core.task.mgt.watcher.internal.TaskWatcherServiceComponent", + immediate = true) public class TaskWatcherServiceComponent { private static final Log log = LogFactory.getLog(TaskWatcherServiceComponent.class); + @Activate protected void activate(ComponentContext ctx) { if (log.isDebugEnabled()) { log.debug("Activating Task Watcher Service Component"); @@ -83,7 +60,7 @@ public class TaskWatcherServiceComponent { log.error("Error occurred while activating Task Watcher Service Component", e); } } - + @Deactivate protected void deactivate(ComponentContext ctx) { if (log.isDebugEnabled()) { log.debug("De-activating Task Watcher Service Component"); @@ -91,6 +68,12 @@ public class TaskWatcherServiceComponent { } @SuppressWarnings("unused") + @Reference( + name = "task.service", + service = org.wso2.carbon.ntask.core.service.TaskService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetTaskService") public void setTaskService(TaskService taskService) { if (log.isDebugEnabled()) { log.debug("Setting the task service to Task Watcher Service Component "); @@ -107,6 +90,12 @@ public class TaskWatcherServiceComponent { } @SuppressWarnings("unused") + @Reference( + name = "task.mgt.service", + service = io.entgra.device.mgt.core.task.mgt.common.spi.TaskManagementService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetTaskMgtService") protected void setTaskMgtService(TaskManagementService taskManagementService) { if (log.isDebugEnabled()) { log.debug("Setting the task service to Task Watcher Service Component "); @@ -121,6 +110,12 @@ public class TaskWatcherServiceComponent { } TaskWatcherDataHolder.getInstance().setTaskManagementService(null); } + @Reference( + name = "heartbeat.service", + service = io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetHeartBeatService") @SuppressWarnings("unused") protected void setHeartBeatService(HeartBeatManagementService heartBeatService) { @@ -144,6 +139,12 @@ public class TaskWatcherServiceComponent { * @param realmService An instance of RealmService */ @SuppressWarnings("unused") + @Reference( + name = "realm.service", + service = org.wso2.carbon.user.core.service.RealmService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRealmService") protected void setRealmService(RealmService realmService) { if (log.isDebugEnabled()) { log.debug("Setting Realm Service"); diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/pom.xml b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/pom.xml index 9757c254af..20f7435708 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/pom.xml +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/pom.xml @@ -32,6 +32,14 @@ + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + org.apache.felix maven-bundle-plugin @@ -43,8 +51,8 @@ ${io.entgra.device.mgt.core.version} Tenant Management Common Bundle - org.apache.commons.logging, - org.wso2.carbon.stratos.common.beans + io.entgra.device.mgt.core.tenant.mgt.common.exception, + org.wso2.carbon.stratos.common.beans;version="[4.9,5)" io.entgra.device.mgt.core.tenant.mgt.common.* @@ -57,7 +65,6 @@ org.wso2.carbon.commons org.wso2.carbon.tenant.common - ${carbon.commons.version} diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml index ea496792f4..6347269f93 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml @@ -33,8 +33,12 @@ - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -48,28 +52,31 @@ Tenant Management Core Bundle io.entgra.device.mgt.core.tenant.mgt.core.internal - org.osgi.framework.*;version="${imp.package.version.osgi.framework}", - org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.apache.commons.logging, - io.entgra.device.mgt.core.application.mgt.common.*, - io.entgra.device.mgt.core.application.mgt.core.config, - io.entgra.device.mgt.core.device.mgt.core, - org.wso2.carbon.user.api, - org.wso2.carbon.registry.core.exceptions, - io.entgra.device.mgt.core.tenant.mgt.common.*, - org.wso2.carbon.stratos.common.beans, - org.wso2.carbon.stratos.common.exception, - org.wso2.carbon.stratos.common.listeners, + io.entgra.device.mgt.core.application.mgt.common.exception;version="[5.0,6)", + io.entgra.device.mgt.core.application.mgt.common.services;version="[5.0,6)", + io.entgra.device.mgt.core.application.mgt.core.config;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.exceptions;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.metadata.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.permission.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.roles.config;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.config;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.dao;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.metadata.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.permission.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.tenant.mgt.common.exception;version="[5.0,6)", + io.entgra.device.mgt.core.tenant.mgt.common.spi;version="[5.0,6)", + io.entgra.device.mgt.core.tenant.mgt.core, + org.apache.commons.logging;version="[1.2,2)", + org.osgi.framework;version="${imp.package.version.osgi.framework}", + org.osgi.service.component;version="${imp.package.version.osgi.service}", + org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.registry.core.exceptions;version="[1.0,2)", + org.wso2.carbon.stratos.common.beans;version="[4.9,5)", + org.wso2.carbon.stratos.common.exception;version="[4.9,5)", + org.wso2.carbon.stratos.common.listeners;version="[4.9,5)", org.wso2.carbon.tenant.mgt.services, - io.entgra.device.mgt.core.device.mgt.common.metadata.mgt, - io.entgra.device.mgt.core.device.mgt.common.exceptions, - io.entgra.device.mgt.core.device.mgt.common.permission.mgt, - io.entgra.device.mgt.core.device.mgt.common.roles.config, - io.entgra.device.mgt.core.device.mgt.core.metadata.mgt, - io.entgra.device.mgt.core.device.mgt.core.config, - io.entgra.device.mgt.core.device.mgt.core.dao.*, - org.wso2.carbon.user.core.service, - org.wso2.carbon.context + org.wso2.carbon.user.api;version="[1.0,2)", + org.wso2.carbon.user.core.service;version="[4.8,5)" !io.entgra.device.mgt.core.tenant.mgt.core.internal, @@ -83,17 +90,13 @@ - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services + org.apache.felix + org.apache.felix.scr.ds-annotations + provided org.wso2.carbon.commons org.wso2.carbon.tenant.common - ${carbon.commons.version} org.wso2.carbon @@ -110,27 +113,36 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.device.mgt.core + provided io.entgra.device.mgt.core io.entgra.device.mgt.core.device.mgt.common + provided io.entgra.device.mgt.core io.entgra.device.mgt.core.application.mgt.core + provided io.entgra.device.mgt.core io.entgra.device.mgt.core.application.mgt.common + provided - io.entgra.device.mgt.core - io.entgra.device.mgt.core.tenant.mgt.common + io.entgra.device.mgt.core + io.entgra.device.mgt.core.tenant.mgt.common + provided org.wso2.carbon org.wso2.carbon.utils + + org.wso2.carbon.multitenancy + org.wso2.carbon.tenant.mgt + provided + - \ No newline at end of file diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerImpl.java b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerImpl.java index 00cdc801be..de63497e87 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerImpl.java +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerImpl.java @@ -18,8 +18,14 @@ package io.entgra.device.mgt.core.tenant.mgt.core.impl; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; -import io.entgra.device.mgt.core.application.mgt.core.config.ConfigurationManager; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; +import io.entgra.device.mgt.core.application.mgt.core.config.ConfigurationManager; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; +import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException; +import io.entgra.device.mgt.core.device.mgt.common.roles.config.Role; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; +import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionUtils; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; @@ -30,19 +36,12 @@ import io.entgra.device.mgt.core.tenant.mgt.core.internal.TenantMgtDataHolder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; -import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; -import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionUtils; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.stratos.common.beans.TenantInfoBean; import org.wso2.carbon.user.api.Permission; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; -import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException; -import io.entgra.device.mgt.core.device.mgt.common.roles.config.Role; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; -import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerServiceImpl.java b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerServiceImpl.java index bc82bef3db..c439aa49fc 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerServiceImpl.java +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerServiceImpl.java @@ -17,8 +17,8 @@ */ package io.entgra.device.mgt.core.tenant.mgt.core.impl; -import io.entgra.device.mgt.core.tenant.mgt.common.spi.TenantManagerService; import io.entgra.device.mgt.core.tenant.mgt.common.exception.TenantMgtException; +import io.entgra.device.mgt.core.tenant.mgt.common.spi.TenantManagerService; import io.entgra.device.mgt.core.tenant.mgt.core.internal.TenantMgtDataHolder; import org.wso2.carbon.stratos.common.beans.TenantInfoBean; diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/internal/TenantMgtServiceComponent.java b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/internal/TenantMgtServiceComponent.java index c6ad710cb8..58d2385868 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/internal/TenantMgtServiceComponent.java +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/internal/TenantMgtServiceComponent.java @@ -18,8 +18,8 @@ package io.entgra.device.mgt.core.tenant.mgt.core.internal; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.WhiteLabelManagementService; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.DeviceStatusManagementService; -import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.DeviceStatusManagementServiceImpl; import io.entgra.device.mgt.core.tenant.mgt.common.spi.TenantManagerAdminService; import io.entgra.device.mgt.core.tenant.mgt.common.spi.TenantManagerService; import io.entgra.device.mgt.core.tenant.mgt.core.TenantManager; @@ -30,33 +30,20 @@ import io.entgra.device.mgt.core.tenant.mgt.core.listener.DeviceMgtTenantListene import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; -import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.WhiteLabelManagementService; -import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.WhiteLabelManagementServiceImpl; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.stratos.common.listeners.TenantMgtListener; import org.wso2.carbon.user.core.service.RealmService; -/** - * @scr.component name="io.entgra.device.mgt.core.tenant.manager" immediate="true" - * @scr.reference name="org.wso2.carbon.application.mgt.service" - * interface="io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager" - * cardinality="1..1" - * policy="dynamic" - * bind="setApplicationManager" - * unbind="unsetApplicationManager" - * @scr.reference name="user.realmservice.default" - * interface="org.wso2.carbon.user.core.service.RealmService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRealmService" - * unbind="unsetRealmService" - */ - +@Component( + name = "io.entgra.device.mgt.core.tenant.mgt.core.internal.TenantMgtServiceComponent", + immediate = true) @SuppressWarnings("unused") public class TenantMgtServiceComponent { private static final Log log = LogFactory.getLog(TenantManagerService.class); @SuppressWarnings("unused") + @Activate protected void activate(ComponentContext componentContext) { try { TenantManagerService tenantManagerService = new TenantManagerServiceImpl(); @@ -67,14 +54,6 @@ public class TenantMgtServiceComponent { registerService(TenantManagerAdminService.class.getName(), tenantManagerAdminService, null); TenantManager tenantManager = new TenantManagerImpl(); TenantMgtDataHolder.getInstance().setTenantManager(tenantManager); - WhiteLabelManagementService whiteLabelManagementService = new WhiteLabelManagementServiceImpl(); - componentContext.getBundleContext().registerService(WhiteLabelManagementService.class.getName(), - whiteLabelManagementService, null); - TenantMgtDataHolder.getInstance().setWhiteLabelManagementService(whiteLabelManagementService); - DeviceStatusManagementService deviceStatusManagementService = new DeviceStatusManagementServiceImpl(); - componentContext.getBundleContext().registerService(DeviceStatusManagementService.class.getName(), - deviceStatusManagementService, null); - TenantMgtDataHolder.getInstance().setDeviceStatusManagementService(deviceStatusManagementService); DeviceMgtTenantListener deviceMgtTenantListener = new DeviceMgtTenantListener(); if(log.isDebugEnabled()) { log.info("Tenant management listener is registering"); @@ -91,10 +70,57 @@ public class TenantMgtServiceComponent { } @SuppressWarnings("unused") + @Deactivate protected void deactivate(ComponentContext componentContext) { // nothing to do } + @Reference( + name = "whiteLabelManagement.service", + service = io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.WhiteLabelManagementService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetWhiteLabelManagementService" + ) + protected void setWhiteLabelManagementService(WhiteLabelManagementService whiteLabelManagementService) { + if(log.isDebugEnabled()) { + log.info("WhiteLabelManagementService is binding"); + } + TenantMgtDataHolder.getInstance().setWhiteLabelManagementService(whiteLabelManagementService); + } + protected void unsetWhiteLabelManagementService(WhiteLabelManagementService whiteLabelManagementService) { + if(log.isDebugEnabled()) { + log.info("WhiteLabelManagementService is unbinding"); + } + TenantMgtDataHolder.getInstance().setWhiteLabelManagementService(null); + } + + @Reference( + name = "deviceStatusManagement.service", + service = io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.DeviceStatusManagementService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetDeviceStatusManagementService" + ) + protected void setDeviceStatusManagementService(DeviceStatusManagementService deviceStatusManagementService) { + if(log.isDebugEnabled()) { + log.info("DeviceStatusManagementService is binding"); + } + TenantMgtDataHolder.getInstance().setDeviceStatusManagementService(deviceStatusManagementService); + } + protected void unsetDeviceStatusManagementService(DeviceStatusManagementService deviceStatusManagementService) { + if(log.isDebugEnabled()) { + log.info("DeviceStatusManagementService is unbinding"); + } + TenantMgtDataHolder.getInstance().setDeviceStatusManagementService(null); + } + + @Reference( + name = "application.mgr", + service = io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetApplicationManager") protected void setApplicationManager(ApplicationManager applicationManager) { if(log.isDebugEnabled()) { log.info("Application manager service is binding"); @@ -109,6 +135,12 @@ public class TenantMgtServiceComponent { TenantMgtDataHolder.getInstance().setApplicationManager(null); } + @Reference( + name = "realm.service", + service = org.wso2.carbon.user.core.service.RealmService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRealmService") protected void setRealmService(RealmService realmService) { if(log.isDebugEnabled()) { log.info("Realm Service service is binding"); diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/listener/DeviceMgtTenantListener.java b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/listener/DeviceMgtTenantListener.java index 978e69b0e4..f73477ff17 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/listener/DeviceMgtTenantListener.java +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/listener/DeviceMgtTenantListener.java @@ -17,8 +17,8 @@ */ package io.entgra.device.mgt.core.tenant.mgt.core.listener; -import io.entgra.device.mgt.core.tenant.mgt.core.TenantManager; import io.entgra.device.mgt.core.tenant.mgt.common.exception.TenantMgtException; +import io.entgra.device.mgt.core.tenant.mgt.core.TenantManager; import io.entgra.device.mgt.core.tenant.mgt.core.internal.TenantMgtDataHolder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/pom.xml b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/pom.xml index 197a91af5e..3e713b580c 100644 --- a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/pom.xml +++ b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/pom.xml @@ -31,13 +31,17 @@ bundle WSO2 Carbon - Email Sender Core WSO2 Carbon - Email Sender Core - http://wso2.org + https://entgra.io - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -51,27 +55,33 @@ Email Management Core Bundle io.entgra.device.mgt.core.transport.mgt.email.sender.core.internal - org.apache.axis2.*;version="${axis2.osgi.version.range}", - org.apache.axiom.*; version="${axiom.osgi.version.range}", + io.entgra.device.mgt.core.transport.mgt.email.sender.core, + javax.xml.bind;version="[0.0,1)", + javax.xml.bind.annotation;version="[0.0,1)", + javax.xml.parsers, + javax.xml.stream;version="[1.0,2)", + org.apache.axiom.om;version="[1.2,2)", + org.apache.axiom.om.impl.llom.util;version="[1.2,2)", + org.apache.axis2;version="[1.6,2)", + org.apache.axis2.addressing;version="[1.6,2)", + org.apache.axis2.client;version="[1.6,2)", + org.apache.axis2.context;version="[1.6,2)", + org.apache.axis2.description;version="[1.6,2)", + org.apache.axis2.engine;version="[1.6,2)", + org.apache.commons.io;version="[2.4,3)", + org.apache.commons.logging;version="[1.2,2)", + org.apache.velocity;version="[2.3,3)", + org.apache.velocity.app;version="[2.3,3)", + org.apache.velocity.context;version="[2.3,3)", + org.apache.velocity.exception;version="[2.3,3)", + org.apache.velocity.runtime.resource;version="[2.3,3)", + org.apache.velocity.runtime.resource.loader;version="[2.3,3)", + org.apache.velocity.util;version="[2.3,3)", org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.apache.commons.logging, - javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, - org.wso2.carbon.context, - org.wso2.carbon.utils.*, - org.wso2.carbon.registry.api, org.w3c.dom, - org.apache.velocity;version="${velocity.version}", - org.apache.velocity.app;version="${velocity.version}", - org.apache.velocity.context;version="${velocity.version}", - org.apache.velocity.exception;version="${velocity.version}", - org.apache.velocity.runtime.resource;version="${velocity.version}", - org.apache.velocity.runtime.resource.loader;version="${velocity.version}", - org.apache.commons.io, - org.apache.axis2.transport.mail, - org.wso2.carbon.registry.core.service, - org.wso2.carbon.registry.core.session, - org.apache.commons.collections + org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.utils;version="[4.8,5)" !io.entgra.device.mgt.core.transport.mgt.email.sender.core.internal, @@ -80,59 +90,19 @@ - - org.apache.maven.plugins - maven-surefire-plugin - - - file:src/test/resources/log4j.properties - - - src/test/resources/testng.xml - - - - - org.jacoco - jacoco-maven-plugin - - ${basedir}/target/coverage-reports/jacoco-unit.exec - - - - jacoco-initialize - - prepare-agent - - - - jacoco-site - test - - report - - - ${basedir}/target/coverage-reports/jacoco-unit.exec - ${basedir}/target/coverage-reports/site - - - - - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services + org.apache.felix + org.apache.felix.scr.ds-annotations + provided - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api + provided org.wso2.carbon @@ -142,10 +112,6 @@ org.testng testng - - org.wso2.carbon - org.wso2.carbon.registry.api - org.wso2.carbon org.wso2.carbon.base @@ -155,8 +121,8 @@ axis2 - org.wso2.orbit.org.apache.velocity - velocity + org.apache.velocity + velocity-engine-core commons-io.wso2 @@ -166,14 +132,15 @@ org.apache.axis2.transport axis2-transport-mail - - org.wso2.carbon - org.wso2.carbon.registry.core - commons-collections.wso2 commons-collections + + org.wso2.orbit.javax.xml.bind + jaxb-api + provided + diff --git a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/EmailContext.java b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/EmailContext.java index 5b54b36c07..cffe749ea5 100644 --- a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/EmailContext.java +++ b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/EmailContext.java @@ -17,7 +17,9 @@ */ package io.entgra.device.mgt.core.transport.mgt.email.sender.core; -import java.util.*; +import java.util.HashSet; +import java.util.Properties; +import java.util.Set; public class EmailContext { diff --git a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/RegistryBasedResourceLoader.java b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/RegistryBasedResourceLoader.java index 5c59bdfcb5..afdd807b52 100644 --- a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/RegistryBasedResourceLoader.java +++ b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/RegistryBasedResourceLoader.java @@ -17,44 +17,63 @@ */ package io.entgra.device.mgt.core.transport.mgt.email.sender.core; -import org.apache.commons.collections.ExtendedProperties; import org.apache.velocity.exception.ResourceNotFoundException; import org.apache.velocity.runtime.resource.Resource; import org.apache.velocity.runtime.resource.loader.ResourceLoader; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.RegistryType; -import org.wso2.carbon.registry.api.Registry; -import org.wso2.carbon.registry.api.RegistryException; +import org.apache.velocity.util.ExtProperties; import java.io.InputStream; +import java.io.Reader; public class RegistryBasedResourceLoader extends ResourceLoader { private static final String EMAIL_CONFIG_BASE_LOCATION = "email-templates"; @Override - public void init(ExtendedProperties extendedProperties) { + public void init(ExtProperties extProperties) { } @Override + public Reader getResourceReader(String name, String encoding) throws ResourceNotFoundException { +// try { +// Registry registry = +// CarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_CONFIGURATION); +// if (registry == null) { +// throw new IllegalStateException("No valid registry instance is attached to the current carbon context"); +// } +// if (!registry.resourceExists(EMAIL_CONFIG_BASE_LOCATION + "/" + name)) { +// throw new ResourceNotFoundException("Resource '" + name + "' does not exist"); +// } +// org.wso2.carbon.registry.api.Resource resource = +// registry.get(EMAIL_CONFIG_BASE_LOCATION + "/" + name); +// resource.setMediaType("text/plain"); +// +// return new InputStreamReader(resource.getContentStream()); +// } catch (RegistryException e) { +// throw new ResourceNotFoundException("Error occurred while retrieving resource", e); +// } + return null; + } + public InputStream getResourceStream(String name) throws ResourceNotFoundException { - try { - Registry registry = - CarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_CONFIGURATION); - if (registry == null) { - throw new IllegalStateException("No valid registry instance is attached to the current carbon context"); - } - if (!registry.resourceExists(EMAIL_CONFIG_BASE_LOCATION + "/" + name)) { - throw new ResourceNotFoundException("Resource '" + name + "' does not exist"); - } - org.wso2.carbon.registry.api.Resource resource = - registry.get(EMAIL_CONFIG_BASE_LOCATION + "/" + name); - resource.setMediaType("text/plain"); - return resource.getContentStream(); - } catch (RegistryException e) { - throw new ResourceNotFoundException("Error occurred while retrieving resource", e); - } +// try { +// Registry registry = +// CarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_CONFIGURATION); +// if (registry == null) { +// throw new IllegalStateException("No valid registry instance is attached to the current carbon context"); +// } +// if (!registry.resourceExists(EMAIL_CONFIG_BASE_LOCATION + "/" + name)) { +// throw new ResourceNotFoundException("Resource '" + name + "' does not exist"); +// } +// org.wso2.carbon.registry.api.Resource resource = +// registry.get(EMAIL_CONFIG_BASE_LOCATION + "/" + name); +// resource.setMediaType("text/plain"); +// return resource.getContentStream(); +// } catch (RegistryException e) { +// throw new ResourceNotFoundException("Error occurred while retrieving resource", e); +// } + return null; } @Override diff --git a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/VelocityBasedEmailContentProvider.java b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/VelocityBasedEmailContentProvider.java index ac40d746e2..98a962ffdb 100644 --- a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/VelocityBasedEmailContentProvider.java +++ b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/VelocityBasedEmailContentProvider.java @@ -22,18 +22,13 @@ import org.apache.commons.logging.LogFactory; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.runtime.resource.loader.ResourceLoader; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.RegistryType; -import org.wso2.carbon.registry.api.Registry; +import org.apache.velocity.runtime.RuntimeConstants; +import org.wso2.carbon.utils.CarbonUtils; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; +import java.io.*; import java.util.Map; public class VelocityBasedEmailContentProvider implements EmailContentProvider { @@ -41,12 +36,11 @@ public class VelocityBasedEmailContentProvider implements EmailContentProvider { private VelocityEngine engine; private static final Log log = LogFactory.getLog(VelocityBasedEmailContentProvider.class); + private static final String EMAIL_TEMPLATE_PATH = "repository" + File.separator + + "resources" + File.separator + "email-templates"; public VelocityBasedEmailContentProvider() { engine = new VelocityEngine(); - engine.setProperty("resource.loader", "registry"); - engine.setProperty("velocimacro.library", ""); - engine.setProperty("registry.resource.loader.class", - "io.entgra.device.mgt.core.transport.mgt.email.sender.core.RegistryBasedResourceLoader"); + engine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome()); engine.init(); } @@ -57,7 +51,7 @@ public class VelocityBasedEmailContentProvider implements EmailContentProvider { for (Map.Entry, Object>> param : params.entrySet()) { ctx.put(param.getKey(), param.getValue().getValue()); } - Template template = engine.getTemplate(name); + Template template = engine.getTemplate(EMAIL_TEMPLATE_PATH + File.separator + name + ".vm"); StringWriter content = new StringWriter(); template.merge(ctx, content); diff --git a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/internal/EmailSenderAxis2ConfigContextObserver.java b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/internal/EmailSenderAxis2ConfigContextObserver.java index 3c05662e0f..e43243e69b 100644 --- a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/internal/EmailSenderAxis2ConfigContextObserver.java +++ b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/internal/EmailSenderAxis2ConfigContextObserver.java @@ -17,10 +17,10 @@ */ package io.entgra.device.mgt.core.transport.mgt.email.sender.core.internal; +import io.entgra.device.mgt.core.transport.mgt.email.sender.core.EmailSenderConfigurationFailedException; import org.apache.axis2.context.ConfigurationContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.transport.mgt.email.sender.core.EmailSenderConfigurationFailedException; import org.wso2.carbon.utils.Axis2ConfigurationContextObserver; class EmailSenderAxis2ConfigContextObserver implements Axis2ConfigurationContextObserver { diff --git a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/internal/EmailSenderDataHolder.java b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/internal/EmailSenderDataHolder.java index 5c5936d8bf..def2e53fe2 100644 --- a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/internal/EmailSenderDataHolder.java +++ b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/internal/EmailSenderDataHolder.java @@ -19,12 +19,11 @@ package io.entgra.device.mgt.core.transport.mgt.email.sender.core.internal; import io.entgra.device.mgt.core.transport.mgt.email.sender.core.service.EmailSenderService; -import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.utils.ConfigurationContextService; public class EmailSenderDataHolder { - private RegistryService registryService; +// private RegistryService registryService; private ConfigurationContextService configurationContextService; private EmailSenderService emailServiceProvider; @@ -36,16 +35,16 @@ public class EmailSenderDataHolder { return thisInstance; } - public RegistryService getRegistryService() { - if (registryService == null) { - throw new IllegalStateException("Registry service is not initialized properly"); - } - return registryService; - } - - public void setRegistryService(RegistryService registryService) { - this.registryService = registryService; - } +// public RegistryService getRegistryService() { +// if (registryService == null) { +// throw new IllegalStateException("Registry service is not initialized properly"); +// } +// return registryService; +// } +// +// public void setRegistryService(RegistryService registryService) { +// this.registryService = registryService; +// } public ConfigurationContextService getConfigurationContextService() { if (configurationContextService == null) { diff --git a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/internal/EmailSenderServiceComponent.java b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/internal/EmailSenderServiceComponent.java index 45157d24f4..3a6ce00f32 100644 --- a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/internal/EmailSenderServiceComponent.java +++ b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/internal/EmailSenderServiceComponent.java @@ -17,37 +17,25 @@ */ package io.entgra.device.mgt.core.transport.mgt.email.sender.core.internal; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; import io.entgra.device.mgt.core.transport.mgt.email.sender.core.EmailSenderConfig; import io.entgra.device.mgt.core.transport.mgt.email.sender.core.service.EmailSenderService; import io.entgra.device.mgt.core.transport.mgt.email.sender.core.service.EmailSenderServiceImpl; -import org.wso2.carbon.registry.core.service.RegistryService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; import org.wso2.carbon.utils.Axis2ConfigurationContextObserver; import org.wso2.carbon.utils.ConfigurationContextService; -/** - * @scr.component name="io.entgra.device.mgt.core.email.sender.emailsendereervicecomponent" - * immediate="true" - * @scr.reference name="registry.service" - * interface="org.wso2.carbon.registry.core.service.RegistryService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRegistryService" - * unbind="unsetRegistryService" - * @scr.reference name="config.context.service" - * interface="org.wso2.carbon.utils.ConfigurationContextService" - * cardinality="0..1" - * policy="dynamic" - * bind="setConfigurationContextService" - * unbind="unsetConfigurationContextService" - */ +@Component( + name = "io.entgra.device.mgt.core.transport.mgt.email.sender.core.internal.EmailSenderServiceComponent", + immediate = true) public class EmailSenderServiceComponent { private static Log log = LogFactory.getLog(EmailSenderServiceComponent.class); @SuppressWarnings("unused") + @Activate protected void activate(ComponentContext componentContext) { try { if (log.isDebugEnabled()) { @@ -73,6 +61,7 @@ public class EmailSenderServiceComponent { } @SuppressWarnings("unused") + @Deactivate protected void deactivate(ComponentContext componentContext) { //do nothing } @@ -86,30 +75,42 @@ public class EmailSenderServiceComponent { componentContext.getBundleContext().registerService(EmailSenderService.class, emailServiceProvider, null); } - /** - * Sets Registry Service. - * - * @param registryService An instance of RegistryService - */ - protected void setRegistryService(RegistryService registryService) { - if (log.isDebugEnabled()) { - log.debug("Setting Registry Service"); - } - EmailSenderDataHolder.getInstance().setRegistryService(registryService); - } - - /** - * Unsets Registry Service. - * - * @param registryService An instance of RegistryService - */ - protected void unsetRegistryService(RegistryService registryService) { - if (log.isDebugEnabled()) { - log.debug("Un setting Registry Service"); - } - EmailSenderDataHolder.getInstance().setRegistryService(null); - } +// /** +// * Sets Registry Service. +// * +// * @param registryService An instance of RegistryService +// */ +// @Reference( +// name = "registry.service", +// service = org.wso2.carbon.registry.core.service.RegistryService.class, +// cardinality = ReferenceCardinality.MANDATORY, +// policy = ReferencePolicy.DYNAMIC, +// unbind = "unsetRegistryService") +// protected void setRegistryService(RegistryService registryService) { +// if (log.isDebugEnabled()) { +// log.debug("Setting Registry Service"); +// } +// EmailSenderDataHolder.getInstance().setRegistryService(registryService); +// } +// +// /** +// * Unsets Registry Service. +// * +// * @param registryService An instance of RegistryService +// */ +// protected void unsetRegistryService(RegistryService registryService) { +// if (log.isDebugEnabled()) { +// log.debug("Un setting Registry Service"); +// } +// EmailSenderDataHolder.getInstance().setRegistryService(null); +// } + @Reference( + name = "configuration.context.service", + service = org.wso2.carbon.utils.ConfigurationContextService.class, + cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetConfigurationContextService") protected void setConfigurationContextService(ConfigurationContextService configurationContextService) { if (log.isDebugEnabled()) { log.debug("Setting ConfigurationContextService"); diff --git a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/internal/EmailUtils.java b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/internal/EmailUtils.java index 4f89ad7f66..6e20932a80 100644 --- a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/internal/EmailUtils.java +++ b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/email/sender/core/internal/EmailUtils.java @@ -17,20 +17,15 @@ */ package io.entgra.device.mgt.core.transport.mgt.email.sender.core.internal; +import io.entgra.device.mgt.core.transport.mgt.email.sender.core.EmailSenderConfigurationFailedException; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; -import io.entgra.device.mgt.core.transport.mgt.email.sender.core.EmailSenderConfigurationFailedException; -import org.wso2.carbon.registry.api.Collection; -import org.wso2.carbon.registry.api.Registry; -import org.wso2.carbon.registry.api.RegistryException; -import org.wso2.carbon.registry.api.Resource; import org.wso2.carbon.utils.CarbonUtils; import java.io.File; import java.io.FileNotFoundException; -import java.io.FilenameFilter; import java.io.IOException; class EmailUtils { @@ -49,31 +44,11 @@ class EmailUtils { } } if (templateDir.canRead()) { - File[] templates = templateDir.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - name = name.toLowerCase(); - return name.endsWith(".vm"); - } - }); try { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - Registry registry = - EmailSenderDataHolder.getInstance().getRegistryService().getConfigSystemRegistry(tenantId); - if (!registry.resourceExists(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH)) { - Collection collection = registry.newCollection(); - registry.put(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH, collection); - for (File template : templates) { - Resource resource = registry.newResource(); - resource.setMediaType("text/plain"); - String contents = FileUtils.readFileToString(template); - resource.setContent(contents); - registry.put(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH + "/" - + template.getName().replace(".vm", ""), resource); - } - } - } catch (RegistryException e) { - throw new EmailSenderConfigurationFailedException("Error occurred while setting up email templates", e); + String tenantTemplateDirectory = CarbonUtils.getCarbonTenantsDirPath() + File.separator + tenantId + File.separator; + File destinationDirectory = new File(tenantTemplateDirectory); + FileUtils.copyDirectoryToDirectory(templateDir, destinationDirectory); } catch (FileNotFoundException e) { throw new EmailSenderConfigurationFailedException("Error occurred while writing template file " + "contents as an input stream of a resource", e); diff --git a/components/transport-mgt/email-sender/pom.xml b/components/transport-mgt/email-sender/pom.xml index 61f8223384..6b2855be0c 100644 --- a/components/transport-mgt/email-sender/pom.xml +++ b/components/transport-mgt/email-sender/pom.xml @@ -30,7 +30,7 @@ email-sender pom WSO2 Carbon - Email Sender Component - http://wso2.org + https://entgra.io io.entgra.device.mgt.core.transport.mgt.email.sender.core diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/pom.xml b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/pom.xml index c95edb55d2..57aba948bf 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/pom.xml +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/pom.xml @@ -37,10 +37,7 @@ maven-compiler-plugin - - 1.8 - 1.8 - + maven-war-plugin @@ -61,7 +58,6 @@ org.apache.maven.plugins maven-antrun-plugin - 1.7 compile @@ -134,8 +130,8 @@ provided - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api provided diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/ConfigurationManagementService.java b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/ConfigurationManagementService.java index c45d96abce..f13eb9fa13 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/ConfigurationManagementService.java +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/ConfigurationManagementService.java @@ -18,19 +18,10 @@ package io.entgra.device.mgt.core.transport.mgt.sms.handler.api; -import io.entgra.device.mgt.core.transport.mgt.sms.handler.common.SMSHandlerConstants; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; +import io.entgra.device.mgt.core.transport.mgt.sms.handler.common.SMSHandlerConstants; +import io.swagger.annotations.*; import javax.ws.rs.Consumes; import javax.ws.rs.GET; diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/addons/ApiOriginFilter.java b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/addons/ApiOriginFilter.java index 93568d35f2..af2a5c6e02 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/addons/ApiOriginFilter.java +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/addons/ApiOriginFilter.java @@ -18,12 +18,7 @@ package io.entgra.device.mgt.core.transport.mgt.sms.handler.api.addons; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/addons/GsonMessageBodyHandler.java b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/addons/GsonMessageBodyHandler.java index d8707625b8..4aa7334727 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/addons/GsonMessageBodyHandler.java +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/addons/GsonMessageBodyHandler.java @@ -24,11 +24,7 @@ import com.google.gson.GsonBuilder; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; +import java.io.*; import java.lang.annotation.Annotation; import java.lang.reflect.Type; diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/impl/ConfigurationManagementServiceImpl.java b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/impl/ConfigurationManagementServiceImpl.java index 636561c120..827654bb95 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/impl/ConfigurationManagementServiceImpl.java +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/api/impl/ConfigurationManagementServiceImpl.java @@ -18,11 +18,11 @@ package io.entgra.device.mgt.core.transport.mgt.sms.handler.api.impl; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.transport.mgt.sms.handler.api.ConfigurationManagementService; import io.entgra.device.mgt.core.transport.mgt.sms.handler.core.config.SMSConfigurationManager; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import javax.ws.rs.GET; import javax.ws.rs.Path; diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/webapp/WEB-INF/cxf-servlet.xml index 4caf9d20c9..4348a1f532 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -19,9 +19,9 @@ + http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.common/pom.xml b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.common/pom.xml index e9eb7fa723..5d0abfd980 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.common/pom.xml +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.common/pom.xml @@ -35,6 +35,14 @@ + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + org.apache.felix maven-bundle-plugin @@ -49,7 +57,10 @@ io.entgra.device.mgt.core.transport.mgt.sms.handler.common.* - io.swagger.annotations; version="${swagger.annotations.version}"; resolution:=optional, + io.entgra.device.mgt.core.transport.mgt.sms.handler.common.bean, + io.entgra.device.mgt.core.transport.mgt.sms.handler.common.exception, + io.swagger.annotations;version="[1.6,2)", + javax.xml.bind.annotation;version="[0.0,1)" @@ -90,6 +101,11 @@ swagger-annotations provided + + org.wso2.orbit.javax.xml.bind + jaxb-api + provided + diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/pom.xml b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/pom.xml index 70246b370e..3b98153af4 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/pom.xml +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/pom.xml @@ -35,10 +35,6 @@ - - org.apache.felix - maven-scr-plugin - org.jacoco jacoco-maven-plugin @@ -65,6 +61,14 @@ + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + org.apache.felix maven-bundle-plugin @@ -77,14 +81,19 @@ SMS Management Core Bundle io.entgra.device.mgt.core.transport.mgt.sms.handler.core.internal - io.entgra.device.mgt.core.transport.mgt.sms.handler.common.*, - javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, - javax.xml.bind.annotation, - javax.xml.bind, - org.apache.commons.lang, - org.wso2.carbon, - io.entgra.device.mgt.core.device.mgt.common.*, - io.entgra.device.mgt.core.device.mgt.core.* + io.entgra.device.mgt.core.device.mgt.common.exceptions;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.util;version="[5.0,6)", + io.entgra.device.mgt.core.transport.mgt.sms.handler.common.bean;version="[5.0,6)", + io.entgra.device.mgt.core.transport.mgt.sms.handler.common.config;version="[5.0,6)", + io.entgra.device.mgt.core.transport.mgt.sms.handler.common.exception;version="[5.0,6)", + io.entgra.device.mgt.core.transport.mgt.sms.handler.common.spi;version="[5.0,6)", + io.entgra.device.mgt.core.transport.mgt.sms.handler.core.config, + javax.xml.bind;version="[0.0,1)", + org.apache.commons.lang;version="[2.6,3)", + org.apache.commons.logging;version="[1.2,2)", + org.osgi.service.*;version="${imp.package.version.osgi.service}", + org.w3c.dom, + org.wso2.carbon.utils;version="[4.8,5)" !io.entgra.device.mgt.core.transport.mgt.sms.handler.core.internal, @@ -99,8 +108,13 @@ - org.wso2.carbon - org.wso2.carbon.logging + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + + + org.ops4j.pax.logging + pax-logging-api provided @@ -123,6 +137,11 @@ io.entgra.device.mgt.core.device.mgt.common provided + + org.wso2.orbit.javax.xml.bind + jaxb-api + provided + diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/core/config/SMSConfigurationManager.java b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/core/config/SMSConfigurationManager.java index e410dbd8a4..3921a27ad4 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/core/config/SMSConfigurationManager.java +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/core/config/SMSConfigurationManager.java @@ -18,13 +18,13 @@ package io.entgra.device.mgt.core.transport.mgt.sms.handler.core.config; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; +import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; import io.entgra.device.mgt.core.transport.mgt.sms.handler.common.SMSHandlerConstants; import io.entgra.device.mgt.core.transport.mgt.sms.handler.common.config.SMSConfiguration; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.utils.CarbonUtils; import javax.xml.bind.JAXBContext; diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/core/internal/SMSHandlerServiceComponent.java b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/core/internal/SMSHandlerServiceComponent.java index 3d4d4f0f99..fbd150d499 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/core/internal/SMSHandlerServiceComponent.java +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/src/main/java/io/entgra/device/mgt/core/transport/mgt/sms/handler/core/internal/SMSHandlerServiceComponent.java @@ -22,15 +22,18 @@ import io.entgra.device.mgt.core.transport.mgt.sms.handler.core.config.SMSConfig import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; -/** - * @scr.component - * name="io.entgra.device.mgt.core.transport.mgt.sms.handler.core.internal.SMSHandlerServiceComponent" immediate="true" - */ +@Component( + name = "io.entgra.device.mgt.core.transport.mgt.sms.handler.core.internal.SMSHandlerServiceComponent", + immediate = true) public class SMSHandlerServiceComponent { private static final Log log = LogFactory.getLog(SMSHandlerServiceComponent.class); + @Activate protected void activate(ComponentContext ctx) { if (log.isDebugEnabled()) { @@ -46,7 +49,7 @@ public class SMSHandlerServiceComponent { log.error("Error occurred while activating SMS Handler Service Component", e); } } - + @Deactivate protected void deactivate(ComponentContext ctx) { if (log.isDebugEnabled()) { log.debug("De-activating SMS Handler Service Component"); diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/pom.xml b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/pom.xml index 4a0ea33801..a384b894fe 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/pom.xml +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/pom.xml @@ -81,7 +81,6 @@ org.codehaus.mojo exec-maven-plugin - 1.4.0 test @@ -101,6 +100,12 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.apimgt.application.extension provided + + + org.wso2.carbon + org.wso2.carbon.tomcat + + io.entgra.device.mgt.core @@ -128,37 +133,25 @@ io.entgra.device.mgt.core.notification.logger provided - - org.springframework - spring-web - provided - - - org.apache.cxf - cxf-bundle-jaxrs - provided - javax.servlet javax.servlet-api provided - - junit - junit - test - commons-logging commons-logging - - org.apache.httpcomponents - httpclient + org.apache.httpcomponents.client5 + httpclient5 + + + org.slf4j + slf4j-api + + - - org.apache.httpcomponents httpcore @@ -319,5 +312,26 @@ httpmime compile + + commons-fileupload.wso2 + commons-fileupload + + + commons-lang + commons-lang + + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common + provided + + + javax.websocket + javax.websocket-api + + + org.json.wso2 + json + \ No newline at end of file diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultOauth2TokenHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultOauth2TokenHandler.java index dac8f541ee..959a911db2 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultOauth2TokenHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultOauth2TokenHandler.java @@ -18,26 +18,21 @@ package io.entgra.device.mgt.core.ui.request.interceptor; -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; -import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.utils.URIBuilder; -import org.apache.http.entity.ContentType; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; -import org.apache.http.entity.StringEntity; +import org.apache.hc.core5.net.URIBuilder; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; @@ -46,53 +41,81 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; -import java.util.Base64; +import java.util.Map; @MultipartConfig @WebServlet("/default-oauth2-credentials") public class DefaultOauth2TokenHandler extends HttpServlet { private static final Log log = LogFactory.getLog(DefaultTokenHandler.class); + private static final long serialVersionUID = 2254408216447549205L; + @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) { try { HttpSession httpSession = req.getSession(false); + if (httpSession != null) { AuthData authData = (AuthData) httpSession.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY); if (authData == null) { HandlerUtil.sendUnAuthorizeResponse(resp); return; } + AuthData defaultAuthData = (AuthData) httpSession .getAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY); if (defaultAuthData != null) { - String accessToken = defaultAuthData.getAccessToken(); - String accessTokenWithoutPrefix = accessToken.substring(accessToken.indexOf("_") + 1); - - HttpPost tokenEndpoint = new HttpPost(HandlerUtil.getKeyManagerUrl(req.getScheme()) + HandlerConstants.INTROSPECT_ENDPOINT); - tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); - DeviceManagementConfig dmc = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); - String adminUsername = dmc.getKeyManagerConfigurations().getAdminUsername(); - String adminPassword = dmc.getKeyManagerConfigurations().getAdminPassword(); - tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder() - .encodeToString((adminUsername + HandlerConstants.COLON + adminPassword).getBytes())); - StringEntity tokenEPPayload = new StringEntity("token=" + accessTokenWithoutPrefix, - ContentType.APPLICATION_FORM_URLENCODED); - tokenEndpoint.setEntity(tokenEPPayload); - ProxyResponse tokenStatus = HandlerUtil.execute(tokenEndpoint); - - if (HandlerConstants.DEFAULT_TOKEN_IS_EXPIRED.equals(tokenStatus.getData())) { - tokenStatus = HandlerUtil.retryRequestWithRefreshedToken(req, tokenEndpoint, HandlerUtil.getKeyManagerUrl(req.getScheme()), true); - if (!HandlerUtil.isResponseSuccessful(tokenStatus)) { - HandlerUtil.handleError(resp, tokenStatus); - return; - } - } else { - HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultAuthData.getAccessToken())); - return; + HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultAuthData.getAccessToken())); + return; + } + + String clientId = authData.getClientId(); + String clientSecret = authData.getClientSecret(); + + String queryString = req.getQueryString(); + String scopeString = ""; + if (StringUtils.isNotEmpty(queryString)) { + scopeString = req.getParameter("scopes"); + if (scopeString != null) { + scopeString = "?scopes=" + scopeString; } } - processDefaultTokenRequest(httpSession, authData, req, resp); + + ClassicHttpRequest defaultTokenRequest = + ClassicRequestBuilder.get(req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) + + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme()) + + "/api/device-mgt/v1.0/devices/" + clientId + HandlerConstants.URI_SEPARATOR + + clientSecret + "/default-token" + scopeString) + .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, org.apache.hc.core5.http.ContentType.APPLICATION_FORM_URLENCODED.toString()) + .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()) + .build(); + + ProxyResponse tokenResultResponse = HandlerUtil.execute(defaultTokenRequest); + + if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { + log.error("Error occurred while invoking the API to get default token data."); + HandlerUtil.handleError(resp, tokenResultResponse); + return; + } + JsonNode tokenResult = tokenResultResponse.getData(); + if (tokenResult == null) { + log.error("Invalid default token response is received."); + HandlerUtil.handleError(resp, tokenResultResponse); + return; + } + + AuthData newDefaultAuthData = new AuthData(); + newDefaultAuthData.setClientId(clientId); + newDefaultAuthData.setClientSecret(clientSecret); + + String defaultToken = tokenResult.get("accessToken").asText(); + newDefaultAuthData.setAccessToken(defaultToken); + newDefaultAuthData.setRefreshToken(tokenResult.get("refreshToken").asText()); + newDefaultAuthData.setScope(tokenResult.get("scopes")); + httpSession.setAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY, newDefaultAuthData); + + HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultToken)); } else { HandlerUtil.sendUnAuthorizeResponse(resp); } @@ -101,62 +124,6 @@ public class DefaultOauth2TokenHandler extends HttpServlet { } } - private void processDefaultTokenRequest(HttpSession httpSession, AuthData authData, HttpServletRequest req, HttpServletResponse resp) throws IOException { - String clientId = authData.getClientId(); - String clientSecret = authData.getClientSecret(); - - String queryString = req.getQueryString(); - String scopeString = ""; - if (StringUtils.isNotEmpty(queryString)) { - scopeString = req.getParameter("scopes"); - if (scopeString != null) { - scopeString = "?scopes=" + scopeString; - } - } - - String iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR - + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) - + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme()); - String tokenUrl = iotsCoreUrl + "/api/device-mgt/v1.0/devices/" + clientId - + "/" + clientSecret + "/default-token" + scopeString; - - HttpGet defaultTokenRequest = new HttpGet(tokenUrl); - defaultTokenRequest - .setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); - defaultTokenRequest - .setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); - ProxyResponse tokenResultResponse = HandlerUtil.execute(defaultTokenRequest); - - if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { - log.error("Error occurred while invoking the API to get default token data."); - HandlerUtil.handleError(resp, tokenResultResponse); - return; - } - String tokenResult = tokenResultResponse.getData(); - if (tokenResult == null) { - log.error("Invalid default token response is received."); - HandlerUtil.handleError(resp, tokenResultResponse); - return; - } - - JsonParser jsonParser = new JsonParser(); - JsonElement jTokenResult = jsonParser.parse(tokenResult); - if (jTokenResult.isJsonObject()) { - JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject(); - AuthData newDefaultAuthData = new AuthData(); - newDefaultAuthData.setClientId(clientId); - newDefaultAuthData.setClientSecret(clientSecret); - - String defaultToken = jTokenResultAsJsonObject.get("accessToken").getAsString(); - newDefaultAuthData.setAccessToken(defaultToken); - newDefaultAuthData.setRefreshToken(jTokenResultAsJsonObject.get("refreshToken").getAsString()); - newDefaultAuthData.setScope(jTokenResultAsJsonObject.get("scopes").getAsString()); - httpSession.setAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY, newDefaultAuthData); - - HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultToken)); - } - } - /** * Get Success Proxy Response * @param defaultAccessToken Access token which has default scope @@ -180,19 +147,19 @@ public class DefaultOauth2TokenHandler extends HttpServlet { ub3.setHost(System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR)); ub3.setPort(Integer.parseInt(System.getProperty(HandlerConstants.IOT_GATEWAY_WEBSOCKET_WS_PORT_ENV_VAR))); - JsonObject responseJsonObj = new JsonObject(); - responseJsonObj.addProperty("default-access-token", defaultAccessToken); - responseJsonObj.addProperty("remote-session-base-url", ub.toString()); - responseJsonObj.addProperty("secured-websocket-gateway-url", ub2.toString()); - responseJsonObj.addProperty("unsecured-websocket-gateway-url", ub3.toString()); - - Gson gson = new Gson(); - String payload = gson.toJson(responseJsonObj); + ObjectMapper mapper = new ObjectMapper(); + JsonNode node = JsonNodeFactory.instance.objectNode(); + Map nodeMap = mapper.convertValue(node, new TypeReference<>() { + }); + nodeMap.put("default-access-token", defaultAccessToken); + nodeMap.put("remote-session-base-url", ub.toString()); + nodeMap.put("secured-websocket-gateway-url", ub2.toString()); + nodeMap.put("unsecured-websocket-gateway-url", ub3.toString()); ProxyResponse proxyResponse = new ProxyResponse(); proxyResponse.setCode(HttpStatus.SC_OK); proxyResponse.setStatus(ProxyResponse.Status.SUCCESS); - proxyResponse.setData(payload); + proxyResponse.setData(mapper.convertValue(nodeMap, JsonNode.class)); return proxyResponse; } } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultTokenHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultTokenHandler.java index 82ebb63ba0..c0b407e7ab 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultTokenHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultTokenHandler.java @@ -18,18 +18,17 @@ package io.entgra.device.mgt.core.ui.request.interceptor; -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; -import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpStatus; -import org.apache.http.client.utils.URIBuilder; -import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.net.URIBuilder; import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.exceptions.OTPManagementException; @@ -46,11 +45,13 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; +import java.util.Map; @MultipartConfig @WebServlet("/default-credentials") public class DefaultTokenHandler extends HttpServlet { private static final Log log = LogFactory.getLog(DefaultTokenHandler.class); + private static final long serialVersionUID = 6356346497117534430L; @Override @@ -113,19 +114,19 @@ public class DefaultTokenHandler extends HttpServlet { ub3.setHost(System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR)); ub3.setPort(Integer.parseInt(System.getProperty(HandlerConstants.IOT_GATEWAY_WEBSOCKET_WS_PORT_ENV_VAR))); - JsonObject responseJsonObj = new JsonObject(); - responseJsonObj.addProperty("default-access-token", defaultAccessToken); - responseJsonObj.addProperty("remote-session-base-url", ub.toString()); - responseJsonObj.addProperty("secured-websocket-gateway-url", ub2.toString()); - responseJsonObj.addProperty("unsecured-websocket-gateway-url", ub3.toString()); - - Gson gson = new Gson(); - String payload = gson.toJson(responseJsonObj); + ObjectMapper mapper = new ObjectMapper(); + JsonNode node = JsonNodeFactory.instance.objectNode(); + Map nodeMap = mapper.convertValue(node, new TypeReference<>() { + }); + nodeMap.put("default-access-token", defaultAccessToken); + nodeMap.put("remote-session-base-url", ub.toString()); + nodeMap.put("secured-websocket-gateway-url", ub2.toString()); + nodeMap.put("unsecured-websocket-gateway-url", ub3.toString()); ProxyResponse proxyResponse = new ProxyResponse(); proxyResponse.setCode(HttpStatus.SC_OK); proxyResponse.setStatus(ProxyResponse.Status.SUCCESS); - proxyResponse.setData(payload); + proxyResponse.setData(mapper.convertValue(nodeMap, JsonNode.class)); return proxyResponse; } } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/GrafanaHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/GrafanaHandler.java index 72ba9aaa51..414067ff20 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/GrafanaHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/GrafanaHandler.java @@ -21,6 +21,7 @@ package io.entgra.device.mgt.core.ui.request.interceptor; import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common.exception.GrafanaManagementException; import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.exception.GrafanaEnvVariablesNotDefined; import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.util.GrafanaUtil; +import io.entgra.device.mgt.core.device.mgt.core.common.util.HttpUtil; import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.util.GrafanaHandlerUtil; @@ -29,13 +30,12 @@ import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.*; -import org.apache.http.impl.client.CloseableHttpClient; -import io.entgra.device.mgt.core.device.mgt.core.common.util.HttpUtil; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; @@ -68,7 +68,7 @@ public class GrafanaHandler extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpGet grafanaRequest = new HttpGet(); + ClassicHttpRequest grafanaRequest = ClassicRequestBuilder.get().build(); HandlerUtil.copyRequestHeaders(req, grafanaRequest, true); if (!GrafanaUtil.isGrafanaAPI(req.getRequestURI())) { proxyPassGrafanaRequest(grafanaRequest, resp, req); @@ -112,7 +112,7 @@ public class GrafanaHandler extends HttpServlet { protected void doPost(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpPost grafanaRequest = new HttpPost(); + ClassicHttpRequest grafanaRequest = ClassicRequestBuilder.post().build(); HandlerUtil.generateRequestEntity(req, grafanaRequest); HandlerUtil.copyRequestHeaders(req, grafanaRequest, true); if (!GrafanaUtil.isGrafanaAPI(req.getRequestURI())) { @@ -206,10 +206,10 @@ public class GrafanaHandler extends HttpServlet { return true; } - private ProxyResponse executeGrafanaAPIRequest(HttpRequestBase requestBase, HttpServletRequest request) + private ProxyResponse executeGrafanaAPIRequest(ClassicHttpRequest requestBase, HttpServletRequest request) throws IOException { URI grafanaUri = HttpUtil.createURI(generateGrafanaAPIUrl(request)); - requestBase.setURI(grafanaUri); + requestBase.setUri(grafanaUri); return HandlerUtil.execute(requestBase); } @@ -230,14 +230,14 @@ public class GrafanaHandler extends HttpServlet { } return uri; } - private void proxyPassGrafanaRequest(HttpRequestBase requestBase, HttpServletResponse response, + private void proxyPassGrafanaRequest(ClassicHttpRequest requestBase, HttpServletResponse response, HttpServletRequest request) throws IOException { try (CloseableHttpClient client = HandlerUtil.getHttpClient()) { String grafanaUriStr = GrafanaHandlerUtil.generateGrafanaUrl(HttpUtil.createURI(getURIWithQuery(request)), GrafanaUtil.getGrafanaHTTPBase(request.getScheme())); URI grafanaURI = HttpUtil.createURI(grafanaUriStr); - requestBase.setURI(grafanaURI); - HttpResponse grafanaResponse = invokeGrafanaAPI(client, requestBase); + requestBase.setUri(grafanaURI); + CloseableHttpResponse grafanaResponse = invokeGrafanaAPI(client, requestBase); forwardGrafanaResponse(grafanaResponse, response); } catch (GrafanaEnvVariablesNotDefined e) { handleError(response, HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage()); @@ -248,17 +248,19 @@ public class GrafanaHandler extends HttpServlet { } } - private HttpResponse invokeGrafanaAPI(HttpClient client, HttpRequestBase request) throws IOException, GrafanaManagementException { + private CloseableHttpResponse invokeGrafanaAPI(CloseableHttpClient client, ClassicHttpRequest request) throws IOException, + GrafanaManagementException { setBasicAuthHeader(request); + //todo this is deprecated call return client.execute(request); } - private void setBasicAuthHeader(HttpRequestBase request) throws GrafanaManagementException { + private void setBasicAuthHeader(ClassicHttpRequest request) throws GrafanaManagementException { String basicAuth = GrafanaUtil.getBasicAuthBase64Header(); request.setHeader(HttpHeaders.AUTHORIZATION, basicAuth); } - private void forwardGrafanaResponse(HttpResponse grafanaResponse, HttpServletResponse response) throws IOException { + private void forwardGrafanaResponse(CloseableHttpResponse grafanaResponse, HttpServletResponse response) throws IOException { InputStream responseContent = grafanaResponse.getEntity().getContent(); String grafanaContentType = HandlerUtil.getMemeType(grafanaResponse); response.setHeader(HttpHeaders.CONTENT_TYPE, grafanaContentType); diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/HubspotHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/HubspotHandler.java index 2e2f5b73bf..559336b6e7 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/HubspotHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/HubspotHandler.java @@ -18,17 +18,15 @@ package io.entgra.device.mgt.core.ui.request.interceptor; -import com.google.gson.JsonObject; -import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; +import com.fasterxml.jackson.databind.JsonNode; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; @@ -48,89 +46,94 @@ import java.io.IOException; ) public class HubspotHandler extends HttpServlet { - private static final Log log = LogFactory.getLog(HubspotHandler.class); - private HttpSession httpSession; - private static String hubspotEndpoint; - private static String chatConfig; - private JsonObject uiConfigJsonObject; - private static String gatewayUrl; - private static String iotsCoreUrl; + private static final Log log = LogFactory.getLog(HubspotHandler.class); + private HttpSession httpSession; + private static String hubspotEndpoint; + private static String chatConfig; + private JsonNode uiConfigJsonObject; + private static String gatewayUrl; + private static String iotsCoreUrl; - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) { - try { - if (validateRequest(req, resp)) { - HttpPost postRequest = new HttpPost(HandlerUtil.generateBackendRequestURL(req, hubspotEndpoint)); - HandlerUtil.generateChatRequestEntity(req, postRequest); - postRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); - postRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig); - ProxyResponse proxyResponse = HandlerUtil.execute(postRequest); - HandlerUtil.handleSuccess(resp, proxyResponse); - } - } catch (IOException e) { - log.error("Error occurred when processing POST request.", e); - } + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) { + try { + if (validateRequest(req, resp)) { + ClassicHttpRequest postRequest = ClassicRequestBuilder.post(HandlerUtil.generateBackendRequestURL(req, hubspotEndpoint)) + .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, "application/json") + .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig) + .build(); + HandlerUtil.generateChatRequestEntity(req, postRequest); + HandlerUtil.handleSuccess(resp, HandlerUtil.execute(postRequest)); + } + } catch (IOException e) { + log.error("Error occurred when processing POST request.", e); } + } - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) { - try { - if (validateRequest(req, resp)) { - HttpGet getRequest = new HttpGet(HandlerUtil.generateBackendRequestURL(req,hubspotEndpoint)); - getRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); - getRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig); - ProxyResponse proxyResponse = HandlerUtil.execute(getRequest); - HandlerUtil.handleSuccess(resp, proxyResponse); - } - } catch (IOException e) { - log.error("Error occurred when processing GET request.", e); - } + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) { + try { + if (validateRequest(req, resp)) { + ClassicHttpRequest getRequest = + ClassicRequestBuilder.get(HandlerUtil.generateBackendRequestURL(req, hubspotEndpoint)) + .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, "application/json") + .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, + HandlerConstants.BEARER + chatConfig).build(); + HandlerUtil.handleSuccess(resp, HandlerUtil.execute(getRequest)); + } + } catch (IOException e) { + log.error("Error occurred when processing GET request.", e); } + } + + @Override + protected void doDelete(HttpServletRequest req, HttpServletResponse resp) { + try { + if (validateRequest(req, resp)) { + ClassicHttpRequest deleteRequest = + ClassicRequestBuilder.delete(HandlerUtil.generateBackendRequestURL(req, hubspotEndpoint)) + .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, "application/json") + .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, + HandlerConstants.BEARER + chatConfig).build(); - @Override - protected void doDelete(HttpServletRequest req, HttpServletResponse resp){ - try{ - if(validateRequest(req, resp)){ - HttpDelete deleteRequest = new HttpDelete(HandlerUtil.generateBackendRequestURL(req,hubspotEndpoint)); - deleteRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); - deleteRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig); - ProxyResponse proxyResponse = HandlerUtil.execute(deleteRequest); - HandlerUtil.handleSuccess(resp, proxyResponse); - } - } catch (IOException e){ - log.error("Error occurred when processing DELETE request.", e); + deleteRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); + deleteRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig); + HandlerUtil.handleSuccess(resp, HandlerUtil.execute(deleteRequest)); } + } catch (IOException e) { + log.error("Error occurred when processing DELETE request.", e); } + } - /*** - * Validates the hubspot's incoming request. - * - * @param req {@link HttpServletRequest} - * @param resp {@link HttpServletResponse} - * @return If request is a valid one, returns TRUE, otherwise return FALSE - * @throws IOException If and error occurs while witting error response to client side - */ - private boolean validateRequest(HttpServletRequest req, HttpServletResponse resp) - throws IOException { - httpSession = req.getSession(false); - if (httpSession == null) { - log.error("Unauthorized, You are not logged in. Please log in to the portal"); - HandlerUtil.handleError(resp, HttpStatus.SC_UNAUTHORIZED); - return false; - } - if (req.getMethod() == null) { - log.error("Bad Request, Request method is empty"); - HandlerUtil.handleError(resp, HttpStatus.SC_BAD_REQUEST); - return false; - } - gatewayUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) - + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme()); - iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR) - + HandlerConstants.COLON + HandlerUtil.getCorePort(req.getScheme()); - String uiConfigUrl = iotsCoreUrl + HandlerConstants.UI_CONFIG_ENDPOINT; - uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, resp); - chatConfig = uiConfigJsonObject.get("hubspotChat").getAsJsonObject().get("accessToken").getAsString(); - hubspotEndpoint = HandlerConstants.HTTPS_PROTOCOL + HandlerConstants.SCHEME_SEPARATOR + HandlerConstants.HUBSPOT_CHAT_URL; - return true; + /*** + * Validates the hubspot's incoming request. + * + * @param req {@link HttpServletRequest} + * @param resp {@link HttpServletResponse} + * @return If request is a valid one, returns TRUE, otherwise return FALSE + * @throws IOException If and error occurs while witting error response to client side + */ + private boolean validateRequest(HttpServletRequest req, HttpServletResponse resp) + throws IOException { + httpSession = req.getSession(false); + if (httpSession == null) { + log.error("Unauthorized, You are not logged in. Please log in to the portal"); + HandlerUtil.handleError(resp, HttpStatus.SC_UNAUTHORIZED); + return false; + } + if (req.getMethod() == null) { + log.error("Bad Request, Request method is empty"); + HandlerUtil.handleError(resp, HttpStatus.SC_BAD_REQUEST); + return false; } + gatewayUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) + + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme()); + iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR) + + HandlerConstants.COLON + HandlerUtil.getCorePort(req.getScheme()); + String uiConfigUrl = iotsCoreUrl + HandlerConstants.UI_CONFIG_ENDPOINT; + uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, resp); + chatConfig = uiConfigJsonObject.get("hubspotChat").get("accessToken").textValue(); + hubspotEndpoint = HandlerConstants.HTTPS_PROTOCOL + HandlerConstants.SCHEME_SEPARATOR + HandlerConstants.HUBSPOT_CHAT_URL; + return true; + } } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/InvokerHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/InvokerHandler.java index 00b35af06c..e8ffb2deef 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/InvokerHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/InvokerHandler.java @@ -19,20 +19,18 @@ package io.entgra.device.mgt.core.ui.request.interceptor; import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; +import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpHead; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; + import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; @@ -61,7 +59,7 @@ public class InvokerHandler extends HttpServlet { protected void doPost(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpPost postRequest = new HttpPost(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest postRequest = ClassicRequestBuilder.post(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)).build(); HandlerUtil.generateRequestEntity(req, postRequest); postRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); ProxyResponse proxyResponse = HandlerUtil.execute(postRequest); @@ -91,7 +89,8 @@ public class InvokerHandler extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpGet getRequest = new HttpGet(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest getRequest = ClassicRequestBuilder.get(HandlerUtil.generateBackendRequestURL(req, + apiEndpoint)).build(); HandlerUtil.copyRequestHeaders(req, getRequest, false); getRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); ProxyResponse proxyResponse = HandlerUtil.execute(getRequest); @@ -126,7 +125,8 @@ public class InvokerHandler extends HttpServlet { protected void doHead(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpHead headRequest = new HttpHead(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest headRequest = ClassicRequestBuilder.head(HandlerUtil.generateBackendRequestURL(req, + apiEndpoint)).build(); HandlerUtil.copyRequestHeaders(req, headRequest, false); headRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); ProxyResponse proxyResponse = HandlerUtil.execute(headRequest); @@ -153,7 +153,8 @@ public class InvokerHandler extends HttpServlet { protected void doPut(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpPut putRequest = new HttpPut(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest putRequest = ClassicRequestBuilder.put(HandlerUtil.generateBackendRequestURL(req, + apiEndpoint)).build(); HandlerUtil.generateRequestEntity(req, putRequest); putRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); ProxyResponse proxyResponse = HandlerUtil.execute(putRequest); @@ -183,7 +184,8 @@ public class InvokerHandler extends HttpServlet { protected void doDelete(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpDelete deleteRequest = new HttpDelete(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest deleteRequest = ClassicRequestBuilder.delete(HandlerUtil.generateBackendRequestURL(req, + apiEndpoint)).build(); HandlerUtil.copyRequestHeaders(req, deleteRequest, false); deleteRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); ProxyResponse proxyResponse = HandlerUtil.execute(deleteRequest); diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/JITEnrollmentCallbackHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/JITEnrollmentCallbackHandler.java index 6a82ae3f26..40db118c7d 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/JITEnrollmentCallbackHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/JITEnrollmentCallbackHandler.java @@ -18,10 +18,12 @@ package io.entgra.device.mgt.core.ui.request.interceptor; +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.JsonArray; -import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import com.google.gson.JsonParser; import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; import io.entgra.device.mgt.core.ui.request.interceptor.beans.JITData; import io.entgra.device.mgt.core.ui.request.interceptor.beans.JITEnrollmentData; @@ -32,8 +34,8 @@ import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHeaders; -import org.apache.http.client.methods.HttpPost; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.w3c.dom.Document; @@ -53,8 +55,7 @@ import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; -import java.util.Base64; -import java.util.Objects; +import java.util.*; @WebServlet( name = "JIT Enrollment callback handler", @@ -75,6 +76,7 @@ public class JITEnrollmentCallbackHandler extends HttpServlet { private String scope; private String JITConfigurationPath; private JITEnrollmentData JITEnrollmentInfo; + @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) { gatewayUrl = request.getScheme() + HandlerConstants.SCHEME_SEPARATOR @@ -130,7 +132,7 @@ public class JITEnrollmentCallbackHandler extends HttpServlet { } else if (Objects.equals(JITEnrollmentInfo.getOs(), HandlerConstants.OS_IOS)) { enrollmentScopes = (Element) JITConfigurationDoc. getElementsByTagName(HandlerConstants.TAG_IOS_ENROLLMENT_SCOPES).item(0); - } else if (Objects.equals(JITEnrollmentInfo.getOs(), HandlerConstants.OS_WINDOWS)) { + } else if (Objects.equals(JITEnrollmentInfo.getOs(), HandlerConstants.OS_WINDOWS)) { enrollmentScopes = (Element) JITConfigurationDoc. getElementsByTagName(HandlerConstants.TAG_WINDOWS_ENROLLMENT_SCOPES).item(0); } else { @@ -168,32 +170,42 @@ public class JITEnrollmentCallbackHandler extends HttpServlet { * @return {@link JsonObject} Json object corresponding to provided json string * @throws JITEnrollmentException throws when error occurred while parsing */ - private JsonObject parseResponseData(String data) throws JITEnrollmentException { - JsonParser parser = new JsonParser(); - JsonElement responseData = parser.parse(data); - if (responseData.isJsonObject()) { - return responseData.getAsJsonObject(); + private JsonNode parseResponseData(String data) throws JITEnrollmentException { + + JsonFactory jsonFactory = new JsonFactory(); + ObjectMapper objectMapper = new ObjectMapper(jsonFactory); + try { + return objectMapper.readTree(data); + } catch (JsonProcessingException e) { + throw new JITEnrollmentException("Unexpected response body return"); } - throw new JITEnrollmentException("Unexpected response body return"); } /*** * Build application registration request - * @return {@link HttpPost} Application registration request + * @return {@link ClassicHttpRequest} Application registration request */ - private HttpPost buildApplicationRegistrationRequest() { - HttpPost applicationRegistrationRequest = new HttpPost(gatewayUrl + HandlerConstants.APP_REG_ENDPOINT); - applicationRegistrationRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC - + JITInfo.getEncodedClientCredentials()); - applicationRegistrationRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); + private ClassicHttpRequest buildApplicationRegistrationRequest() { + JsonArray tags = new JsonArray(); tags.add("device_management"); - JsonObject payload = new JsonObject(); - payload.addProperty("applicationName", applicationName); - payload.add("tags", tags); - payload.addProperty("allowedToAllDomains", false); - payload.addProperty("mappingAnExistingOAuthApp", false); - applicationRegistrationRequest.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON)); + + ObjectMapper objectMapper = new ObjectMapper(); + Map payload = new HashMap<>(); + + payload.put("applicationName", applicationName); + payload.put("tags", tags); + payload.put("allowedToAllDomains", false); + payload.put("mappingAnExistingOAuthApp", false); + + ClassicHttpRequest applicationRegistrationRequest = ClassicRequestBuilder.post(gatewayUrl + HandlerConstants.APP_REG_ENDPOINT) + .setEntity(new org.apache.hc.core5.http.io.entity.StringEntity(objectMapper.valueToTree(payload).toString(), + org.apache.hc.core5.http.ContentType.APPLICATION_JSON)) + .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, + org.apache.hc.core5.http.ContentType.APPLICATION_JSON.toString()) + .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + + JITInfo.getEncodedClientCredentials()) + .build(); return applicationRegistrationRequest; } @@ -201,10 +213,10 @@ public class JITEnrollmentCallbackHandler extends HttpServlet { * Populate dynamic client's data * @param application - application data receiving from dcr request */ - private void populateApplicationData(JsonObject application) { - clientId = application.get("client_id").getAsString(); - clientSecret = application.get("client_secret").getAsString(); - String headerValue = clientId+ ':' + clientSecret; + private void populateApplicationData(JsonNode application) { + clientId = application.get("client_id").asText(); + clientSecret = application.get("client_secret").asText(); + String headerValue = clientId + ':' + clientSecret; encodedClientCredentials = Base64.getEncoder().encodeToString(headerValue.getBytes()); } @@ -213,12 +225,12 @@ public class JITEnrollmentCallbackHandler extends HttpServlet { * @return {@link JsonObject} Json object contain registered application data * @throws JITEnrollmentException throws when error occurred while application registration */ - private JsonObject registerApplication() throws JITEnrollmentException { + private JsonNode registerApplication() throws JITEnrollmentException { try { ProxyResponse proxyResponse = HandlerUtil.execute(buildApplicationRegistrationRequest()); if (proxyResponse.getCode() == HttpStatus.SC_CREATED || proxyResponse.getCode() == HttpStatus.SC_OK) { - return parseResponseData(proxyResponse.getData()); + return parseResponseData(proxyResponse.getData().toString()); } throw new JITEnrollmentException("Unexpected response status return for application registration request"); } catch (IOException ex) { @@ -231,12 +243,12 @@ public class JITEnrollmentCallbackHandler extends HttpServlet { * @return {@link JsonObject} Json object containing token data * @throws JITEnrollmentException throws when error occurred while acquiring token */ - private JsonObject getToken() throws JITEnrollmentException { + private JsonNode getToken() throws JITEnrollmentException { try { ProxyResponse proxyResponse = HandlerUtil.execute(buildTokenAcquireRequest()); if (proxyResponse.getCode() == org.apache.http.HttpStatus.SC_CREATED || proxyResponse.getCode() == org.apache.http.HttpStatus.SC_OK) { - return parseResponseData(proxyResponse.getData()); + return parseResponseData(proxyResponse.getData().toString()); } throw new JITEnrollmentException("Unexpected response status return for token acquiring request"); } catch (IOException ex) { @@ -246,17 +258,19 @@ public class JITEnrollmentCallbackHandler extends HttpServlet { /*** * Build token acquire request - * @return {@link HttpPost} Token acquire request + * @return {@link ClassicHttpRequest} Token acquire request */ - private HttpPost buildTokenAcquireRequest() { - HttpPost tokenAcquiringRequest = new HttpPost(keyManagerUrl + HandlerConstants.OAUTH2_TOKEN_ENDPOINT); - tokenAcquiringRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); - tokenAcquiringRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC - + encodedClientCredentials); + private ClassicHttpRequest buildTokenAcquireRequest() { + StringEntity payload = new StringEntity( "grant_type=" + HandlerConstants.CLIENT_CREDENTIAL_GRANT_TYPE + "&scope=" + scope, ContentType.APPLICATION_FORM_URLENCODED); - tokenAcquiringRequest.setEntity(payload); + + ClassicHttpRequest tokenAcquiringRequest = ClassicRequestBuilder.post(keyManagerUrl + HandlerConstants.OAUTH2_TOKEN_ENDPOINT) + .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()) + .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + encodedClientCredentials) + .setEntity(new org.apache.hc.core5.http.io.entity.StringEntity(payload.toString(), org.apache.hc.core5.http.ContentType.APPLICATION_JSON)) + .build(); return tokenAcquiringRequest; } @@ -265,13 +279,13 @@ public class JITEnrollmentCallbackHandler extends HttpServlet { * @param session - {@link HttpSession} * @param token - Json object containing token data */ - private void persistAuthData(HttpSession session, JsonObject token) { + private void persistAuthData(HttpSession session, JsonNode token) { AuthData authData = new AuthData(); - authData.setAccessToken(token.get("access_token").getAsString()); + authData.setAccessToken(token.get("access_token").asText()); authData.setClientId(clientId); authData.setClientSecret(clientSecret); authData.setEncodedClientApp(encodedClientCredentials); - authData.setScope(token.get("scope").getAsString()); + authData.setScope(token.get("scope")); session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, authData); } } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/JITEnrollmentHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/JITEnrollmentHandler.java index 8ca9cdf98c..0c3de9e429 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/JITEnrollmentHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/JITEnrollmentHandler.java @@ -19,14 +19,10 @@ package io.entgra.device.mgt.core.ui.request.interceptor; import io.entgra.device.mgt.core.ui.request.interceptor.beans.JITEnrollmentData; -import io.entgra.device.mgt.core.ui.request.interceptor.exceptions.JITEnrollmentException; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.wso2.carbon.utils.CarbonUtils; -import org.xml.sax.SAXException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/JITProvisionCallbackHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/JITProvisionCallbackHandler.java index 433c1e7de3..b6496e0db3 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/JITProvisionCallbackHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/JITProvisionCallbackHandler.java @@ -19,12 +19,11 @@ package io.entgra.device.mgt.core.ui.request.interceptor; import io.entgra.device.mgt.core.ui.request.interceptor.beans.JITData; -import io.entgra.device.mgt.core.ui.request.interceptor.beans.JITEnrollmentData; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; -import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.hc.core5.http.HttpStatus; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/JITProvisionHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/JITProvisionHandler.java index 9c1cf31a94..4b02cec035 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/JITProvisionHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/JITProvisionHandler.java @@ -18,22 +18,13 @@ package io.entgra.device.mgt.core.ui.request.interceptor; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; import io.entgra.device.mgt.core.ui.request.interceptor.beans.JITData; -import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; -import io.entgra.device.mgt.core.ui.request.interceptor.exceptions.JITEnrollmentException; import io.entgra.device.mgt.core.ui.request.interceptor.exceptions.JITProvisionException; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; +import org.apache.hc.core5.http.HttpStatus; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/LoginHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/LoginHandler.java index 82b31ce1a0..6a97630e99 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/LoginHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/LoginHandler.java @@ -18,12 +18,11 @@ package io.entgra.device.mgt.core.ui.request.interceptor; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.google.gson.JsonSyntaxException; import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; +import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.cache.LoginCache; import io.entgra.device.mgt.core.ui.request.interceptor.cache.OAuthApp; import io.entgra.device.mgt.core.ui.request.interceptor.cache.OAuthAppCacheKey; @@ -32,13 +31,12 @@ import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.protocol.HTTP; -import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; +import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.NameValuePair; +import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; +import org.apache.hc.core5.http.message.BasicNameValuePair; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; @@ -47,7 +45,9 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; +import java.util.ArrayList; import java.util.Base64; +import java.util.List; @MultipartConfig @WebServlet("/login") @@ -71,10 +71,13 @@ public class LoginHandler extends HttpServlet { httpSession.invalidate(); } httpSession = req.getSession(true); + final String baseContextPath = req.getContextPath(); + final String applicationName = baseContextPath.substring(1, baseContextPath.indexOf("-ui-request-handler")) + "-login"; - JsonObject uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, resp); - JsonArray tags = uiConfigJsonObject.get("appRegistration").getAsJsonObject().get("tags").getAsJsonArray(); - JsonArray scopes = uiConfigJsonObject.get("scopes").getAsJsonArray(); + JsonNode uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, + resp); + ArrayNode tags = (ArrayNode) uiConfigJsonObject.get("appRegistration").get("tags"); + ArrayNode scopes = (ArrayNode) uiConfigJsonObject.get("scopes"); int sessionTimeOut = Integer.parseInt(String.valueOf(uiConfigJsonObject.get("sessionTimeOut"))); //setting session to expire in 1h @@ -82,15 +85,20 @@ public class LoginHandler extends HttpServlet { // Check if OAuth app cache exists. If not create a new application. LoginCache loginCache = HandlerUtil.getLoginCache(httpSession); - OAuthAppCacheKey oAuthAppCacheKey = new OAuthAppCacheKey(HandlerConstants.PUBLISHER_APPLICATION_NAME, username); + OAuthAppCacheKey oAuthAppCacheKey = new OAuthAppCacheKey(applicationName, username); OAuthApp oAuthApp = loginCache.getOAuthAppCache(oAuthAppCacheKey); if (oAuthApp == null) { - HttpPost apiRegEndpoint = new HttpPost(gatewayUrl + HandlerConstants.APP_REG_ENDPOINT); - apiRegEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder() - .encodeToString((username + HandlerConstants.COLON + password).getBytes())); - apiRegEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); - apiRegEndpoint.setEntity(HandlerUtil.constructAppRegPayload(tags, HandlerConstants.PUBLISHER_APPLICATION_NAME, username, password)); + ArrayList supportedGrantTypes = new ArrayList<>(); + supportedGrantTypes.add(HandlerConstants.PASSWORD_GRANT_TYPE); + supportedGrantTypes.add(HandlerConstants.REFRESH_TOKEN_GRANT_TYPE); + ClassicHttpRequest apiRegEndpoint = ClassicRequestBuilder.post(gatewayUrl + HandlerConstants.APP_REG_ENDPOINT) + .setEntity(HandlerUtil.constructAppRegPayload(tags, applicationName, + username, password, null, supportedGrantTypes)) + .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, + org.apache.hc.core5.http.ContentType.APPLICATION_JSON.toString()) + .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder().encodeToString((username + HandlerConstants.COLON + password).getBytes())) + .build(); ProxyResponse clientAppResponse = HandlerUtil.execute(apiRegEndpoint); @@ -100,19 +108,17 @@ public class LoginHandler extends HttpServlet { } if (clientAppResponse.getCode() == HttpStatus.SC_CREATED) { - JsonParser jsonParser = new JsonParser(); - JsonElement jClientAppResult = jsonParser.parse(clientAppResponse.getData()); + JsonNode jsonNode = clientAppResponse.getData(); String clientId = null; String clientSecret = null; String encodedClientApp = null; - if (jClientAppResult.isJsonObject()) { - JsonObject jClientAppResultAsJsonObject = jClientAppResult.getAsJsonObject(); - clientId = jClientAppResultAsJsonObject.get("client_id").getAsString(); - clientSecret = jClientAppResultAsJsonObject.get("client_secret").getAsString(); + if (jsonNode != null) { + clientId = jsonNode.get("client_id").textValue(); + clientSecret = jsonNode.get("client_secret").textValue(); encodedClientApp = Base64.getEncoder() .encodeToString((clientId + HandlerConstants.COLON + clientSecret).getBytes()); oAuthApp = new OAuthApp( - HandlerConstants.PUBLISHER_APPLICATION_NAME, + applicationName, username, clientId, clientSecret, @@ -156,8 +162,7 @@ public class LoginHandler extends HttpServlet { */ private boolean getTokenAndPersistInSession(HttpServletRequest req, HttpServletResponse resp, String clientId, String clientSecret, String encodedClientApp, - JsonArray scopes) throws LoginException { - JsonParser jsonParser = new JsonParser(); + ArrayNode scopes) throws LoginException { try { ProxyResponse tokenResultResponse = getTokenResult(encodedClientApp, scopes); @@ -167,31 +172,26 @@ public class LoginHandler extends HttpServlet { HandlerUtil.handleError(resp, tokenResultResponse); return false; } - String tokenResult = tokenResultResponse.getData(); + JsonNode tokenResult = tokenResultResponse.getData(); if (tokenResult == null) { log.error("Invalid token response is received."); HandlerUtil.handleError(resp, tokenResultResponse); return false; } - JsonElement jTokenResult = jsonParser.parse(tokenResult); - if (jTokenResult.isJsonObject()) { - JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject(); - HttpSession session = req.getSession(false); - if (session == null) { - return false; - } - AuthData authData = new AuthData(); - authData.setClientId(clientId); - authData.setClientSecret(clientSecret); - authData.setEncodedClientApp(encodedClientApp); - authData.setAccessToken(jTokenResultAsJsonObject.get("access_token").getAsString()); - authData.setRefreshToken(jTokenResultAsJsonObject.get("refresh_token").getAsString()); - authData.setScope(jTokenResultAsJsonObject.get("scope").getAsString()); - session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, authData); - return true; + HttpSession session = req.getSession(false); + if (session == null) { + return false; } - return false; + AuthData authData = new AuthData(); + authData.setClientId(clientId); + authData.setClientSecret(clientSecret); + authData.setEncodedClientApp(encodedClientApp); + authData.setAccessToken(tokenResult.get("access_token").textValue()); + authData.setRefreshToken(tokenResult.get("refresh_token").textValue()); + authData.setScope(tokenResult.get("scope")); + session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, authData); + return true; } catch (IOException e) { throw new LoginException("Error occurred while sending the response into the socket", e); } @@ -228,23 +228,27 @@ public class LoginHandler extends HttpServlet { * @return Invoke token endpoint and return the response as string. * @throws IOException IO exception throws if an error occurred when invoking token endpoint */ - private ProxyResponse getTokenResult(String encodedClientApp, JsonArray scopes) throws IOException { - HttpPost tokenEndpoint = new HttpPost(gatewayUrl + HandlerConstants.INTERNAL_TOKEN_ENDPOINT); - tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + encodedClientApp); - tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); + private ProxyResponse getTokenResult(String encodedClientApp, JsonNode scopes) throws IOException { String scopeString = HandlerUtil.getScopeString(scopes); - if (scopeString != null) { scopeString = scopeString.trim(); } else { scopeString = "default"; } - StringEntity tokenEPPayload = new StringEntity( - "grant_type=" + HandlerConstants.PASSWORD_GRANT_TYPE + "&username=" + username + "&password=" + - password + "&scope=" + scopeString, - ContentType.APPLICATION_FORM_URLENCODED); - tokenEndpoint.setEntity(tokenEPPayload); + List nameValuePairs = new ArrayList<>(); + nameValuePairs.add(new BasicNameValuePair("grant_type", HandlerConstants.PASSWORD_GRANT_TYPE)); + nameValuePairs.add(new BasicNameValuePair("username", username)); + nameValuePairs.add(new BasicNameValuePair("password", password)); + nameValuePairs.add(new BasicNameValuePair("scope", scopeString)); + + + ClassicHttpRequest tokenEndpoint = ClassicRequestBuilder.post(gatewayUrl + HandlerConstants.INTERNAL_TOKEN_ENDPOINT) + .setEntity(new UrlEncodedFormEntity(nameValuePairs)) + .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, + org.apache.hc.core5.http.ContentType.APPLICATION_FORM_URLENCODED.toString()) + .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + encodedClientApp) + .build(); return HandlerUtil.execute(tokenEndpoint); } } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/LogoutHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/LogoutHandler.java index 0d0bd5fbe7..496007fe88 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/LogoutHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/LogoutHandler.java @@ -18,11 +18,11 @@ package io.entgra.device.mgt.core.ui.request.interceptor; +import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpStatus; -import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; +import org.apache.hc.core5.http.HttpStatus; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/OTPInvokerHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/OTPInvokerHandler.java index 1505bb9434..9e6954fe47 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/OTPInvokerHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/OTPInvokerHandler.java @@ -18,19 +18,17 @@ package io.entgra.device.mgt.core.ui.request.interceptor; +import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpHead; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; + import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -54,7 +52,8 @@ public class OTPInvokerHandler extends HttpServlet { protected void doPost(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpPost postRequest = new HttpPost(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest postRequest = ClassicRequestBuilder.post(HandlerUtil.generateBackendRequestURL(req + , apiEndpoint)).build(); HandlerUtil.generateRequestEntity(req, postRequest); ProxyResponse proxyResponse = HandlerUtil.execute(postRequest); @@ -76,7 +75,8 @@ public class OTPInvokerHandler extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpGet getRequest = new HttpGet(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest getRequest = ClassicRequestBuilder.get(HandlerUtil.generateBackendRequestURL(req + , apiEndpoint)).build(); HandlerUtil.copyRequestHeaders(req, getRequest, false); ProxyResponse proxyResponse = HandlerUtil.execute(getRequest); @@ -96,7 +96,8 @@ public class OTPInvokerHandler extends HttpServlet { protected void doHead(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpHead headRequest = new HttpHead(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest headRequest = ClassicRequestBuilder.head(HandlerUtil.generateBackendRequestURL(req + , apiEndpoint)).build(); HandlerUtil.copyRequestHeaders(req, headRequest, false); ProxyResponse proxyResponse = HandlerUtil.execute(headRequest); @@ -116,7 +117,8 @@ public class OTPInvokerHandler extends HttpServlet { protected void doPut(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpPut putRequest = new HttpPut(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest putRequest = ClassicRequestBuilder.put(HandlerUtil.generateBackendRequestURL(req + , apiEndpoint)).build(); HandlerUtil.generateRequestEntity(req, putRequest); ProxyResponse proxyResponse = HandlerUtil.execute(putRequest); @@ -138,7 +140,8 @@ public class OTPInvokerHandler extends HttpServlet { protected void doDelete(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpDelete deleteRequest = new HttpDelete(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest deleteRequest = ClassicRequestBuilder.delete(HandlerUtil.generateBackendRequestURL(req + , apiEndpoint)).build(); HandlerUtil.copyRequestHeaders(req, deleteRequest, false); ProxyResponse proxyResponse = HandlerUtil.execute(deleteRequest); diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/PermissionScopeHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/PermissionScopeHandler.java index 1516b4faa7..90d272907a 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/PermissionScopeHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/PermissionScopeHandler.java @@ -18,15 +18,15 @@ package io.entgra.device.mgt.core.ui.request.interceptor; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; -import org.apache.commons.lang3.StringUtils; -import org.apache.http.HttpStatus; -import org.json.JSONObject; +import org.apache.commons.lang.StringUtils; +import org.apache.hc.core5.http.HttpStatus; -import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; @@ -34,12 +34,16 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; +import java.util.HashMap; +import java.util.Map; @MultipartConfig @WebServlet("/login-user/scopes") public class PermissionScopeHandler extends HttpServlet { + private static final long serialVersionUID = 976006906915355611L; + @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { HttpSession httpSession = req.getSession(false); if (httpSession == null) { HandlerUtil.sendUnAuthorizeResponse(resp); @@ -52,13 +56,16 @@ public class PermissionScopeHandler extends HttpServlet { return; } - if (!StringUtils.isEmpty(authData.getScope())) { + if (!StringUtils.isEmpty(authData.getScope().toString())) { ProxyResponse proxyResponse = new ProxyResponse(); - JSONObject jsonObject = new JSONObject(); - jsonObject.put(HandlerConstants.USER_SCOPES, authData.getScope()); + JsonNode authDataScope = authData.getScope(); + + ObjectMapper mapper = new ObjectMapper(); + Map nodeMap = new HashMap<>(); + nodeMap.put(HandlerConstants.USER_SCOPES, authDataScope.asText().replace("\"", "")); proxyResponse.setCode(HttpStatus.SC_OK); proxyResponse.setStatus(ProxyResponse.Status.SUCCESS); - proxyResponse.setData(jsonObject.toString()); + proxyResponse.setData(mapper.convertValue(nodeMap, JsonNode.class)); HandlerUtil.handleSuccess(resp, proxyResponse); return; } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginCallbackHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginCallbackHandler.java index 2730090125..2acd5fc167 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginCallbackHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginCallbackHandler.java @@ -18,20 +18,18 @@ package io.entgra.device.mgt.core.ui.request.interceptor; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; +import com.fasterxml.jackson.databind.JsonNode; import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; +import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; @@ -75,33 +73,35 @@ public class SsoLoginCallbackHandler extends HttpServlet { } String scope = session.getAttribute("scope").toString(); - - HttpPost tokenEndpoint = new HttpPost(keyManagerUrl + HandlerConstants.OAUTH2_TOKEN_ENDPOINT); - tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + session.getAttribute("encodedClientApp")); - tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); - String loginCallbackUrl = iotsCoreUrl + req.getContextPath() + HandlerConstants.SSO_LOGIN_CALLBACK; StringEntity tokenEPPayload = new StringEntity( "grant_type=" + HandlerConstants.CODE_GRANT_TYPE + "&code=" + code + "&scope=" + scope + "&redirect_uri=" + loginCallbackUrl, ContentType.APPLICATION_FORM_URLENCODED); - tokenEndpoint.setEntity(tokenEPPayload); + + ClassicHttpRequest tokenEndpoint = ClassicRequestBuilder.post(keyManagerUrl + HandlerConstants.OAUTH2_TOKEN_ENDPOINT) + .setEntity(tokenEPPayload) + .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, org.apache.hc.core5.http.ContentType.APPLICATION_FORM_URLENCODED.toString()) + .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + session.getAttribute("encodedClientApp")) + .build(); + ProxyResponse tokenResultResponse = HandlerUtil.execute(tokenEndpoint); + JsonNode jsonNode = tokenResultResponse.getData(); - JsonParser jsonParser = new JsonParser(); - JsonElement jTokenResult = jsonParser.parse(tokenResultResponse.getData()); - if (jTokenResult.isJsonObject()) { - JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject(); + if (jsonNode != null) { AuthData authData = new AuthData(); authData.setClientId(session.getAttribute("clientId").toString()); authData.setClientSecret(session.getAttribute("clientSecret").toString()); authData.setEncodedClientApp(session.getAttribute("encodedClientApp").toString()); - authData.setAccessToken(jTokenResultAsJsonObject.get("access_token").getAsString()); - authData.setRefreshToken(jTokenResultAsJsonObject.get("refresh_token").getAsString()); - authData.setScope(jTokenResultAsJsonObject.get("scope").getAsString()); + authData.setAccessToken(jsonNode.get("access_token").textValue()); + authData.setRefreshToken(jsonNode.get("refresh_token").textValue()); + authData.setScope(jsonNode.get("scope")); session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, authData); resp.sendRedirect(session.getAttribute("redirectUrl").toString()); + } else { + log.error("Found empty response for token call."); + HandlerUtil.handleError(resp, HandlerConstants.INTERNAL_ERROR_CODE); } } } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginHandler.java index 78fb91f7ae..4f63c48b32 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginHandler.java @@ -18,33 +18,21 @@ package io.entgra.device.mgt.core.ui.request.interceptor; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.JsonSyntaxException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.cache.LoginCache; import io.entgra.device.mgt.core.ui.request.interceptor.cache.OAuthApp; import io.entgra.device.mgt.core.ui.request.interceptor.cache.OAuthAppCacheKey; +import io.entgra.device.mgt.core.ui.request.interceptor.exceptions.LoginException; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; -import org.apache.commons.lang.text.StrSubstitutor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.protocol.HTTP; -import org.json.JSONArray; -import org.json.JSONObject; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; import org.w3c.dom.Document; -import org.w3c.dom.NodeList; -import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; -import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.servlet.annotation.MultipartConfig; @@ -58,30 +46,25 @@ import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; -import java.io.StringReader; +import java.util.ArrayList; import java.util.Base64; -import java.util.HashMap; -import java.util.Map; @MultipartConfig @WebServlet("/ssoLogin") public class SsoLoginHandler extends HttpServlet { private static final Log log = LogFactory.getLog(SsoLoginHandler.class); + private static final long serialVersionUID = 5594017767311123453L; private static String adminUsername; private static String adminPassword; private static String gatewayUrl; - private static String iotsCoreUrl; - private static String apiMgtUrl; - private static String keyManagerUrl; + private static String iotSCoreUrl; private static int sessionTimeOut; - private static String encodedAdminCredentials; private static String encodedClientApp; - private static String applicationId; private static String applicationName; private static String baseContextPath; - private JsonObject uiConfigJsonObject; + private JsonNode uiConfigJsonObject; private HttpSession httpSession; private LoginCache loginCache; private OAuthApp oAuthApp; @@ -105,15 +88,14 @@ public class SsoLoginHandler extends HttpServlet { gatewayUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme()); - iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR) + iotSCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR) + HandlerConstants.COLON + HandlerUtil.getCorePort(req.getScheme()); - apiMgtUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_APIM_HOST_ENV_VAR) - + HandlerConstants.COLON + HandlerUtil.getAPIManagerPort(req.getScheme()); - keyManagerUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_KM_HOST_ENV_VAR) + String keyManagerUrl = + req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_KM_HOST_ENV_VAR) + HandlerConstants.COLON + HandlerUtil.getKeyManagerPort(req.getScheme()); // Fetch ui config and persists in session - String uiConfigUrl = iotsCoreUrl + HandlerConstants.UI_CONFIG_ENDPOINT; + String uiConfigUrl = iotSCoreUrl + HandlerConstants.UI_CONFIG_ENDPOINT; uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, resp); // Retrieving login cache and do a DCR if the cache is not available. @@ -125,9 +107,10 @@ public class SsoLoginHandler extends HttpServlet { } String clientId = oAuthApp.getClientId(); - JsonArray scopesSsoJson = uiConfigJsonObject.get("scopes").getAsJsonArray(); - String scopesSsoString = HandlerUtil.getScopeString(scopesSsoJson); - String loginCallbackUrl = iotsCoreUrl + baseContextPath + HandlerConstants.SSO_LOGIN_CALLBACK; + + JsonNode scopeJsonNode = uiConfigJsonObject.get("scopes"); + String scopesSsoString = HandlerUtil.getScopeString(scopeJsonNode); + String loginCallbackUrl = iotSCoreUrl + baseContextPath + HandlerConstants.SSO_LOGIN_CALLBACK; persistAuthSessionData(req, oAuthApp.getClientId(), oAuthApp.getClientSecret(), oAuthApp.getEncodedClientApp(), scopesSsoString, state); resp.sendRedirect(keyManagerUrl + HandlerConstants.AUTHORIZATION_ENDPOINT + @@ -138,12 +121,12 @@ public class SsoLoginHandler extends HttpServlet { "&redirect_uri=" + loginCallbackUrl); } catch (IOException e) { log.error("Error occurred while sending the response into the socket. ", e); - } catch (JsonSyntaxException e) { - log.error("Error occurred while parsing the response. ", e); } catch (ParserConfigurationException e) { log.error("Error while creating the document builder."); } catch (SAXException e) { log.error("Error while parsing xml file.", e); + } catch (LoginException e) { + log.error("SSO Login is failed. Application: " + applicationName, e); } } @@ -154,37 +137,34 @@ public class SsoLoginHandler extends HttpServlet { * @param req {@link HttpServletRequest} * @param resp {@link HttpServletResponse} */ - private void dynamicClientRegistration(HttpServletRequest req, HttpServletResponse resp) { + private void dynamicClientRegistration(HttpServletRequest req, HttpServletResponse resp) throws LoginException { try { - JsonArray tags = uiConfigJsonObject.get("appRegistration").getAsJsonObject().get("tags").getAsJsonArray(); - JsonArray scopes = uiConfigJsonObject.get("scopes").getAsJsonArray(); + ArrayNode tags = (ArrayNode) uiConfigJsonObject.get("appRegistration").get("tags"); + JsonNode scopes = uiConfigJsonObject.get("scopes"); sessionTimeOut = Integer.parseInt(String.valueOf(uiConfigJsonObject.get("sessionTimeOut"))); + String callbackUrl = iotSCoreUrl + baseContextPath + HandlerConstants.SSO_LOGIN_CALLBACK; - // Register the client application - HttpPost apiRegEndpoint = new HttpPost(gatewayUrl + HandlerConstants.APP_REG_ENDPOINT); - encodedAdminCredentials = Base64.getEncoder() + String encodedAdminCredentials = Base64.getEncoder() .encodeToString((adminUsername + HandlerConstants.COLON + adminPassword).getBytes()); - apiRegEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + - encodedAdminCredentials); - apiRegEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); - apiRegEndpoint.setEntity(HandlerUtil.constructAppRegPayload(tags, applicationName, adminUsername, adminPassword)); + ClassicHttpRequest apiRegEndpoint = ClassicRequestBuilder.post(gatewayUrl + HandlerConstants.APP_REG_ENDPOINT) + .setEntity(HandlerUtil.constructAppRegPayload(tags, applicationName, adminUsername, adminPassword, + callbackUrl, constructAppGrantTypeUpdateArray())) + .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, + org.apache.hc.core5.http.ContentType.APPLICATION_JSON.toString()) + .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + + encodedAdminCredentials) + .build(); ProxyResponse clientAppResponse = HandlerUtil.execute(apiRegEndpoint); - if (clientAppResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) { - HandlerUtil.handleError(resp, clientAppResponse); - } - if (clientAppResponse.getCode() == HttpStatus.SC_CREATED) { - JsonParser jsonParser = new JsonParser(); - JsonElement jClientAppResult = jsonParser.parse(clientAppResponse.getData()); String clientId = null; String clientSecret = null; + JsonNode jsonNode = clientAppResponse.getData(); - if (jClientAppResult.isJsonObject()) { - JsonObject jClientAppResultAsJsonObject = jClientAppResult.getAsJsonObject(); - clientId = jClientAppResultAsJsonObject.get("client_id").getAsString(); - clientSecret = jClientAppResultAsJsonObject.get("client_secret").getAsString(); + if (jsonNode != null) { + clientId = jsonNode.get("client_id").textValue(); + clientSecret = jsonNode.get("client_secret").textValue(); encodedClientApp = Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes()); String scopesString = HandlerUtil.getScopeString(scopes); persistAuthSessionData(req, clientId, clientSecret, encodedClientApp, scopesString, state); @@ -193,70 +173,22 @@ public class SsoLoginHandler extends HttpServlet { // cache the oauth app credentials oAuthApp = new OAuthApp(applicationName, adminUsername, clientId, clientSecret, encodedClientApp); loginCache.addOAuthAppToCache(oAuthAppCacheKey, oAuthApp); + } else if (clientAppResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) { + String msg = "Unauthorized attempt to register the client application. " + + "Application Name: " + applicationName + ". Response message: " + clientAppResponse.getData(); + log.error(msg); + HandlerUtil.handleError(resp, clientAppResponse); + throw new LoginException(msg); + } else { + String msg = "Failed the process while registering the client application. " + + "Application Name: " + applicationName + ". Response Code: " + + clientAppResponse.getCode() + ", Response message: " + clientAppResponse.getData(); + log.error(msg); + HandlerUtil.handleError(resp, null); + throw new LoginException(msg); } - - // Get the details of the registered application - String getApplicationEndpointUrl = apiMgtUrl + HandlerConstants.APIM_APPLICATIONS_ENDPOINT + - "?query=" + applicationName; - HttpGet getApplicationEndpoint = new HttpGet(getApplicationEndpointUrl); - getApplicationEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + - getAccessToken(resp, encodedClientApp)); - - ProxyResponse getApplicationResponse = HandlerUtil.execute(getApplicationEndpoint); - - if (getApplicationResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) { - HandlerUtil.handleError(resp, getApplicationResponse); - return; - } - - if (getApplicationResponse.getCode() == HttpStatus.SC_OK) { - JsonParser jsonParser = new JsonParser(); - JsonElement jAppResult = jsonParser.parse(getApplicationResponse.getData()); - if (jAppResult.isJsonObject()) { - JsonObject jClientAppResultAsJsonObject = jAppResult.getAsJsonObject(); - JsonArray appList = jClientAppResultAsJsonObject.getAsJsonArray("list"); - JsonObject app; - for (JsonElement appJson : appList) { - app = appJson.getAsJsonObject(); - if (app.get("name").getAsString().equals(applicationName)) { - applicationId = app.get("applicationId").getAsString(); - break; - } - } - } - } - - // Update the grant types of the application - String url = apiMgtUrl + HandlerConstants.APIM_APPLICATIONS_ENDPOINT + applicationId + "/keys/" + - HandlerConstants.PRODUCTION_KEY; - HttpPut updateApplicationGrantTypesEndpoint = new HttpPut(url); - updateApplicationGrantTypesEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + - getAccessToken(resp, encodedClientApp)); - updateApplicationGrantTypesEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); - updateApplicationGrantTypesEndpoint.setEntity(constructAppGrantTypeUpdatePayload()); - - ProxyResponse updateApplicationGrantTypesEndpointResponse = HandlerUtil.execute(updateApplicationGrantTypesEndpoint); - - // Update app as a SaaS app - this.updateSaasApp(applicationId); - - if (updateApplicationGrantTypesEndpointResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) { - HandlerUtil.handleError(resp, updateApplicationGrantTypesEndpointResponse); - return; - } - - if (updateApplicationGrantTypesEndpointResponse.getCode() == HttpStatus.SC_OK) { - return; - } - HandlerUtil.handleError(resp, null); } catch (IOException e) { - log.error("Error occurred while sending the response into the socket. ", e); - } catch (JsonSyntaxException e) { - log.error("Error occurred while parsing the response. ", e); - } catch (ParserConfigurationException e) { - log.error("Error while creating the document builder."); - } catch (SAXException e) { - log.error("Error while parsing xml file.", e); + throw new LoginException("Error occurred while sending the response into the socket.", e); } } @@ -277,7 +209,6 @@ public class SsoLoginHandler extends HttpServlet { adminPassword = doc.getElementsByTagName("Password").item(0).getTextContent(); } - /** * Persist the Auth data inside the session * @@ -302,172 +233,14 @@ public class SsoLoginHandler extends HttpServlet { /*** * Generates payload for application grant_type update payload * - * @return {@link StringEntity} of the payload to update application grant type + * @return {@link ArrayList} of the payload to update application grant type */ - private StringEntity constructAppGrantTypeUpdatePayload() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("supportedGrantTypes", - new JSONArray(new Object[]{ - HandlerConstants.CODE_GRANT_TYPE, - HandlerConstants.REFRESH_TOKEN_GRANT_TYPE, - HandlerConstants.PASSWORD_GRANT_TYPE, - HandlerConstants.JWT_BEARER_GRANT_TYPE - }) - ); - jsonObject.put(HandlerConstants.CALLBACK_URL_KEY, iotsCoreUrl + baseContextPath + HandlerConstants.SSO_LOGIN_CALLBACK); - String payload = jsonObject.toString(); - return new StringEntity(payload, ContentType.APPLICATION_JSON); - } - - /*** - * Generates tokens using password grant_type by invoking token endpoint - * - * @param encodedClientApp - Base64 encoded clientId:clientSecret. - * @return Invoke token endpoint and return the response as string. - * @throws IOException IO exception throws if an error occurred when invoking token endpoint - */ - private ProxyResponse getTokenResult(String encodedClientApp) throws IOException { - HttpPost tokenEndpoint = new HttpPost(keyManagerUrl + HandlerConstants.OAUTH2_TOKEN_ENDPOINT); - tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + encodedClientApp); - tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); - - StringEntity tokenEPPayload = new StringEntity( - "grant_type=" + HandlerConstants.PASSWORD_GRANT_TYPE + "&username=" + adminUsername + "&password=" + adminPassword + - "&scope=apim:api_view apim:api_create apim:api_publish apim:subscribe", - ContentType.APPLICATION_FORM_URLENCODED); - tokenEndpoint.setEntity(tokenEPPayload); - return HandlerUtil.execute(tokenEndpoint); - } - - /*** - * Retrieves and returns access token - * - * @param resp - Http Servlet Response - * @param encodedClientApp - Base64 encoded clientId:clientSecret. - * @return Returns access token - * @throws IOException IO exception throws if an error occurred when invoking token endpoint - */ - private String getAccessToken(HttpServletResponse resp, String encodedClientApp) throws IOException { - ProxyResponse tokenResultResponse = getTokenResult(encodedClientApp); - - if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { - log.error("Error occurred while invoking the API to get token data."); - HandlerUtil.handleError(resp, tokenResultResponse); - } - String tokenResult = tokenResultResponse.getData(); - if (tokenResult == null) { - log.error("Invalid token response is received."); - HandlerUtil.handleError(resp, tokenResultResponse); - } - - JsonParser jsonParser = new JsonParser(); - JsonElement jTokenResult = jsonParser.parse(tokenResult); - - JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject(); - return jTokenResultAsJsonObject.get("access_token").getAsString(); - } - - /*** - * Updates Application - * - * @param appName - Application name - * @throws IOException IO exception throws if an error occurred when invoking token endpoint - * @throws ParserConfigurationException,SAXException throws if an error occurred when parsing xml - */ - private void updateSaasApp(String appName) throws ParserConfigurationException, IOException, SAXException { - File getAppRequestXmlFile = new File(HandlerConstants.PAYLOADS_DIR + "/get-app-request.xml"); - String identityAppMgtUrl = apiMgtUrl + HandlerConstants.IDENTITY_APP_MGT_ENDPOINT; - - HttpPost getApplicationEndpoint = new HttpPost(identityAppMgtUrl); - getApplicationEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + - encodedAdminCredentials); - getApplicationEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_XML.toString()); - getApplicationEndpoint.setHeader(HandlerConstants.SOAP_ACTION_HEADER, "urn:getApplication"); - - String requestBodyString = HandlerUtil.xmlToString(getAppRequestXmlFile); - - Map data = new HashMap<>(); - appName = adminUsername + HandlerConstants.UNDERSCORE + appName + HandlerConstants.UNDERSCORE + - HandlerConstants.PRODUCTION_KEY; - data.put("applicationName", appName); - requestBodyString = StrSubstitutor.replace(requestBodyString, data); - getApplicationEndpoint.setEntity(new StringEntity(requestBodyString, ContentType.TEXT_XML)); - - ProxyResponse getApplicationEndpointResponse = HandlerUtil.execute(getApplicationEndpoint); - - Document doc = DocumentBuilderFactory.newInstance() - .newDocumentBuilder() - .parse(new InputSource(new StringReader(getApplicationEndpointResponse.getData()))); - NodeList nodeList = doc.getElementsByTagName(HandlerConstants.AX_PREFIX + "inboundAuthenticationConfig"); - NodeList childNodeList; - String nodeName; - - data.clear(); - data.put("applicationId", doc.getElementsByTagName(HandlerConstants.AX_PREFIX + "applicationID").item(0).getTextContent()); - data.put("applicationName", doc.getElementsByTagName(HandlerConstants.AX_PREFIX + "applicationName").item(0).getTextContent()); - data.put("description", doc.getElementsByTagName(HandlerConstants.AX_PREFIX + "description").item(0).getTextContent()); - data.put("saasApp", "true"); - - for (int i = 0; i < nodeList.getLength(); i++) { - childNodeList = nodeList.item(i).getChildNodes(); - for (int j = 0; j < childNodeList.getLength(); j++) { - if (childNodeList.item(j).getNodeName().equalsIgnoreCase(HandlerConstants.AX_PREFIX + "inboundAuthenticationRequestConfigs")) { - NodeList inboundAuthRequestConfigs = childNodeList.item(j).getChildNodes(); - for (int k = 0; k < inboundAuthRequestConfigs.getLength(); k++) { - nodeName = inboundAuthRequestConfigs.item(k).getNodeName(); - if (nodeName.equalsIgnoreCase(HandlerConstants.AX_PREFIX + "inboundAuthKey")) { - data.put("inboundAuthKey", inboundAuthRequestConfigs.item(k).getTextContent()); - } - if (nodeName.equalsIgnoreCase(HandlerConstants.AX_PREFIX + "inboundAuthType")) { - data.put("inboundAuthType", inboundAuthRequestConfigs.item(k).getTextContent()); - } - if (nodeName.equalsIgnoreCase(HandlerConstants.AX_PREFIX + "inboundConfigType")) { - data.put("inboundConfigType", inboundAuthRequestConfigs.item(k).getTextContent()); - } - } - } - } - } - - nodeList = doc.getElementsByTagName(HandlerConstants.AX_PREFIX + "owner"); - for (int i = 0; i < nodeList.getLength(); i++) { - childNodeList = nodeList.item(i).getChildNodes(); - for (int j = 0; j < childNodeList.getLength(); j++) { - switch (childNodeList.item(j).getNodeName()) { - case HandlerConstants.AX_PREFIX + "tenantDomain": - data.put("tenantDomain", childNodeList.item(j).getTextContent()); - break; - case HandlerConstants.AX_PREFIX + "userName": - data.put("userName", childNodeList.item(j).getTextContent()); - break; - case HandlerConstants.AX_PREFIX + "userStoreDomain": - data.put("userStoreDomain", childNodeList.item(j).getTextContent()); - break; - } - } - } - - nodeList = doc.getElementsByTagName(HandlerConstants.AX_PREFIX + "spProperties"); - for (int k = 0; k < nodeList.getLength(); k++) { - childNodeList = nodeList.item(k).getChildNodes(); - for (int l = 0; l < childNodeList.getLength(); l++) { - if (childNodeList.item(l).getNodeName().equalsIgnoreCase(HandlerConstants.AX_PREFIX + "value")) { - data.put("displayName", childNodeList.item(l).getTextContent()); - } - } - } - - File appUpdateRequest = new File(HandlerConstants.PAYLOADS_DIR + "/update-app-request.xml"); - String docStr = HandlerUtil.xmlToString(appUpdateRequest); - requestBodyString = StrSubstitutor.replace(docStr, data); - - HttpPost updateApplicationEndpoint = new HttpPost(identityAppMgtUrl); - updateApplicationEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + - encodedAdminCredentials); - updateApplicationEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_XML.toString()); - updateApplicationEndpoint.setHeader(HandlerConstants.SOAP_ACTION_HEADER, "urn:updateApplication"); - updateApplicationEndpoint.setEntity(new StringEntity(requestBodyString, ContentType.TEXT_XML)); - - HandlerUtil.execute(updateApplicationEndpoint); + private ArrayList constructAppGrantTypeUpdateArray() { + ArrayList jsonArray = new ArrayList<>(); + jsonArray.add(HandlerConstants.CODE_GRANT_TYPE); + jsonArray.add(HandlerConstants.REFRESH_TOKEN_GRANT_TYPE); + jsonArray.add(HandlerConstants.PASSWORD_GRANT_TYPE); + jsonArray.add(HandlerConstants.JWT_BEARER_GRANT_TYPE); + return jsonArray; } } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLogoutHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLogoutHandler.java index bc019fe0b8..5dbd7d85f9 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLogoutHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLogoutHandler.java @@ -18,20 +18,16 @@ package io.entgra.device.mgt.core.ui.request.interceptor; +import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpStatus; -import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; +import org.apache.hc.core5.http.HttpStatus; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import javax.servlet.http.Cookie; +import javax.servlet.http.*; import java.io.IOException; @MultipartConfig diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/UserHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/UserHandler.java index 011215bc2d..5ca4860c87 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/UserHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/UserHandler.java @@ -18,24 +18,26 @@ package io.entgra.device.mgt.core.ui.request.interceptor; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.JsonSyntaxException; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; +import io.entgra.device.mgt.core.device.mgt.extensions.logger.spi.EntgraLogger; +import io.entgra.device.mgt.core.notification.logger.UserLoginLogContext; +import io.entgra.device.mgt.core.notification.logger.impl.EntgraUserLoginLoggerImpl; import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; -import io.entgra.device.mgt.core.device.mgt.extensions.logger.spi.EntgraLogger; -import io.entgra.device.mgt.core.notification.logger.UserLoginLogContext; -import io.entgra.device.mgt.core.notification.logger.impl.EntgraUserLoginLoggerImpl; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; -import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; +import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.NameValuePair; +import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; +import org.apache.hc.core5.http.message.BasicNameValuePair; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; @@ -44,7 +46,9 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; +import java.util.ArrayList; import java.util.Base64; +import java.util.List; @MultipartConfig @WebServlet("/user") @@ -56,7 +60,7 @@ public class UserHandler extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { try { - String keymanagerUrl = + String keyManagerUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_KM_HOST_ENV_VAR) + HandlerConstants.COLON + HandlerUtil.getKeyManagerPort(req.getScheme()); @@ -73,24 +77,24 @@ public class UserHandler extends HttpServlet { } String accessToken = authData.getAccessToken(); - String accessTokenWithoutPrefix = accessToken.substring(accessToken.indexOf("_") + 1); - - HttpPost tokenEndpoint = new HttpPost(keymanagerUrl + HandlerConstants.INTROSPECT_ENDPOINT); - tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); DeviceManagementConfig dmc = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); String adminUsername = dmc.getKeyManagerConfigurations().getAdminUsername(); String adminPassword = dmc.getKeyManagerConfigurations().getAdminPassword(); - tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder() - .encodeToString((adminUsername + HandlerConstants.COLON + adminPassword).getBytes())); - StringEntity tokenEPPayload = new StringEntity("token=" + accessTokenWithoutPrefix, - ContentType.APPLICATION_FORM_URLENCODED); - tokenEndpoint.setEntity(tokenEPPayload); - ProxyResponse tokenStatus = HandlerUtil.execute(tokenEndpoint); + List nameValuePairs = new ArrayList<>(); + nameValuePairs.add(new BasicNameValuePair("token", accessToken)); + + ClassicHttpRequest introspectCall = ClassicRequestBuilder.post(keyManagerUrl + HandlerConstants.INTROSPECT_ENDPOINT) + .setEntity(new UrlEncodedFormEntity(nameValuePairs)) + .setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()) + .setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder().encodeToString((adminUsername + HandlerConstants.COLON + adminPassword).getBytes())) + .build(); + + ProxyResponse tokenStatus = HandlerUtil.execute(introspectCall); if (tokenStatus.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { if (tokenStatus.getCode() == HttpStatus.SC_UNAUTHORIZED) { - tokenStatus = HandlerUtil.retryRequestWithRefreshedToken(req, tokenEndpoint, keymanagerUrl); - if(!HandlerUtil.isResponseSuccessful(tokenStatus)) { + tokenStatus = HandlerUtil.retryRequestWithRefreshedToken(req, introspectCall, keyManagerUrl); + if (!HandlerUtil.isResponseSuccessful(tokenStatus)) { HandlerUtil.handleError(resp, tokenStatus); return; } @@ -100,35 +104,34 @@ public class UserHandler extends HttpServlet { return; } } - String tokenData = tokenStatus.getData(); + JsonNode tokenData = tokenStatus.getData(); if (tokenData == null) { log.error("Invalid token data is received."); HandlerUtil.handleError(resp, tokenStatus); return; } - JsonParser jsonParser = new JsonParser(); - JsonElement jTokenResult = jsonParser.parse(tokenData); - if (jTokenResult.isJsonObject()) { - JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject(); - if (!jTokenResultAsJsonObject.get("active").getAsBoolean()) { - HandlerUtil.sendUnAuthorizeResponse(resp); - return; - } - ProxyResponse proxyResponse = new ProxyResponse(); - proxyResponse.setStatus(ProxyResponse.Status.SUCCESS); - proxyResponse.setCode(HttpStatus.SC_OK); - proxyResponse.setData( - jTokenResultAsJsonObject.get("username").getAsString().replaceAll("@carbon.super", "")); - HandlerUtil.handleSuccess(resp, proxyResponse); - httpSession.setAttribute(HandlerConstants.USERNAME_WITH_DOMAIN, jTokenResultAsJsonObject.get("username").getAsString()); - log.info( - "User " + proxyResponse.getData() + " logged in", - userLoginLogContextBuilder - .setUserName(proxyResponse.getData()) - .setUserRegistered(true) - .build() - ); + + if (!tokenData.get("active").asBoolean()) { + HandlerUtil.sendUnAuthorizeResponse(resp); + return; } + ProxyResponse proxyResponse = new ProxyResponse(); + proxyResponse.setStatus(ProxyResponse.Status.SUCCESS); + proxyResponse.setCode(HttpStatus.SC_OK); + + ObjectMapper mapper = new ObjectMapper(); + String data = tokenData.get("username").textValue().replaceAll("@carbon.super", ""); + proxyResponse.setData(mapper.convertValue(data, JsonNode.class)); + + HandlerUtil.handleSuccess(resp, proxyResponse); + httpSession.setAttribute(HandlerConstants.USERNAME_WITH_DOMAIN, tokenData.get("username").textValue()); + log.info( + "User " + proxyResponse.getData() + " logged in", + userLoginLogContextBuilder + .setUserName(proxyResponse.getData().toString()) + .setUserRegistered(true) + .build() + ); } catch (IOException e) { log.error("Error occurred while sending the response into the socket. ", e); } catch (JsonSyntaxException e) { diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/beans/AuthData.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/beans/AuthData.java index 36cb8aea59..a0c057383c 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/beans/AuthData.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/beans/AuthData.java @@ -19,6 +19,8 @@ package io.entgra.device.mgt.core.ui.request.interceptor.beans; +import com.fasterxml.jackson.databind.JsonNode; + public class AuthData implements java.io.Serializable { private static final long serialVersionUID = -5156750882531944849L; @@ -29,7 +31,7 @@ public class AuthData implements java.io.Serializable { private String clientId; private String clientSecret; private String encodedClientApp; - private String scope; + private JsonNode scope; public String getAccessToken() { return accessToken; @@ -79,11 +81,11 @@ public class AuthData implements java.io.Serializable { this.encodedClientApp = encodedClientApp; } - public String getScope() { + public JsonNode getScope() { return scope; } - public void setScope(String scope) { + public void setScope(JsonNode scope) { this.scope = scope; } } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/beans/ProxyResponse.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/beans/ProxyResponse.java index 263a98bfeb..d259b33314 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/beans/ProxyResponse.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/beans/ProxyResponse.java @@ -17,7 +17,8 @@ */ package io.entgra.device.mgt.core.ui.request.interceptor.beans; -import org.apache.http.Header; +import com.fasterxml.jackson.databind.JsonNode; +import org.apache.hc.core5.http.Header; public class ProxyResponse { @@ -27,7 +28,7 @@ public class ProxyResponse { } private int code; - private String data; + private JsonNode data; private String executorResponse; private int status; private Header[] headers; @@ -36,9 +37,9 @@ public class ProxyResponse { public void setCode(int code) { this.code = code; } - public String getData() { return data; } + public JsonNode getData() { return data; } - public void setData(String data) { this.data = data; } + public void setData(JsonNode data) { this.data = data; } public String getExecutorResponse() { return executorResponse; } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/exceptions/JITEnrollmentException.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/exceptions/JITEnrollmentException.java index c845f8b5c8..ae7129985a 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/exceptions/JITEnrollmentException.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/exceptions/JITEnrollmentException.java @@ -20,6 +20,8 @@ package io.entgra.device.mgt.core.ui.request.interceptor.exceptions; public class JITEnrollmentException extends Exception { + private static final long serialVersionUID = -5414968249196525915L; + public JITEnrollmentException(String msg, Throwable t) { super(msg, t); } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/exceptions/JITProvisionException.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/exceptions/JITProvisionException.java index fc3018890d..34cfc2568c 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/exceptions/JITProvisionException.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/exceptions/JITProvisionException.java @@ -20,6 +20,8 @@ package io.entgra.device.mgt.core.ui.request.interceptor.exceptions; public class JITProvisionException extends Exception { + private static final long serialVersionUID = 1413607461296734217L; + public JITProvisionException(String msg, Throwable t) { super(msg, t); } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/exceptions/LoginException.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/exceptions/LoginException.java index 4a7396a31a..dc9ed4f36e 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/exceptions/LoginException.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/exceptions/LoginException.java @@ -19,6 +19,8 @@ package io.entgra.device.mgt.core.ui.request.interceptor.exceptions; public class LoginException extends Exception { + private static final long serialVersionUID = -6376045524044788791L; + public LoginException(String message) { super(message); } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerConstants.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerConstants.java index d38b9942d3..33d8dd420b 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerConstants.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerConstants.java @@ -26,7 +26,7 @@ public class HandlerConstants { public static final String INTERNAL_TOKEN_ENDPOINT = "/token"; public static final String INTROSPECT_ENDPOINT = "/oauth2/introspect"; public static final String AUTHORIZATION_ENDPOINT = "/oauth2/authorize"; - public static final String APIM_APPLICATIONS_ENDPOINT = "/api/am/devportal/v2/applications/"; + public static final String APIM_APPLICATIONS_ENDPOINT = "/api/am/devportal/v3/applications"; public static final String IDENTITY_APP_MGT_ENDPOINT = "/services/IdentityApplicationManagementService.IdentityApplicationManagementServiceHttpsSoap11Endpoint"; public static final String LOGIN_PAGE = "/login"; public static final String SSO_LOGIN_CALLBACK = "/ssoLoginCallback"; @@ -43,6 +43,7 @@ public class HandlerConstants { public static final String SESSION_DEFAULT_AUTH_DATA_KEY = "defaultAuthInfo"; public static final String UI_CONFIG_KEY = "ui-config"; public static final String CALLBACK_URL_KEY = "callbackUrl"; + public static final String GRANT_TYPE_KEY = "supportedGrantTypes"; public static final String IS_ALLOWED_TO_ALL_DOMAINS_KEY = "isAllowedToAllDomains"; public static final String JSESSIONID_KEY = "JSESSIONID"; public static final String COMMON_AUTH_ID_KEY = "commonAuthId"; @@ -78,7 +79,7 @@ public class HandlerConstants { public static final String OTP_HEADER = "one-time-token"; - public static final String AX_PREFIX = "ax2251:"; + public static final String AX_PREFIX = "ax2245:"; public static final String PAYLOADS_DIR = "repository/resources/payloads"; public static final String SOAP_ACTION_HEADER = "SOAPAction"; public static final String REFERER_HEADER = "Referer"; diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerUtil.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerUtil.java index 0d991c8693..26c4be4201 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerUtil.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerUtil.java @@ -18,8 +18,15 @@ package io.entgra.device.mgt.core.ui.request.interceptor.util; +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.gson.Gson; -import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; @@ -32,50 +39,48 @@ import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.*; -import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.classic.methods.HttpPost; +import org.apache.hc.client5.http.entity.mime.InputStreamBody; +import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder; +import org.apache.hc.client5.http.ssl.NoopHostnameVerifier; +import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder; +import org.apache.hc.client5.http.ssl.TrustAllStrategy; +import org.apache.hc.core5.http.*; +import org.apache.hc.core5.http.io.entity.BufferedHttpEntity; +import org.apache.hc.core5.http.io.entity.InputStreamEntity; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.ssl.SSLContextBuilder; +import org.apache.hc.client5.http.entity.mime.HttpMultipartMode; +import org.apache.http.Consts; import org.apache.http.cookie.SM; -import org.apache.http.entity.BufferedHttpEntity; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.InputStreamEntity; -import org.apache.http.entity.StringEntity; -import org.apache.http.entity.mime.HttpMultipartMode; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.entity.mime.content.InputStreamBody; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.xml.serialize.OutputFormat; -import org.apache.xml.serialize.XMLSerializer; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.w3c.dom.Document; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService; -import org.xml.sax.SAXException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import java.io.BufferedReader; -import java.io.File; import java.io.IOException; +import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; -import java.io.StringWriter; +import java.io.Reader; import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; +import java.util.ArrayList; import java.util.Base64; import java.util.Enumeration; +import java.util.HashMap; import java.util.List; +import java.util.Map; public class HandlerUtil { @@ -92,71 +97,69 @@ public class HandlerUtil { * @return response as string * @throws IOException IO exception returns if error occurs when executing the httpMethod */ - public static ProxyResponse execute(HttpRequestBase httpRequest) throws IOException { + public static ProxyResponse execute(ClassicHttpRequest httpRequest) throws IOException { + try (CloseableHttpClient client = getHttpClient()) { - HttpResponse response = client.execute(httpRequest); - ProxyResponse proxyResponse = new ProxyResponse(); - - if (response == null) { - log.error("Received null response for http request : " + httpRequest.getMethod() + " " + httpRequest - .getURI().toString()); - proxyResponse.setCode(HandlerConstants.INTERNAL_ERROR_CODE); - proxyResponse.setStatus(ProxyResponse.Status.ERROR); - proxyResponse.setExecutorResponse(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey( - HandlerConstants.INTERNAL_ERROR_CODE)); - return proxyResponse; - } else { - int statusCode = response.getStatusLine().getStatusCode(); - String jsonString = getResponseString(response); + return client.execute(httpRequest, response -> { + final HttpEntity responseEntity = response.getEntity(); + ProxyResponse handlerResponse = new ProxyResponse(); + int statusCode = response.getCode(); + if (responseEntity == null) { + log.error("Received null response for http request : " + httpRequest.getMethod() + " " + httpRequest.getRequestUri()); + handlerResponse.setCode(HandlerConstants.INTERNAL_ERROR_CODE); + handlerResponse.setStatus(ProxyResponse.Status.ERROR); + handlerResponse.setExecutorResponse(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey( + HandlerConstants.INTERNAL_ERROR_CODE)); + return handlerResponse; + } + JsonNode responseData = getResponseDataAsJsonNode(responseEntity); if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) { - proxyResponse.setCode(statusCode); - proxyResponse.setData(jsonString); - proxyResponse.setStatus(ProxyResponse.Status.SUCCESS); - proxyResponse.setExecutorResponse("SUCCESS"); - proxyResponse.setHeaders(response.getAllHeaders()); - return proxyResponse; + handlerResponse.setCode(statusCode); + handlerResponse.setData(responseData); + handlerResponse.setStatus(ProxyResponse.Status.SUCCESS); + handlerResponse.setExecutorResponse("SUCCESS"); + handlerResponse.setHeaders(response.getHeaders()); + return handlerResponse; } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) { - if (isTokenExpired(jsonString)) { - proxyResponse.setCode(statusCode); - proxyResponse.setStatus(ProxyResponse.Status.ERROR); - proxyResponse.setExecutorResponse(HandlerConstants.TOKEN_IS_EXPIRED); + if (isTokenExpired(responseData)) { + handlerResponse.setCode(statusCode); + handlerResponse.setStatus(ProxyResponse.Status.ERROR); + handlerResponse.setExecutorResponse(HandlerConstants.TOKEN_IS_EXPIRED); } else { log.error( "Received " + statusCode + " response for http request : " + httpRequest.getMethod() - + " " + httpRequest.getURI().toString() + ". Error message: " + jsonString); - proxyResponse.setCode(statusCode); - proxyResponse.setData(jsonString); - proxyResponse.setStatus(ProxyResponse.Status.ERROR); - proxyResponse.setExecutorResponse( + + " " + httpRequest.getRequestUri() + ". Error message: " + responseData.textValue()); + handlerResponse.setCode(statusCode); + handlerResponse.setData(responseData); + handlerResponse.setStatus(ProxyResponse.Status.ERROR); + handlerResponse.setExecutorResponse( HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(statusCode)); } - return proxyResponse; + return handlerResponse; } - log.error("Received " + statusCode + - " response for http request : " + httpRequest.getMethod() + " " + httpRequest.getURI() - .toString() + ". Error message: " + jsonString); - proxyResponse.setCode(statusCode); - proxyResponse.setData(jsonString); - proxyResponse.setStatus(ProxyResponse.Status.ERROR); - proxyResponse + log.error("Received " + statusCode + " response for http request : " + httpRequest.getMethod() + + " " + httpRequest.getRequestUri() + ". Error message: " + responseData.textValue()); + handlerResponse.setCode(statusCode); + handlerResponse.setData(responseData); + handlerResponse.setStatus(ProxyResponse.Status.ERROR); + handlerResponse .setExecutorResponse(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(statusCode)); - return proxyResponse; - } + return handlerResponse; + }); } } - public static boolean isTokenExpired(String jsonBody) { - return jsonBody.contains("Access token expired") || jsonBody + public static boolean isTokenExpired(JsonNode jsonBody) { + return jsonBody.textValue().contains("Access token expired") || jsonBody.textValue() .contains("Invalid input. Access token validation failed"); } public static String getMemeType(HttpResponse response) { - String memeType = ""; - Header contentType = response.getEntity().getContentType(); + Header contentType = response.getFirstHeader("Content-Type"); if (contentType != null) { - memeType = contentType.getValue().split(";")[0].trim(); + return contentType.getValue().split(";")[0].trim(); } - return memeType; + return ""; } /*** @@ -266,29 +269,17 @@ public class HandlerUtil { resp.setStatus(proxyResponse.getCode()); resp.setContentType(ContentType.APPLICATION_JSON.getMimeType()); resp.setCharacterEncoding(Consts.UTF_8.name()); - JSONObject response = new JSONObject(); - String responseData = proxyResponse.getData(); + JsonNode responseData = proxyResponse.getData(); - if (!StringUtils.isEmpty(responseData)) { - try { - if (responseData.startsWith("{")) { - JSONObject responseDataJsonObj = new JSONObject(responseData); - response.put("data", responseDataJsonObj); - } else if (responseData.startsWith("[")) { - JSONArray responseDataJsonArr = new JSONArray(responseData); - response.put("data", responseDataJsonArr); - } else { - log.warn("Response data is not valid json string >> " + responseData); - response.put("data", responseData); - } - } catch (JSONException e) { - log.error("Response data is not passable"); - response.put("data", responseData); - } + if (!(responseData == null)) { + ObjectMapper mapper = new ObjectMapper(); + Map newNodeMap = new HashMap<>(); + newNodeMap.put("data", responseData); + responseData = mapper.convertValue(newNodeMap, JsonNode.class); } try (PrintWriter writer = resp.getWriter()) { - writer.write(response.toString()); + writer.write(responseData != null ? responseData.toString() : "{}"); } } @@ -363,7 +354,21 @@ public class HandlerUtil { boolean isIgnoreHostnameVerification = Boolean.parseBoolean(System. getProperty("org.wso2.ignoreHostnameVerification")); if (isIgnoreHostnameVerification) { - return HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build(); + try { + return HttpClients.custom() + .setConnectionManager(PoolingHttpClientConnectionManagerBuilder.create() + .setSSLSocketFactory(SSLConnectionSocketFactoryBuilder.create() + .setSslContext(SSLContextBuilder.create() + .loadTrustMaterial(TrustAllStrategy.INSTANCE) + .build()) + .setHostnameVerifier(NoopHostnameVerifier.INSTANCE) + .build()) + .build()) + .build(); + } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { + log.error("Error Occurred while creating the custom http client", e); + throw new RuntimeException(e); + } } else { return HttpClients.createDefault(); } @@ -414,13 +419,13 @@ public class HandlerUtil { * @throws FileUploadException If unable to parse the incoming request for multipart content extraction. * @throws IOException If error occurred while generating the request body. */ - public static void generateRequestEntity(HttpServletRequest req, HttpEntityEnclosingRequestBase proxyRequest) + public static void generateRequestEntity(HttpServletRequest req, ClassicHttpRequest proxyRequest) throws FileUploadException, IOException { if (ServletFileUpload.isMultipartContent(req)) { ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); List fileItemList = servletFileUpload.parseRequest(req); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); - entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + entityBuilder.setMode(HttpMultipartMode.LEGACY); for (FileItem item : fileItemList) { if (!item.isFormField()) { entityBuilder.addPart(item.getFieldName(), new InputStreamBody(item.getInputStream(), @@ -435,7 +440,7 @@ public class HandlerUtil { if (StringUtils.isNotEmpty(req.getHeader(HttpHeaders.CONTENT_LENGTH)) || StringUtils.isNotEmpty(req.getHeader(HttpHeaders.TRANSFER_ENCODING))) { InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), - Long.parseLong(req.getHeader(HttpHeaders.CONTENT_LENGTH))); + Long.parseLong(req.getHeader(HttpHeaders.CONTENT_LENGTH)), ContentType.parse(req.getContentType())); proxyRequest.setEntity(new BufferedHttpEntity(entity)); } HandlerUtil.copyRequestHeaders(req, proxyRequest, true); @@ -449,12 +454,12 @@ public class HandlerUtil { * @param proxyRequest proxy request instance. * @throws IOException If error occurred while generating the request body. */ - public static void generateChatRequestEntity(HttpServletRequest req, HttpEntityEnclosingRequestBase proxyRequest) + public static void generateChatRequestEntity(HttpServletRequest req, ClassicHttpRequest proxyRequest) throws IOException { if (StringUtils.isNotEmpty(req.getHeader(HttpHeaders.CONTENT_LENGTH)) || StringUtils.isNotEmpty(req.getHeader(HttpHeaders.TRANSFER_ENCODING))) { InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), - Long.parseLong(req.getHeader(HttpHeaders.CONTENT_LENGTH))); + Long.parseLong(req.getHeader(HttpHeaders.CONTENT_LENGTH)), ContentType.parse(req.getContentType())); proxyRequest.setEntity(new BufferedHttpEntity(entity)); } } @@ -465,17 +470,30 @@ public class HandlerUtil { * @param tags - tags which are retrieved by reading app manager configuration * @param username - username provided from login form or admin username * @param password - password provided from login form or admin password + * @param callbackUrl - callback url + * @param supportedGrantTypes - supported grant types * @return {@link StringEntity} of the payload to create the client application */ - public static StringEntity constructAppRegPayload(JsonArray tags, String appName, String username, String password) { - JsonObject jsonObject = new JsonObject(); - jsonObject.addProperty(HandlerConstants.APP_NAME_KEY, appName); - jsonObject.addProperty(HandlerConstants.USERNAME, username); - jsonObject.addProperty(HandlerConstants.PASSWORD, password); - jsonObject.addProperty(HandlerConstants.IS_ALLOWED_TO_ALL_DOMAINS_KEY, "false"); - jsonObject.add(HandlerConstants.TAGS_KEY, tags); - String payload = jsonObject.toString(); - return new StringEntity(payload, ContentType.APPLICATION_JSON); + public static StringEntity constructAppRegPayload(ArrayNode tags, String appName, String username, String password, + String callbackUrl, ArrayList supportedGrantTypes) { + + ObjectMapper objectMapper = new ObjectMapper(); + Map data = new HashMap<>(); + + data.put(HandlerConstants.APP_NAME_KEY, appName); + data.put(HandlerConstants.USERNAME, username); + data.put(HandlerConstants.PASSWORD, password); + data.put(HandlerConstants.IS_ALLOWED_TO_ALL_DOMAINS_KEY, "false"); + data.put(HandlerConstants.TAGS_KEY, tags); + if (callbackUrl != null) { + data.put(HandlerConstants.CALLBACK_URL_KEY, callbackUrl); + } + if (supportedGrantTypes != null) { + data.put(HandlerConstants.GRANT_TYPE_KEY, supportedGrantTypes); + + } + + return new StringEntity(objectMapper.valueToTree(data).toString(), ContentType.APPLICATION_JSON); } /*** @@ -485,9 +503,9 @@ public class HandlerUtil { * @param gatewayUrl - gateway endpoint URL * @param httpSession - current active HttpSession * @param resp - HttpServletResponse - * @return {@link JsonObject} of UI configurations + * @return {@link JsonNode} of UI configurations */ - public static JsonObject getUIConfigAndPersistInSession(String uiConfigUrl, String gatewayUrl, HttpSession httpSession, + public static JsonNode getUIConfigAndPersistInSession(String uiConfigUrl, String gatewayUrl, HttpSession httpSession, HttpServletResponse resp) throws IOException { HttpGet uiConfigEndpoint = new HttpGet(uiConfigUrl); ProxyResponse uiConfigResponse = HandlerUtil.execute(uiConfigEndpoint); @@ -498,39 +516,28 @@ public class HandlerUtil { HandlerUtil.handleError(resp, uiConfigResponse); } - if (uiConfigResponse.getData() == null) { + JsonNode responseData = uiConfigResponse.getData(); + if (responseData == null) { log.error("UI config retrieval is failed, and didn't find UI configuration for App manager."); HandlerUtil.handleError(resp, null); - } - JsonParser jsonParser = new JsonParser(); - - JsonElement uiConfigJsonElement = jsonParser.parse(uiConfigResponse.getData()); - JsonObject uiConfigJsonObject = null; - if (uiConfigJsonElement.isJsonObject()) { - uiConfigJsonObject = uiConfigJsonElement.getAsJsonObject(); - if (uiConfigJsonObject == null) { - log.error( - "Either UI config json element is not an json object or converting rom json element to json object is failed."); - HandlerUtil.handleError(resp, null); - } - httpSession.setAttribute(HandlerConstants.UI_CONFIG_KEY, uiConfigJsonObject); + } else { + httpSession.setAttribute(HandlerConstants.UI_CONFIG_KEY, responseData); httpSession.setAttribute(HandlerConstants.PLATFORM, gatewayUrl); } - return uiConfigJsonObject; + return responseData; } /*** * Converts scopes from JsonArray to string with space separated values. * - * @param scopes - scope Json Array and it is retrieved by reading UI config. + * @param scopes - scope Array and it is retrieved by reading UI config. * @return string value of the defined scopes */ - public static String getScopeString(JsonArray scopes) { - if (scopes != null && scopes.size() > 0) { + public static String getScopeString(JsonNode scopes) { + if (scopes != null && scopes.isArray() && !scopes.isEmpty()) { StringBuilder builder = new StringBuilder(); - for (JsonElement scope : scopes) { - String tmpScope = scope.getAsString() + " "; - builder.append(tmpScope); + for (JsonNode objNode : scopes) { + builder.append(objNode.asText()).append(" "); } return builder.toString(); } else { @@ -538,35 +545,6 @@ public class HandlerUtil { } } - /*** - * Converts xml file into string. - * - * @param xmlFile - xmlFile which needs to be converted into string. - * @return string value of the xml file. - */ - public static String xmlToString(File xmlFile) { - String stringOutput = null; - - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document doc = builder.parse(xmlFile); - OutputFormat format = new OutputFormat(doc); - StringWriter stringWriterOutput = new StringWriter(); - XMLSerializer serial = new XMLSerializer(stringWriterOutput, format); - serial.serialize(doc); - stringOutput = stringWriterOutput.toString(); - } catch (IOException e) { - log.error("Error occurred while sending the response into the socket. ", e); - } catch (ParserConfigurationException e) { - log.error("Error while creating the document builder."); - } catch (SAXException e) { - log.error("Error while parsing xml file.", e); - } - - return stringOutput; - } - /*** * Search a key from a given json string object. * @@ -609,37 +587,30 @@ public class HandlerUtil { * Retry request again after refreshing the access token * * @param req incoming {@link HttpServletRequest} - * @param httpRequest subclass of {@link HttpRequestBase} related to the current request. + * @param httpRequest {@link ClassicHttpRequest} related to the current request. * @return {@link ProxyResponse} if successful and null if failed. * @throws IOException If an error occurs when try to retry the request. */ - public static ProxyResponse retryRequestWithRefreshedToken(HttpServletRequest req, HttpRequestBase httpRequest, - String apiEndpoint, boolean isDefaultAuthToken) throws IOException { - ProxyResponse retryResponse = refreshToken(req, apiEndpoint, isDefaultAuthToken); + public static ProxyResponse retryRequestWithRefreshedToken(HttpServletRequest req, ClassicHttpRequest httpRequest, + String apiEndpoint) throws IOException { + ProxyResponse retryResponse = refreshToken(req, apiEndpoint); if (isResponseSuccessful(retryResponse)) { HttpSession session = req.getSession(false); if (session == null) { log.error("Unauthorized, You are not logged in. Please log in to the portal"); return constructProxyResponseByErrorCode(HttpStatus.SC_UNAUTHORIZED); } - if (!isDefaultAuthToken) { - httpRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); - ProxyResponse proxyResponse = HandlerUtil.execute(httpRequest); - if (proxyResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { - log.error("Error occurred while invoking the API after refreshing the token."); - return proxyResponse; - } + httpRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); + ProxyResponse proxyResponse = HandlerUtil.execute(httpRequest); + if (proxyResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { + log.error("Error occurred while invoking the API after refreshing the token."); return proxyResponse; } + return proxyResponse; } return retryResponse; } - public static ProxyResponse retryRequestWithRefreshedToken(HttpServletRequest req, HttpRequestBase httpRequest, - String apiEndpoint) throws IOException { - return retryRequestWithRefreshedToken(req, httpRequest, apiEndpoint, false); - } - /*** * This method is responsible to get the refresh token * @@ -657,7 +628,6 @@ public class HandlerUtil { if (session == null) { log.error("Couldn't find a session, hence it is required to login and proceed."); tokenResultResponse = constructProxyResponseByErrorCode(HttpStatus.SC_UNAUTHORIZED); -// handleError(resp, HttpStatus.SC_UNAUTHORIZED); return tokenResultResponse; } if (isDefaultAuthToken) { @@ -668,25 +638,17 @@ public class HandlerUtil { tokenResultResponse = getTokenResult(authData, keymanagerUrl); if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { log.error("Error occurred while refreshing access token."); -// HandlerUtil.handleError(resp, tokenResultResponse); return tokenResultResponse; } - JsonParser jsonParser = new JsonParser(); - JsonElement jTokenResult = jsonParser.parse(tokenResultResponse.getData()); - - if (jTokenResult.isJsonObject()) { - if (isDefaultAuthToken) { - setNewDefaultAuthData(constructAuthDataFromTokenResult(jTokenResult, authData), session); - } else { - setNewAuthData(constructAuthDataFromTokenResult(jTokenResult, authData), session); - } + JsonNode tokenResponse = tokenResultResponse.getData(); + if (tokenResponse != null) { + setNewAuthData(constructAuthDataFromTokenResult(tokenResponse, authData), session); return tokenResultResponse; } log.error("Error Occurred in token renewal process."); tokenResultResponse = constructProxyResponseByErrorCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); -// handleError(resp, HttpStatus.SC_INTERNAL_SERVER_ERROR); return tokenResultResponse; } @@ -719,17 +681,17 @@ public class HandlerUtil { session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, newAuthData); } - public static void setNewDefaultAuthData(AuthData newAuthData, HttpSession session) { - authData = newAuthData; - session.setAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY, newAuthData); - } - - public static AuthData constructAuthDataFromTokenResult(JsonElement tokenResult, AuthData authData) { - JsonObject jTokenResultAsJsonObject = tokenResult.getAsJsonObject(); + /** + * Construct {@link AuthData} from token response + * @param tokenResult {@link JsonNode} + * @param authData {@link AuthData} existing auth data values + * @return new {@link AuthData} object + */ + public static AuthData constructAuthDataFromTokenResult(JsonNode tokenResult, AuthData authData) { AuthData newAuthData = new AuthData(); - newAuthData.setAccessToken(jTokenResultAsJsonObject.get("access_token").getAsString()); - newAuthData.setRefreshToken(jTokenResultAsJsonObject.get("refresh_token").getAsString()); - newAuthData.setScope(jTokenResultAsJsonObject.get("scope").getAsString()); + newAuthData.setAccessToken(tokenResult.get("access_token").textValue()); + newAuthData.setRefreshToken(tokenResult.get("refresh_token").textValue()); + newAuthData.setScope(tokenResult.get("scope")); newAuthData.setClientId(authData.getClientId()); newAuthData.setClientSecret(authData.getClientSecret()); newAuthData.setEncodedClientApp(authData.getEncodedClientApp()); @@ -746,7 +708,7 @@ public class HandlerUtil { * This should be set to false when handling multipart requests as Http * client will generate the Content-Type header automatically. */ - public static void copyRequestHeaders(HttpServletRequest req, HttpRequestBase httpRequest, boolean preserveContentType) { + public static void copyRequestHeaders(HttpServletRequest req, ClassicHttpRequest httpRequest, boolean preserveContentType) { Enumeration headerNames = req.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); @@ -772,18 +734,6 @@ public class HandlerUtil { return headerValue; } - public static String getResponseString(HttpResponse response) throws IOException { - try (BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) { - StringBuilder responseBuilder = new StringBuilder(); - String line; - while ((line = rd.readLine()) != null) { - responseBuilder.append(line); - } - return responseBuilder.toString(); - } - } - - public static boolean isPropertyDefined(String property) { return StringUtils.isEmpty(System.getProperty(property)); } @@ -799,4 +749,45 @@ public class HandlerUtil { public static String generateStateToken() { return new BigInteger(130, new SecureRandom()).toString(32); } + + /** + * Get response data and convert data into a json tree + * @param responseEntity Incoming {@link HttpEntity} + * @return {@link JsonNode} consists with response data content + * @throws IOException Throws when IO exception encountered + */ + public static JsonNode getResponseDataAsJsonNode(HttpEntity responseEntity) throws IOException { + JsonFactory jsonFactory = new JsonFactory(); + ObjectMapper objectMapper = new ObjectMapper(jsonFactory); + JsonNode finalNode; + try (InputStream inputStream = responseEntity.getContent()) { + String content = getResponseDataAsString(inputStream); + try { + finalNode = objectMapper.readTree(content); + } catch (JsonProcessingException e) { + ObjectNode objectNode = objectMapper.createObjectNode(); + objectNode.put("message", content); + finalNode = objectMapper.valueToTree(objectNode); + } + } + return finalNode; + } + + /** + * Get response content as a string + * @param inputStream Incoming response content as a stream + * @return String content of the incoming response + * @throws IOException Throws when IO exception encountered + */ + public static String getResponseDataAsString(InputStream inputStream) throws IOException { + char []buffer = new char[8192]; + StringBuilder stringBuilder = new StringBuilder(); + try (Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) { + int charsRead; + while ((charsRead = reader.read(buffer, 0, buffer.length)) > 0) { + stringBuilder.append(buffer, 0, charsRead); + } + } + return stringBuilder.toString(); + } } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/websocket/GrafanaWebSocketClient.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/websocket/GrafanaWebSocketClient.java index 7638e53ab5..630f43c29a 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/websocket/GrafanaWebSocketClient.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/websocket/GrafanaWebSocketClient.java @@ -24,19 +24,18 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.websocket.ClientEndpoint; +import javax.websocket.ClientEndpointConfig; +import javax.websocket.CloseReason; import javax.websocket.ContainerProvider; -import javax.websocket.Session; -import javax.websocket.OnOpen; +import javax.websocket.Endpoint; +import javax.websocket.EndpointConfig; import javax.websocket.OnClose; import javax.websocket.OnError; -import javax.websocket.CloseReason; +import javax.websocket.OnOpen; +import javax.websocket.Session; import javax.websocket.WebSocketContainer; -import java.net.URI; - -import javax.websocket.ClientEndpointConfig; -import javax.websocket.Endpoint; -import javax.websocket.EndpointConfig; import javax.ws.rs.core.HttpHeaders; +import java.net.URI; import java.util.Collections; import java.util.List; import java.util.Map; diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/websocket/GrafanaWebSocketHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/websocket/GrafanaWebSocketHandler.java index a9efaae87a..97e5da899d 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/websocket/GrafanaWebSocketHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/websocket/GrafanaWebSocketHandler.java @@ -25,12 +25,12 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.websocket.CloseReason; -import javax.websocket.server.ServerEndpoint; -import javax.websocket.Session; -import javax.websocket.OnOpen; -import javax.websocket.OnMessage; import javax.websocket.OnClose; import javax.websocket.OnError; +import javax.websocket.OnMessage; +import javax.websocket.OnOpen; +import javax.websocket.Session; +import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/pom.xml b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/pom.xml index e6de5b033c..c0ca459167 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/pom.xml +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/pom.xml @@ -26,18 +26,21 @@ 4.0.0 - io.entgra.device.mgt.core io.entgra.device.mgt.core.webapp.authenticator.framework bundle WSO2 Carbon - Web Application Authenticator Framework Bundle WSO2 Carbon - Web Application Authenticator Framework Bundle - http://wso2.org + https://entgra.io - org.apache.felix - maven-scr-plugin + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + org.apache.felix @@ -55,65 +58,70 @@ io.entgra.device.mgt.core.webapp.authenticator.framework.* - com.nimbusds.jose;version="${nimbus.orbit.version.range}", - com.nimbusds.jose.crypto;version="${nimbus.orbit.version.range}", - com.nimbusds.jwt;version="${nimbus.orbit.version.range}", - javax.xml.bind, - javax.xml.bind.annotation, - javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, - javax.xml.validation, - org.apache.catalina;version="9.0", - org.apache.catalina.connector;version="9.0", - org.apache.catalina.util;version="9.0", - org.apache.commons.logging, - org.apache.coyote;version="9.0", - org.apache.tomcat.util.buf;version="9.0", - org.apache.tomcat.util.http;version="9.0", + com.google.gson;version="[2.9,3)", + com.nimbusds.jose;version="[7.9,8)", + com.nimbusds.jose.crypto;version="[7.9,8)", + com.nimbusds.jwt;version="[7.9,8)", + io.entgra.device.mgt.core.certificate.mgt.core.dto;version="[5.0,6)", + io.entgra.device.mgt.core.certificate.mgt.core.exception;version="[5.0,6)", + io.entgra.device.mgt.core.certificate.mgt.core.scep;version="[5.0,6)", + io.entgra.device.mgt.core.certificate.mgt.core.service;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.otp.mgt.dto;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.permission.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common.spi;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.permission.mgt;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.core.util;version="[5.0,6)", + io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth, + io.entgra.device.mgt.core.webapp.authenticator.framework.authorizer, + io.entgra.device.mgt.core.webapp.authenticator.framework.config, + io.entgra.device.mgt.core.webapp.authenticator.framework.config.impl, + javax.servlet;version="[2.6,3)", + + + javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}", + + javax.xml.stream.*;version="[1.0.1,1.1.0)", + org.apache.axiom.om;version="[1.2,2)", + org.apache.axiom.om.impl.builder;version="[1.2,2)", + org.apache.axiom.om.util;version="[1.2,2)", + org.apache.axiom.soap;version="[1.2,2)", + org.apache.axiom.soap.impl.builder;version="[1.2,2)", + org.apache.axis2;version="[1.6,2)", + org.apache.axis2.client;version="[1.6,2)", + org.apache.axis2.context;version="[1.6,2)", + org.apache.catalina;version="${catalina.version.range}", + org.apache.catalina.connector;version="${catalina.version.range}", + org.apache.commons.codec.binary;version="[1.14,2)", + org.apache.commons.httpclient;version="[3.1,4)", + org.apache.commons.httpclient.params;version="[3.1,4)", + org.apache.commons.lang;version="[2.6,3)", + org.apache.commons.logging;version="[1.2,2)", + org.apache.commons.pool;version="[1.5,2)", + org.apache.commons.pool.impl;version="[1.5,2)", + org.apache.coyote;version="[9.0,10)", + org.apache.tomcat.util.buf;version="[9.0,10)", + org.apache.tomcat.util.http;version="[9.0,10)", org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", + org.owasp.encoder;version="[1.2,2)", org.w3c.dom, - org.wso2.carbon.context, - org.wso2.carbon.core.util, - org.wso2.carbon.identity.base; version="${carbon.identity.imp.pkg.version}", - org.wso2.carbon.identity.core.util; version="${carbon.identity.imp.pkg.version}", - org.wso2.carbon.identity.oauth2.*; - version="${carbon.identity-inbound-auth-oauth.imp.pkg.version}", - org.wso2.carbon.tomcat.ext.valves, - org.wso2.carbon.user.api, - org.wso2.carbon.user.core.service, - org.wso2.carbon.user.core.tenant, - org.wso2.carbon.utils, - org.wso2.carbon.utils.multitenancy, - org.xml.sax, - - javax.servlet, - javax.servlet.http, - javax.xml, - org.apache.axis2.transport.http, - io.entgra.device.mgt.core.certificate.mgt.core.*, - io.entgra.device.mgt.core.device.mgt.core.permission.mgt.*, - io.entgra.device.mgt.core.device.mgt.core.util.*, - io.entgra.device.mgt.core.device.mgt.common.*, - io.entgra.device.mgt.core.device.mgt.common.permission.mgt.*, - org.apache.axis2, - org.apache.axis2.client, - org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}", - org.apache.commons.httpclient, - org.wso2.carbon.core.security, - org.apache.axis2.context, - org.apache.commons.httpclient.params, - org.apache.commons.pool, - org.apache.commons.pool.impl, - org.apache.http.conn, - org.apache.http.impl.conn, - - javax.xml.stream, - org.apache.axiom.*; version="${axiom.osgi.version.range}", - org.wso2.carbon.registry.core.*, - org.wso2.carbon.registry.common.*;version="${carbon.registry.imp.pkg.version.range}", - org.wso2.carbon.registry.indexing.*; version="${carbon.registry.imp.pkg.version.range}", - org.wso2.carbon.base, - org.owasp.encoder + org.wso2.carbon.base;version="[1.0,2)", + org.wso2.carbon.context;version="[4.8,5)", + org.wso2.carbon.core.util;version="[4.8,5)", + org.wso2.carbon.identity.oauth2;version="[6.9,7)", + org.wso2.carbon.identity.oauth2.dto;version="[6.9,7)", + org.wso2.carbon.identity.oauth2.stub;version="[6.9,7)", + org.wso2.carbon.identity.oauth2.stub.dto;version="[6.9,7)", + org.wso2.carbon.registry.core.exceptions;version="[1.0,2)", + org.wso2.carbon.registry.core.service;version="[1.0,2)", + org.wso2.carbon.registry.indexing.service;version="[4.8,5)", + org.wso2.carbon.tomcat.ext.valves;version="[4.8,5)", + org.wso2.carbon.user.api;version="[1.0,2)", + org.wso2.carbon.user.core.service;version="[4.8,5)", + org.wso2.carbon.user.core.tenant;version="[4.8,5)", + org.wso2.carbon.utils;version="[4.8,5)", + org.wso2.carbon.utils.multitenancy;version="[4.8,5)" @@ -161,11 +169,16 @@ - org.wso2.tomcat + org.apache.felix + org.apache.felix.scr.ds-annotations + provided + + + org.wso2.orbit.org.apache.tomcat tomcat - org.wso2.tomcat + org.wso2.orbit.org.apache.tomcat tomcat-servlet-api @@ -254,13 +267,13 @@ commons-codec - com.h2database.wso2 - h2-database-engine + org.wso2.orbit.com.h2database + h2 test org.powermock - powermock-api-mockito + powermock-api-mockito2 test @@ -281,13 +294,16 @@ org.wso2.carbon javax.cache.wso2 - 4.6.3-m5 test org.wso2.carbon.identity.inbound.auth.oauth2 org.wso2.carbon.identity.oauth.stub + + org.wso2.carbon + org.wso2.carbon.base + diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/AuthenticationFrameworkUtil.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/AuthenticationFrameworkUtil.java index 9a1e8819dd..811204b630 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/AuthenticationFrameworkUtil.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/AuthenticationFrameworkUtil.java @@ -17,6 +17,7 @@ */ package io.entgra.device.mgt.core.webapp.authenticator.framework; +import io.entgra.device.mgt.core.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.commons.logging.Log; @@ -28,7 +29,6 @@ import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import io.entgra.device.mgt.core.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/Utils/Utils.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/Utils/Utils.java index 08f27c1a5e..014b2fffed 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/Utils/Utils.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/Utils/Utils.java @@ -18,14 +18,7 @@ package io.entgra.device.mgt.core.webapp.authenticator.framework.Utils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; -import org.wso2.carbon.user.api.TenantManager; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.core.service.RealmService; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationException; import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.WebappAuthenticator; @@ -33,6 +26,13 @@ import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oa import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuthValidationResponse; import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuthValidatorFactory; import io.entgra.device.mgt.core.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.user.api.TenantManager; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.core.service.RealmService; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import java.util.Properties; import java.util.regex.Matcher; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticationValve.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticationValve.java index b5df66b4b4..8b430ba012 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticationValve.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticationValve.java @@ -18,6 +18,9 @@ package io.entgra.device.mgt.core.webapp.authenticator.framework; import com.google.gson.Gson; +import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.WebappAuthenticator; +import io.entgra.device.mgt.core.webapp.authenticator.framework.authorizer.PermissionAuthorizer; +import io.entgra.device.mgt.core.webapp.authenticator.framework.authorizer.WebappTenantAuthorizer; import org.apache.catalina.Context; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; @@ -31,9 +34,6 @@ import org.wso2.carbon.tomcat.ext.valves.CompositeValve; import org.wso2.carbon.user.api.Tenant; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.service.RealmService; -import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.WebappAuthenticator; -import io.entgra.device.mgt.core.webapp.authenticator.framework.authorizer.PermissionAuthorizer; -import io.entgra.device.mgt.core.webapp.authenticator.framework.authorizer.WebappTenantAuthorizer; import javax.servlet.http.HttpServletResponse; import java.net.InetAddress; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticatorFactory.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticatorFactory.java index bacd26902d..6d1e9a3c21 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticatorFactory.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticatorFactory.java @@ -17,9 +17,9 @@ */ package io.entgra.device.mgt.core.webapp.authenticator.framework; -import org.apache.catalina.connector.Request; import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.WebappAuthenticator; import io.entgra.device.mgt.core.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; +import org.apache.catalina.connector.Request; import java.util.Map; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/BSTAuthenticator.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/BSTAuthenticator.java index 3f488df019..9ea23cc7be 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/BSTAuthenticator.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/BSTAuthenticator.java @@ -17,6 +17,12 @@ */ package io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator; +import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationException; +import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; +import io.entgra.device.mgt.core.webapp.authenticator.framework.Utils.Utils; +import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuth2TokenValidator; +import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuthTokenValidationException; +import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuthValidationResponse; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.impl.builder.StAXBuilder; import org.apache.axiom.om.util.StAXUtils; @@ -27,14 +33,6 @@ import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.coyote.InputBuffer; -import org.apache.tomcat.util.buf.ByteChunk; -import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationException; -import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; -import io.entgra.device.mgt.core.webapp.authenticator.framework.Utils.Utils; -import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuth2TokenValidator; -import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuthTokenValidationException; -import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuthValidationResponse; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; @@ -42,7 +40,12 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; -import java.util.*; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Iterator; +import java.util.List; +import java.util.Properties; +import java.util.StringTokenizer; public class BSTAuthenticator implements WebappAuthenticator { @@ -146,30 +149,27 @@ public class BSTAuthenticator implements WebappAuthenticator { private String getBSTHeader(Request request) throws IOException, XMLStreamException { org.apache.coyote.Request coyoteReq = request.getCoyoteRequest(); - InputBuffer buf = coyoteReq.getInputBuffer(); - ByteChunk bc = new ByteChunk(); + String securityHeader = coyoteReq.getHeader("Security"); + + if (securityHeader == null || securityHeader.isEmpty()) { + return null; + } - buf.doRead(bc, coyoteReq); - try (InputStream is = new ByteArrayInputStream(getUTF8Bytes(bc.toString()))) { + // Process the "Security" header value as needed + try (InputStream is = new ByteArrayInputStream(getUTF8Bytes(securityHeader))) { XMLStreamReader reader = StAXUtils.createXMLStreamReader(is); StAXBuilder builder = new StAXSOAPModelBuilder(reader); SOAPEnvelope envelope = (SOAPEnvelope) builder.getDocumentElement(); envelope.build(); SOAPHeader header = envelope.getHeader(); - Iterator headerEls = header.getChildrenWithLocalName("Security"); + Iterator headerEls = header.getChildrenWithLocalName("BinarySecurityToken"); if (!headerEls.hasNext()) { return null; } - OMElement securityHeader = (OMElement) headerEls.next(); - Iterator securityHeaderEls = securityHeader.getChildrenWithLocalName("BinarySecurityToken"); - if (!securityHeaderEls.hasNext()) { - return null; - } - OMElement bstHeader = (OMElement) securityHeaderEls.next(); + OMElement bstHeader = (OMElement) headerEls.next(); bstHeader.build(); return bstHeader.getText(); } } - } diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java index 3478dd2dba..11395eef60 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java @@ -17,6 +17,11 @@ */ package io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator; +import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationException; +import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; +import io.entgra.device.mgt.core.webapp.authenticator.framework.Constants; +import io.entgra.device.mgt.core.webapp.authenticator.framework.Utils.Utils; +import io.entgra.device.mgt.core.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.commons.logging.Log; @@ -26,11 +31,6 @@ import org.apache.tomcat.util.buf.MessageBytes; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationException; -import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; -import io.entgra.device.mgt.core.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; -import io.entgra.device.mgt.core.webapp.authenticator.framework.Constants; -import io.entgra.device.mgt.core.webapp.authenticator.framework.Utils.Utils; import java.nio.charset.Charset; import java.util.Base64; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java index e4aad4b517..cb9bf50215 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java @@ -18,10 +18,6 @@ package io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator; -import org.apache.catalina.connector.Request; -import org.apache.catalina.connector.Response; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreException; import io.entgra.device.mgt.core.certificate.mgt.core.scep.SCEPException; @@ -32,8 +28,12 @@ import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationException; import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; -import io.entgra.device.mgt.core.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; import io.entgra.device.mgt.core.webapp.authenticator.framework.Utils.Utils; +import io.entgra.device.mgt.core.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; +import org.apache.catalina.connector.Request; +import org.apache.catalina.connector.Response; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.security.cert.X509Certificate; import java.util.Properties; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/JWTAuthenticator.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/JWTAuthenticator.java index 6759980b29..165a064ac4 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/JWTAuthenticator.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/JWTAuthenticator.java @@ -21,6 +21,8 @@ package io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator; import com.nimbusds.jose.JWSVerifier; import com.nimbusds.jose.crypto.RSASSAVerifier; import com.nimbusds.jwt.SignedJWT; +import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; +import io.entgra.device.mgt.core.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.commons.logging.Log; @@ -35,19 +37,13 @@ import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; -import io.entgra.device.mgt.core.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; import java.io.FileInputStream; import java.security.KeyStore; import java.security.PublicKey; import java.security.interfaces.RSAPublicKey; import java.text.ParseException; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Properties; -import java.util.StringTokenizer; +import java.util.*; /** * This authenticator authenticates HTTP requests using JWT header. diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java index 4365d0d30e..9678bff1eb 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java @@ -17,11 +17,6 @@ */ package io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator; -import org.apache.catalina.connector.Response; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.tomcat.util.buf.ByteChunk; -import org.apache.tomcat.util.buf.MessageBytes; import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationException; import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; import io.entgra.device.mgt.core.webapp.authenticator.framework.Constants; @@ -29,6 +24,11 @@ import io.entgra.device.mgt.core.webapp.authenticator.framework.Utils.Utils; import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuth2TokenValidator; import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuthTokenValidationException; import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuthValidationResponse; +import org.apache.catalina.connector.Response; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.tomcat.util.buf.ByteChunk; +import org.apache.tomcat.util.buf.MessageBytes; import java.util.Properties; import java.util.StringTokenizer; @@ -74,7 +74,7 @@ public class OAuthAuthenticator implements WebappAuthenticator { } try { String bearerToken = getBearerToken(request); - bearerToken = bearerToken.substring(bearerToken.indexOf("_")+1); +// bearerToken = bearerToken.substring(bearerToken.indexOf("_")+1); String resource = requestUri + ":" + requestMethod; OAuthValidationResponse oAuthValidationResponse = this.tokenValidator.validateToken(bearerToken, resource); authenticationInfo = Utils.setAuthenticationInfo(oAuthValidationResponse, authenticationInfo); diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OneTimeTokenAuthenticator.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OneTimeTokenAuthenticator.java index 6021f2ad1d..29392b63f5 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OneTimeTokenAuthenticator.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OneTimeTokenAuthenticator.java @@ -17,15 +17,15 @@ */ package io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator; -import org.apache.catalina.connector.Response; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.otp.mgt.dto.OneTimePinDTO; import io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService; import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; import io.entgra.device.mgt.core.webapp.authenticator.framework.Constants; import io.entgra.device.mgt.core.webapp.authenticator.framework.Utils.Utils; import io.entgra.device.mgt.core.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; +import org.apache.catalina.connector.Response; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.util.Properties; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/WebappAuthenticator.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/WebappAuthenticator.java index 49eea111d8..b21a643bb8 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/WebappAuthenticator.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/WebappAuthenticator.java @@ -17,9 +17,9 @@ */ package io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator; +import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; -import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; import java.util.Properties; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/oauth/impl/LocalOAuthValidator.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/oauth/impl/LocalOAuthValidator.java index d2d226aacc..0e155dc776 100755 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/oauth/impl/LocalOAuthValidator.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/oauth/impl/LocalOAuthValidator.java @@ -17,15 +17,15 @@ */ package io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.impl; -import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO; -import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import io.entgra.device.mgt.core.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuth2TokenValidator; import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuthConstants; import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuthTokenValidationException; import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuthValidationResponse; +import io.entgra.device.mgt.core.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; +import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO; +import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO; +import org.wso2.carbon.utils.multitenancy.MultitenantConstants; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; /** * Handles the OAuth2 token validation from the same server using OSGi services. diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java index 9fc873b522..2df0ae88d2 100755 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java @@ -17,6 +17,10 @@ */ package io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.impl; +import io.entgra.device.mgt.core.webapp.authenticator.framework.Utils.OAuthTokenValidationStubFactory; +import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuth2TokenValidator; +import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuthTokenValidationException; +import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuthValidationResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.pool.impl.GenericObjectPool; @@ -26,10 +30,6 @@ import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_ import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_TokenValidationContextParam; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import io.entgra.device.mgt.core.webapp.authenticator.framework.Utils.OAuthTokenValidationStubFactory; -import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuth2TokenValidator; -import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuthTokenValidationException; -import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuthValidationResponse; import java.rmi.RemoteException; import java.util.Properties; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java index aed1ecf836..c9bf8974a7 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java @@ -17,9 +17,6 @@ */ package io.entgra.device.mgt.core.webapp.authenticator.framework.authorizer; -import org.apache.catalina.connector.Request; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.Permission; import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException; import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagerService; @@ -28,6 +25,9 @@ import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationEx import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationFrameworkUtil; import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.WebappAuthenticator; +import org.apache.catalina.connector.Request; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.util.ArrayList; import java.util.List; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authorizer/WebappTenantAuthorizer.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authorizer/WebappTenantAuthorizer.java index 513c5bb7e3..2091efb2fd 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authorizer/WebappTenantAuthorizer.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authorizer/WebappTenantAuthorizer.java @@ -18,9 +18,9 @@ package io.entgra.device.mgt.core.webapp.authenticator.framework.authorizer; -import org.apache.catalina.connector.Request; import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.WebappAuthenticator; +import org.apache.catalina.connector.Request; /** * This class represents the methods that are used to authorize requests based on the tenant subscription. diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/config/WebappAuthenticatorConfig.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/config/WebappAuthenticatorConfig.java index d4d6b5229e..48cd0a2774 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/config/WebappAuthenticatorConfig.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/config/WebappAuthenticatorConfig.java @@ -17,12 +17,12 @@ */ package io.entgra.device.mgt.core.webapp.authenticator.framework.config; +import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationFrameworkUtil; +import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticatorFrameworkException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.wso2.carbon.utils.CarbonUtils; -import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationFrameworkUtil; -import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticatorFrameworkException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/internal/AuthenticatorFrameworkDataHolder.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/internal/AuthenticatorFrameworkDataHolder.java index aa83cd5008..5ae093a6e4 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/internal/AuthenticatorFrameworkDataHolder.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/internal/AuthenticatorFrameworkDataHolder.java @@ -20,11 +20,11 @@ package io.entgra.device.mgt.core.webapp.authenticator.framework.internal; import io.entgra.device.mgt.core.certificate.mgt.core.scep.SCEPManager; import io.entgra.device.mgt.core.certificate.mgt.core.service.CertificateManagementService; import io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService; +import io.entgra.device.mgt.core.webapp.authenticator.framework.WebappAuthenticatorRepository; import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; import org.wso2.carbon.registry.core.service.TenantRegistryLoader; import org.wso2.carbon.registry.indexing.service.TenantIndexingLoader; import org.wso2.carbon.user.core.service.RealmService; -import io.entgra.device.mgt.core.webapp.authenticator.framework.WebappAuthenticatorRepository; public class AuthenticatorFrameworkDataHolder { diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java index 336de8fdbc..ab9a0988f4 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java @@ -18,19 +18,9 @@ package io.entgra.device.mgt.core.webapp.authenticator.framework.internal; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.framework.BundleContext; -import org.osgi.service.component.ComponentContext; import io.entgra.device.mgt.core.certificate.mgt.core.scep.SCEPManager; import io.entgra.device.mgt.core.certificate.mgt.core.service.CertificateManagementService; import io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService; -import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; -import org.wso2.carbon.registry.core.service.TenantRegistryLoader; -import org.wso2.carbon.registry.indexing.service.TenantIndexingLoader; -import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve; -import org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer; -import org.wso2.carbon.user.core.service.RealmService; import io.entgra.device.mgt.core.webapp.authenticator.framework.WebappAuthenticationValve; import io.entgra.device.mgt.core.webapp.authenticator.framework.WebappAuthenticatorRepository; import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.WebappAuthenticator; @@ -38,60 +28,30 @@ import io.entgra.device.mgt.core.webapp.authenticator.framework.config.Authentic import io.entgra.device.mgt.core.webapp.authenticator.framework.config.AuthenticatorConfigService; import io.entgra.device.mgt.core.webapp.authenticator.framework.config.WebappAuthenticatorConfig; import io.entgra.device.mgt.core.webapp.authenticator.framework.config.impl.AuthenticatorConfigServiceImpl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.framework.BundleContext; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; +import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; +import org.wso2.carbon.registry.core.service.TenantRegistryLoader; +import org.wso2.carbon.registry.indexing.service.TenantIndexingLoader; +import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve; +import org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer; +import org.wso2.carbon.user.core.service.RealmService; import java.util.ArrayList; import java.util.List; import java.util.Properties; -/** - * @scr.component name="org.wso2.carbon.webapp.authenticator" immediate="true" - * @scr.reference name="user.realmservice.default" - * interface="org.wso2.carbon.user.core.service.RealmService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRealmService" - * unbind="unsetRealmService" - * @scr.reference name="org.wso2.carbon.certificate.mgt" - * interface="io.entgra.device.mgt.core.certificate.mgt.core.service.CertificateManagementService" - * policy="dynamic" - * cardinality="1..n" - * bind="setCertificateManagementService" - * unbind="unsetCertificateManagementService" - * @scr.reference name="io.entgra.device.mgt.core.certificate.mgt.core.scep" - * interface="io.entgra.device.mgt.core.certificate.mgt.core.scep.SCEPManager" - * policy="dynamic" - * cardinality="1..n" - * bind="setSCEPManagementService" - * unbind="unsetSCEPManagementService" - * @scr.reference name="identity.oauth2.validation.service" - * interface="org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService" - * cardinality="1..1" - * policy="dynamic" - * bind="setOAuth2ValidationService" - * unbind="unsetOAuth2ValidationService" - * @scr.reference name="tenant.indexloader" - * interface="org.wso2.carbon.registry.indexing.service.TenantIndexingLoader" - * cardinality="1..1" - * policy="dynamic" - * bind="setTenantIndexLoader" - * unbind="unsetTenantIndexLoader" - * @scr.reference name="tenant.registryloader" - * interface="org.wso2.carbon.registry.core.service.TenantRegistryLoader" - * cardinality="1..1" policy="dynamic" - * bind="setTenantRegistryLoader" - * unbind="unsetTenantRegistryLoader" - * @scr.reference name="org.wso2.carbon.device.manager" - * interface="io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService" - * cardinality="1..1" - * policy="dynamic" - * bind="setOTPManagementService" - * unbind="unsetOTPManagementService" - */ - +@Component( + name = "io.entgra.device.mgt.core.webapp.authenticator.framework.internal.WebappAuthenticatorFrameworkServiceComponent", + immediate = true) public class WebappAuthenticatorFrameworkServiceComponent { private static final Log log = LogFactory.getLog(WebappAuthenticatorFrameworkServiceComponent.class); @SuppressWarnings("unused") + @Activate protected void activate(ComponentContext componentContext) { if (log.isDebugEnabled()) { log.debug("Starting Web Application Authenticator Framework Bundle"); @@ -134,10 +94,17 @@ public class WebappAuthenticatorFrameworkServiceComponent { } @SuppressWarnings("unused") + @Deactivate protected void deactivate(ComponentContext componentContext) { //do nothing } + @Reference( + name = "realm.service", + service = org.wso2.carbon.user.core.service.RealmService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetRealmService") protected void setRealmService(RealmService realmService) { if (log.isDebugEnabled()) { log.debug("RealmService acquired"); @@ -149,6 +116,12 @@ public class WebappAuthenticatorFrameworkServiceComponent { AuthenticatorFrameworkDataHolder.getInstance().setRealmService(null); } + @Reference( + name = "certificate.mgt.service", + service = io.entgra.device.mgt.core.certificate.mgt.core.service.CertificateManagementService.class, + cardinality = ReferenceCardinality.MULTIPLE, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetCertificateManagementService") protected void setCertificateManagementService(CertificateManagementService certificateManagementService) { if (log.isDebugEnabled()) { log.debug("Setting certificate management service"); @@ -164,6 +137,12 @@ public class WebappAuthenticatorFrameworkServiceComponent { AuthenticatorFrameworkDataHolder.getInstance().setCertificateManagementService(null); } + @Reference( + name = "scep.mgr", + service = io.entgra.device.mgt.core.certificate.mgt.core.scep.SCEPManager.class, + cardinality = ReferenceCardinality.MULTIPLE, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetSCEPManagementService") protected void setSCEPManagementService(SCEPManager scepManager) { if (log.isDebugEnabled()) { log.debug("Setting SCEP management service"); @@ -184,6 +163,12 @@ public class WebappAuthenticatorFrameworkServiceComponent { * * @param tokenValidationService An instance of OAuth2TokenValidationService */ + @Reference( + name = "oauth2.token.validation.service", + service = org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetOAuth2ValidationService") protected void setOAuth2ValidationService(OAuth2TokenValidationService tokenValidationService) { if (log.isDebugEnabled()) { log.debug("Setting OAuth2TokenValidationService Service"); @@ -203,6 +188,12 @@ public class WebappAuthenticatorFrameworkServiceComponent { AuthenticatorFrameworkDataHolder.getInstance().setOAuth2TokenValidationService(null); } + @Reference( + name = "tenant.index.loader", + service = org.wso2.carbon.registry.indexing.service.TenantIndexingLoader.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetTenantIndexLoader") protected void setTenantIndexLoader(TenantIndexingLoader tenantIndexLoader) { AuthenticatorFrameworkDataHolder.getInstance().setTenantIndexingLoader(tenantIndexLoader); } @@ -211,6 +202,12 @@ public class WebappAuthenticatorFrameworkServiceComponent { AuthenticatorFrameworkDataHolder.getInstance().setTenantIndexingLoader(null); } + @Reference( + name = "tenant.registry.loader", + service = org.wso2.carbon.registry.core.service.TenantRegistryLoader.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetTenantRegistryLoader") protected void setTenantRegistryLoader(TenantRegistryLoader tenantRegistryLoader) { AuthenticatorFrameworkDataHolder.getInstance().setTenantRegistryLoader(tenantRegistryLoader); } @@ -219,6 +216,12 @@ public class WebappAuthenticatorFrameworkServiceComponent { AuthenticatorFrameworkDataHolder.getInstance().setTenantRegistryLoader(null); } + @Reference( + name = "otp.mgt.service", + service = io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetOTPManagementService") protected void setOTPManagementService(OTPManagementService otpManagementService) { if (log.isDebugEnabled()) { log.debug("Setting OTP Management OSGI Service"); diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/BaseWebAppAuthenticatorFrameworkTest.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/BaseWebAppAuthenticatorFrameworkTest.java index 08814c7446..5cbc878fb9 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/BaseWebAppAuthenticatorFrameworkTest.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/BaseWebAppAuthenticatorFrameworkTest.java @@ -19,12 +19,15 @@ package io.entgra.device.mgt.core.webapp.authenticator.framework; +import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; +import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionUtils; +import io.entgra.device.mgt.core.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; +import io.entgra.device.mgt.core.webapp.authenticator.framework.util.TestTenantIndexingLoader; +import io.entgra.device.mgt.core.webapp.authenticator.framework.util.TestTenantRegistryLoader; import org.testng.annotations.BeforeSuite; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.core.internal.CarbonCoreDataHolder; -import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; -import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionUtils; import org.wso2.carbon.registry.core.config.RegistryContext; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.internal.RegistryDataHolder; @@ -35,9 +38,6 @@ import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; -import io.entgra.device.mgt.core.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; -import io.entgra.device.mgt.core.webapp.authenticator.framework.util.TestTenantIndexingLoader; -import io.entgra.device.mgt.core.webapp.authenticator.framework.util.TestTenantRegistryLoader; import java.io.File; import java.io.InputStream; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticationValveTest.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticationValveTest.java index 0c89fe4ecb..7da4adc9ec 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticationValveTest.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticationValveTest.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.webapp.authenticator.framework; +import io.entgra.device.mgt.core.webapp.authenticator.framework.util.TestRequest; import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.catalina.connector.Request; @@ -30,7 +31,6 @@ import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.tomcat.ext.valves.CompositeValve; -import io.entgra.device.mgt.core.webapp.authenticator.framework.util.TestRequest; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.Field; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticatorConfigTest.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticatorConfigTest.java index cba25ea90e..fc7f94c839 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticatorConfigTest.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticatorConfigTest.java @@ -17,16 +17,15 @@ */ package io.entgra.device.mgt.core.webapp.authenticator.framework; -import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticatorFrameworkException; +import io.entgra.device.mgt.core.webapp.authenticator.framework.config.AuthenticatorConfig; +import io.entgra.device.mgt.core.webapp.authenticator.framework.config.AuthenticatorConfigService; +import io.entgra.device.mgt.core.webapp.authenticator.framework.config.WebappAuthenticatorConfig; +import io.entgra.device.mgt.core.webapp.authenticator.framework.config.impl.AuthenticatorConfigServiceImpl; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.utils.ServerConstants; -import io.entgra.device.mgt.core.webapp.authenticator.framework.config.AuthenticatorConfig; -import io.entgra.device.mgt.core.webapp.authenticator.framework.config.AuthenticatorConfigService; -import io.entgra.device.mgt.core.webapp.authenticator.framework.config.WebappAuthenticatorConfig; -import io.entgra.device.mgt.core.webapp.authenticator.framework.config.impl.AuthenticatorConfigServiceImpl; import java.util.List; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticatorFrameworkUtilTest.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticatorFrameworkUtilTest.java index 34319eeee7..47d7e59bab 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticatorFrameworkUtilTest.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticatorFrameworkUtilTest.java @@ -17,6 +17,7 @@ */ package io.entgra.device.mgt.core.webapp.authenticator.framework; +import io.entgra.device.mgt.core.webapp.authenticator.framework.Utils.OAuthTokenValidationStubFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.pool.ObjectPool; @@ -24,7 +25,6 @@ import org.apache.commons.pool.impl.GenericObjectPool; import org.testng.Assert; import org.testng.annotations.Test; import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; -import io.entgra.device.mgt.core.webapp.authenticator.framework.Utils.OAuthTokenValidationStubFactory; import java.util.Properties; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticatorRepositoryTest.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticatorRepositoryTest.java index 48cb70829d..ccd3c70c2a 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticatorRepositoryTest.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/WebappAuthenticatorRepositoryTest.java @@ -17,12 +17,11 @@ */ package io.entgra.device.mgt.core.webapp.authenticator.framework; -import io.entgra.device.mgt.core.webapp.authenticator.framework.WebappAuthenticatorRepository; -import org.testng.Assert; -import org.testng.annotations.Test; import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.WebappAuthenticator; import io.entgra.device.mgt.core.webapp.authenticator.framework.util.MalformedAuthenticator; import io.entgra.device.mgt.core.webapp.authenticator.framework.util.TestWebappAuthenticator; +import org.testng.Assert; +import org.testng.annotations.Test; public class WebappAuthenticatorRepositoryTest { diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/BSTAuthenticatorTest.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/BSTAuthenticatorTest.java index 667391d308..d22ad085be 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/BSTAuthenticatorTest.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/BSTAuthenticatorTest.java @@ -18,6 +18,10 @@ package io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator; +import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; +import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuth2TokenValidator; +import io.entgra.device.mgt.core.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; +import io.entgra.device.mgt.core.webapp.authenticator.framework.util.TestInputBuffer; import org.apache.catalina.Context; import org.apache.catalina.connector.Request; import org.apache.catalina.core.StandardContext; @@ -32,10 +36,6 @@ import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; import org.wso2.carbon.identity.oauth2.dto.OAuth2ClientApplicationDTO; import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO; -import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; -import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.OAuth2TokenValidator; -import io.entgra.device.mgt.core.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; -import io.entgra.device.mgt.core.webapp.authenticator.framework.util.TestInputBuffer; import java.io.File; import java.io.IOException; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/BasicAuthAuthenticatorTest.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/BasicAuthAuthenticatorTest.java index 94033b74e2..4254d83fc4 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/BasicAuthAuthenticatorTest.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/BasicAuthAuthenticatorTest.java @@ -18,6 +18,8 @@ package io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator; +import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; +import io.entgra.device.mgt.core.webapp.authenticator.framework.BaseWebAppAuthenticatorFrameworkTest; import org.apache.catalina.Context; import org.apache.catalina.connector.Request; import org.apache.catalina.core.StandardContext; @@ -26,11 +28,8 @@ import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.MimeHeaders; import org.testng.Assert; import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; -import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; -import io.entgra.device.mgt.core.webapp.authenticator.framework.BaseWebAppAuthenticatorFrameworkTest; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/CertificateAuthenticatorTest.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/CertificateAuthenticatorTest.java index bcc88b8943..9784ba61d1 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/CertificateAuthenticatorTest.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/CertificateAuthenticatorTest.java @@ -18,22 +18,6 @@ package io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator; -import org.apache.catalina.Context; -import org.apache.catalina.connector.Request; -import org.apache.catalina.core.StandardContext; -import org.apache.tomcat.util.buf.MessageBytes; -import org.apache.tomcat.util.http.MimeHeaders; -import org.bouncycastle.cert.jcajce.JcaCertStore; -import org.bouncycastle.cms.CMSAbsentContent; -import org.bouncycastle.cms.CMSException; -import org.bouncycastle.cms.CMSSignedData; -import org.bouncycastle.cms.CMSSignedDataGenerator; -import org.h2.jdbcx.JdbcDataSource; -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.base.MultitenantConstants; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreException; import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; @@ -45,12 +29,28 @@ import io.entgra.device.mgt.core.certificate.mgt.core.scep.TenantedDeviceWrapper import io.entgra.device.mgt.core.certificate.mgt.core.service.CertificateManagementService; import io.entgra.device.mgt.core.certificate.mgt.core.service.CertificateManagementServiceImpl; import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; import io.entgra.device.mgt.core.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; import io.entgra.device.mgt.core.webapp.authenticator.framework.util.TestCertificateGenerator; +import org.apache.catalina.Context; +import org.apache.catalina.connector.Request; +import org.apache.catalina.core.StandardContext; +import org.apache.tomcat.util.buf.MessageBytes; +import org.apache.tomcat.util.http.MimeHeaders; +import org.bouncycastle.cert.jcajce.JcaCertStore; +import org.bouncycastle.cms.CMSAbsentContent; +import org.bouncycastle.cms.CMSException; +import org.bouncycastle.cms.CMSSignedData; +import org.bouncycastle.cms.CMSSignedDataGenerator; +import org.h2.jdbcx.JdbcDataSource; +import org.mockito.Mockito; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.base.MultitenantConstants; import javax.sql.DataSource; import java.io.File; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/JWTAuthenticatorTest.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/JWTAuthenticatorTest.java index 4ce617659e..35d434bc57 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/JWTAuthenticatorTest.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/JWTAuthenticatorTest.java @@ -18,6 +18,10 @@ package io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator; +import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.JWTConfig; +import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; +import io.entgra.device.mgt.core.identity.jwt.client.extension.util.JWTClientUtil; +import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; import org.apache.catalina.connector.Request; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.MimeHeaders; @@ -25,10 +29,6 @@ import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.base.MultitenantConstants; -import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.JWTConfig; -import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; -import io.entgra.device.mgt.core.identity.jwt.client.extension.util.JWTClientUtil; -import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; import java.io.File; import java.io.FileInputStream; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OauthAuthenticatorTest.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OauthAuthenticatorTest.java index af9fb47938..e2285145d0 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OauthAuthenticatorTest.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OauthAuthenticatorTest.java @@ -18,6 +18,9 @@ package io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator; +import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; +import io.entgra.device.mgt.core.webapp.authenticator.framework.BaseWebAppAuthenticatorFrameworkTest; +import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.impl.RemoteOAuthValidator; import org.apache.catalina.connector.Request; import org.apache.commons.pool.impl.GenericObjectPool; import org.apache.tomcat.util.buf.MessageBytes; @@ -26,13 +29,9 @@ import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import org.wso2.carbon.core.security.AuthenticatorsConfiguration; import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2ClientApplicationDTO; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO; -import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; -import io.entgra.device.mgt.core.webapp.authenticator.framework.BaseWebAppAuthenticatorFrameworkTest; -import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.oauth.impl.RemoteOAuthValidator; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/util/MalformedAuthenticator.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/util/MalformedAuthenticator.java index 2bbe24e3b1..f287fa766e 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/util/MalformedAuthenticator.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/util/MalformedAuthenticator.java @@ -17,10 +17,10 @@ */ package io.entgra.device.mgt.core.webapp.authenticator.framework.util; -import org.apache.catalina.connector.Request; -import org.apache.catalina.connector.Response; import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.WebappAuthenticator; +import org.apache.catalina.connector.Request; +import org.apache.catalina.connector.Response; import java.util.Properties; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/util/TestCertificateGenerator.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/util/TestCertificateGenerator.java index 7363a4403f..f578580e8e 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/util/TestCertificateGenerator.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/util/TestCertificateGenerator.java @@ -18,6 +18,11 @@ package io.entgra.device.mgt.core.webapp.authenticator.framework.util; +import io.entgra.device.mgt.core.certificate.mgt.core.bean.Certificate; +import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreException; +import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; +import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagementConstants; +import io.entgra.device.mgt.core.certificate.mgt.core.util.CommonUtil; import org.bouncycastle.cert.X509v3CertificateBuilder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; @@ -25,23 +30,11 @@ import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; -import io.entgra.device.mgt.core.certificate.mgt.core.bean.Certificate; -import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreException; -import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; -import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagementConstants; -import io.entgra.device.mgt.core.certificate.mgt.core.util.CommonUtil; import org.wso2.carbon.context.PrivilegedCarbonContext; import javax.security.auth.x500.X500Principal; import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.SecureRandom; -import java.security.Security; -import java.security.SignatureException; +import java.security.*; import java.security.cert.CertificateException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateNotYetValidException; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/util/TestWebappAuthenticator.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/util/TestWebappAuthenticator.java index 6ef378b499..39315bb46d 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/util/TestWebappAuthenticator.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/java/io/entgra/device/mgt/core/webapp/authenticator/framework/util/TestWebappAuthenticator.java @@ -17,10 +17,10 @@ */ package io.entgra.device.mgt.core.webapp.authenticator.framework.util; -import org.apache.catalina.connector.Request; -import org.apache.catalina.connector.Response; import io.entgra.device.mgt.core.webapp.authenticator.framework.AuthenticationInfo; import io.entgra.device.mgt.core.webapp.authenticator.framework.authenticator.WebappAuthenticator; +import org.apache.catalina.connector.Request; +import org.apache.catalina.connector.Response; import java.util.Properties; diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/resources/user-test/user-mgt-registry-test.xml b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/resources/user-test/user-mgt-registry-test.xml index 1ced8bb1f1..4d53df601c 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/resources/user-test/user-mgt-registry-test.xml +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/test/resources/user-test/user-mgt-registry-test.xml @@ -27,7 +27,7 @@ everyone false 500 - jdbc:h2:target/databasetest/CARBON_TEST + jdbc:h2:./target/databasetest/CARBON_TEST org.h2.Driver 50 60000 diff --git a/components/webapp-authenticator-framework/pom.xml b/components/webapp-authenticator-framework/pom.xml index beddb000d8..3fd0427bb6 100644 --- a/components/webapp-authenticator-framework/pom.xml +++ b/components/webapp-authenticator-framework/pom.xml @@ -31,29 +31,10 @@ webapp-authenticator-framework pom WSO2 Carbon - Webapp Authenticator Framework - http://wso2.org + https://entgra.io io.entgra.device.mgt.core.webapp.authenticator.framework - - - - - org.apache.felix - maven-scr-plugin - 1.7.2 - - - generate-scr-scrdescriptor - - scr - - - - - - - diff --git a/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.server.feature/pom.xml b/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.server.feature/pom.xml index 31f79d9390..668d4489ea 100644 --- a/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.server.feature/pom.xml +++ b/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.server.feature/pom.xml @@ -60,8 +60,8 @@ ${cxf.version} - com.h2database.wso2 - h2-database-engine + org.wso2.orbit.com.h2database + h2 @@ -69,7 +69,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension.feature/pom.xml b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension.feature/pom.xml index 7aacadb4f7..49792aa682 100644 --- a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension.feature/pom.xml +++ b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension.feature/pom.xml @@ -41,7 +41,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.feature/pom.xml b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.feature/pom.xml index 051a90fe56..e376ed1fb7 100644 --- a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.feature/pom.xml +++ b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.feature/pom.xml @@ -29,7 +29,7 @@ io.entgra.device.mgt.core.apimgt.application.extension.feature pom WSO2 Carbon - API Management Application Extension Feature - http://wso2.org + https://entgra.io This feature contains an implementation of a api application registration, which takes care of subscription and generating keys. @@ -45,7 +45,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.feature/pom.xml b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.feature/pom.xml index 4012b4f0ff..a4cc71f07e 100644 --- a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.feature/pom.xml +++ b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.feature/pom.xml @@ -29,7 +29,7 @@ io.entgra.device.mgt.core.apimgt.keymgt.extension.feature pom WSO2 Carbon - Api Key Mgt Extensions Feature - http://wso2.org + https://entgra.io This feature contains apimgt related key management extensions @@ -44,7 +44,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher.feature/pom.xml b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher.feature/pom.xml index 1000bc6860..09b90bc4ae 100644 --- a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher.feature/pom.xml +++ b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher.feature/pom.xml @@ -29,7 +29,7 @@ io.entgra.device.mgt.core.apimgt.webapp.publisher.feature pom WSO2 Carbon - API Management Webapp Publisher Feature - http://wso2.org + https://entgra.io This feature contains an implementation of a Tomcat lifecycle listener, which takes care of publishing JAX-RS web applications as 'Managed APIs' @@ -44,7 +44,7 @@ io.entgra.device.mgt.core.apimgt.annotations - org.wso2.orbit.org.scannotation + io.entgra.org.scannotation scannotation @@ -57,7 +57,6 @@ maven-resources-plugin - 2.6 copy-resources @@ -138,7 +137,7 @@ io.entgra.device.mgt.core:io.entgra.device.mgt.core.apimgt.annotations:${io.entgra.device.mgt.core.version} - org.wso2.orbit.org.scannotation:scannotation:${scannotation.version} + io.entgra.org.scannotation:scannotation:${scannotation.version} io.swagger:swagger-annotations:${swagger.version} diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/pom.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/pom.xml deleted file mode 100644 index 1f1335f94c..0000000000 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/pom.xml +++ /dev/null @@ -1,105 +0,0 @@ - - - - - - - io.entgra.device.mgt.core - apimgt-extensions-feature - 5.0.0-SNAPSHOT - ../pom.xml - - - 4.0.0 - org.wso2.carbon.apimgt.handler.server.feature - pom - WSO2 Carbon - Device Management - APIM handler Server Feature - http://wso2.org - This feature contains the handler for the api authentications - - - - - io.entgra.device.mgt.core - org.wso2.carbon.apimgt.handlers - - - - - - - maven-resources-plugin - 2.6 - - - copy-resources - generate-resources - - copy-resources - - - src/main/resources - - - resources - - build.properties - p2.inf - - - - - - - - - org.wso2.maven - carbon-p2-plugin - ${carbon.p2.plugin.version} - - - p2-feature-generation - package - - p2-feature-gen - - - org.wso2.carbon.apimgt.handler.server - ../../../features/etc/feature.properties - - - org.wso2.carbon.p2.category.type:server - org.eclipse.equinox.p2.type.group:false - - - - - io.entgra.device.mgt.core:org.wso2.carbon.apimgt.handlers:${io.entgra.device.mgt.core.version} - - - - - - - - - - - - diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/src/main/resources/build.properties b/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/src/main/resources/build.properties deleted file mode 100644 index 89aee3ff76..0000000000 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/src/main/resources/build.properties +++ /dev/null @@ -1,19 +0,0 @@ -# -# Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. -# -# Entgra (Pvt) Ltd. licenses this file to you 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. -# - -custom = true diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/src/main/resources/conf/iot-api-config.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/src/main/resources/conf/iot-api-config.xml deleted file mode 100644 index 7b1462746b..0000000000 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/src/main/resources/conf/iot-api-config.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - https://${iot.core.host}:${iot.core.https.port}/ - - - https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/ - - - admin - admin - - - https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.12/register - - - https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token - - - /services - - \ No newline at end of file diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/src/main/resources/p2.inf b/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/src/main/resources/p2.inf deleted file mode 100644 index e7c6acf89f..0000000000 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/src/main/resources/p2.inf +++ /dev/null @@ -1,2 +0,0 @@ -instructions.configure = \ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.apimgt.handler.server_${feature.version}/conf/iot-api-config.xml,target:${installFolder}/../../conf/iot-api-config.xml,overwrite:true);\ diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/pom.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/pom.xml deleted file mode 100644 index d1658f96c0..0000000000 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/pom.xml +++ /dev/null @@ -1,119 +0,0 @@ - - - - - - io.entgra.device.mgt.core - apimgt-extensions-feature - 5.0.0-SNAPSHOT - ../pom.xml - - - 4.0.0 - org.wso2.carbon.apimgt.integration.client.feature - pom - WSO2 Carbon - APIM Integration Client Feature - http://wso2.org - This feature contains a http client implementation to communicate with WSO2-APIM server - - - - io.entgra.device.mgt.core - org.wso2.carbon.apimgt.integration.client - - - io.entgra.device.mgt.core - org.wso2.carbon.apimgt.integration.generated.client - - - - - - - maven-resources-plugin - 2.6 - - - copy-resources - generate-resources - - copy-resources - - - src/main/resources - - - resources - - build.properties - p2.inf - - - - - - - - - org.wso2.maven - carbon-p2-plugin - ${carbon.p2.plugin.version} - - - p2-feature-generation - package - - p2-feature-gen - - - org.wso2.carbon.apimgt.integration.client - ../../../features/etc/feature.properties - - - org.wso2.carbon.p2.category.type:server - org.eclipse.equinox.p2.type.group:false - - - - - io.github.openfeign:feign-jackson:${io.github.openfeign.version} - - - io.github.openfeign:feign-core:${io.github.openfeign.version} - - - io.github.openfeign:feign-gson:${io.github.openfeign.version} - - - io.github.openfeign:feign-slf4j:${io.github.openfeign.version} - - - io.entgra.device.mgt.core:org.wso2.carbon.apimgt.integration.client:${project.version} - - - io.entgra.device.mgt.core:org.wso2.carbon.apimgt.integration.generated.client:${project.version} - - - - - - - - - diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/src/main/resources/build.properties b/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/src/main/resources/build.properties deleted file mode 100644 index 89aee3ff76..0000000000 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/src/main/resources/build.properties +++ /dev/null @@ -1,19 +0,0 @@ -# -# Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. -# -# Entgra (Pvt) Ltd. licenses this file to you 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. -# - -custom = true diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/src/main/resources/conf/apim-integration.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/src/main/resources/conf/apim-integration.xml deleted file mode 100644 index ec89b619c1..0000000000 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/src/main/resources/conf/apim-integration.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.12/register - https://${iot.gateway.host}:${iot.gateway.https.port}/token - https://${iot.apimpublisher.host}:${iot.apimpublisher.https.port}/api/am/publisher/v0.12 - https://${iot.apimstore.host}:${iot.apimstore.https.port}/api/am/store/v0.12 - admin - admin - \ No newline at end of file diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/src/main/resources/p2.inf b/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/src/main/resources/p2.inf deleted file mode 100644 index 3dca52fc59..0000000000 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/src/main/resources/p2.inf +++ /dev/null @@ -1,2 +0,0 @@ -instructions.configure = \ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.apimgt.integration.client_${feature.version}/conf/apim-integration.xml,target:${installFolder}/../../conf/apim-integration.xml,overwrite:true);\ diff --git a/features/apimgt-extensions/pom.xml b/features/apimgt-extensions/pom.xml index 9933bee4ea..b30032892c 100644 --- a/features/apimgt-extensions/pom.xml +++ b/features/apimgt-extensions/pom.xml @@ -31,7 +31,7 @@ apimgt-extensions-feature pom WSO2 Carbon - API Management Extensions Feature - http://wso2.org + https://entgra.io io.entgra.device.mgt.core.apimgt.webapp.publisher.feature diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/pom.xml b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/pom.xml index 3acec29245..6170579a5d 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/pom.xml +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/pom.xml @@ -60,8 +60,8 @@ ${cxf.version} - com.h2database.wso2 - h2-database-engine + org.wso2.orbit.com.h2database + h2 @@ -69,7 +69,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf/datasources/application-mgt-datasources.xml b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf/datasources/application-mgt-datasources.xml index dd3b6fc42f..f13ee588b6 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf/datasources/application-mgt-datasources.xml +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf/datasources/application-mgt-datasources.xml @@ -16,7 +16,7 @@ ~ under the License. --> - + org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql index 27c7669289..67694fa26c 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql @@ -42,6 +42,7 @@ CREATE TABLE IF NOT EXISTS AP_APP_RELEASE( RATED_USERS INTEGER NULL, AP_APP_ID INTEGER NOT NULL, PRIMARY KEY (ID), + CONSTRAINT UUID_CONSTRAINT UNIQUE (UUID), CONSTRAINT fk_AP_APP_RELEASE_AP_APP1 FOREIGN KEY (AP_APP_ID) REFERENCES AP_APP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION @@ -267,7 +268,7 @@ CREATE INDEX fk_AP_APP_SUB_OP_MAPPING_AP_DEVICE_SUBSCRIPTION1_idx ON AP_APP_SUB_ CREATE TABLE IF NOT EXISTS AP_SCHEDULED_SUBSCRIPTION( ID INTEGER NOT NULL AUTO_INCREMENT, TASK_NAME VARCHAR(100) NOT NULL, - APPLICATION_UUID VARCHAR(36) NOT NULL, + APPLICATION_UUID VARCHAR(200) NOT NULL, SUBSCRIBER_LIST LONGVARCHAR NOT NULL, STATUS VARCHAR(15) NOT NULL, SCHEDULED_AT BIGINT NOT NULL, diff --git a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api.feature/pom.xml b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api.feature/pom.xml index d75d0d6a4a..ddf23673a7 100644 --- a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api.feature/pom.xml +++ b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api.feature/pom.xml @@ -30,7 +30,7 @@ io.entgra.device.mgt.core.certificate.mgt.api.feature pom WSO2 Carbon - Certificate Management API Feature - http://wso2.org + https://entgra.io This feature contains the APIs required for Certificate Management. diff --git a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.feature/pom.xml b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.feature/pom.xml index cd735d49ba..ca84f08aee 100644 --- a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.feature/pom.xml +++ b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.feature/pom.xml @@ -30,7 +30,7 @@ io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.feature pom WSO2 Carbon - Admin Certificate Management API Feature - http://wso2.org + https://entgra.io This feature contains the APIs required for Admin Certificate Management. diff --git a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.server.feature/pom.xml b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.server.feature/pom.xml index d30ecdc964..b595688ff1 100644 --- a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.server.feature/pom.xml +++ b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.server.feature/pom.xml @@ -30,7 +30,7 @@ io.entgra.device.mgt.core.certificate.mgt.server.feature pom WSO2 Carbon - Certificate Management Server Feature - http://wso2.org + https://entgra.io This feature contains the core bundles required for back-end Certificate Management functionality @@ -48,7 +48,7 @@ bcpkix-jdk15on - org.wso2.orbit.com.google.code.jscep + io.entgra.com.google.code.jscep jscep @@ -73,7 +73,6 @@ maven-resources-plugin - 2.6 copy-resources @@ -124,7 +123,7 @@ org.wso2.orbit.org.bouncycastle:bcpkix-jdk15on:${bcpkix.wso2.version} - org.wso2.orbit.com.google.code.jscep:jscep:${jscep.version} + io.entgra.com.google.code.jscep:jscep:${jscep.version} commons-io.wso2:commons-io:${version.commons.io} diff --git a/features/certificate-mgt/pom.xml b/features/certificate-mgt/pom.xml index 2605cb5307..4862bc26b2 100644 --- a/features/certificate-mgt/pom.xml +++ b/features/certificate-mgt/pom.xml @@ -30,7 +30,7 @@ certificate-mgt-feature pom WSO2 Carbon - Certificate Management Feature - http://wso2.org + https://entgra.io io.entgra.device.mgt.core.certificate.mgt.server.feature diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.feature/pom.xml index 4803979259..6961e1c4d0 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.feature/pom.xml @@ -46,7 +46,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.feature/pom.xml index a829c2ee38..da8d09cc0d 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.feature/pom.xml @@ -30,7 +30,7 @@ io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.feature pom WSO2 Carbon - Device Type Deployer Feature - http://wso2.org + https://entgra.io WSO2 Carbon - Device Type Deployer Feature @@ -44,7 +44,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger.feature/pom.xml index 74f0b590c6..801618cb67 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger.feature/pom.xml @@ -46,7 +46,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml index 1a5739468e..b281a9ab5e 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml @@ -30,7 +30,7 @@ io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.feature pom WSO2 Carbon - FCM Based Push Notification Provider Feature - http://wso2.org + https://entgra.io WSO2 Carbon - MQTT Based Push Notification Provider Feature @@ -44,7 +44,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.feature/pom.xml index cf0713ce5d..e7ed43fb8d 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.feature/pom.xml @@ -30,7 +30,7 @@ io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.feature pom WSO2 Carbon - MQTT Based Push Notification Provider Feature - http://wso2.org + https://entgra.io WSO2 Carbon - MQTT Based Push Notification Provider Feature @@ -44,7 +44,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml index 19c98ade1b..2699079465 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml @@ -30,7 +30,7 @@ io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.feature pom WSO2 Carbon - MQTT Based Push Notification Provider Feature - http://wso2.org + https://entgra.io WSO2 Carbon - MQTT Based Push Notification Provider Feature @@ -44,7 +44,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml index bec51304ac..dc586b9ac9 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml @@ -30,7 +30,7 @@ io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.feature pom WSO2 Carbon - XMPP Based Push Notification Provider Feature - http://wso2.org + https://entgra.io WSO2 Carbon - XMPP Based Push Notification Provider Feature @@ -44,7 +44,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine.feature/pom.xml index 05ef9d2518..6f4f899cbc 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine.feature/pom.xml @@ -46,7 +46,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/device-mgt-extensions/pom.xml b/features/device-mgt-extensions/pom.xml index 03b3cd5035..91fb09e401 100644 --- a/features/device-mgt-extensions/pom.xml +++ b/features/device-mgt-extensions/pom.xml @@ -30,7 +30,7 @@ device-mgt-extensions-feature pom WSO2 Carbon - Device Management Extensions Feature - http://wso2.org + https://entgra.io io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.feature diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.api.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.api.feature/pom.xml index 9e037c35e4..4d7ed1e2c2 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.api.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.api.feature/pom.xml @@ -30,7 +30,7 @@ io.entgra.device.mgt.core.device.mgt.api.feature pom WSO2 Carbon - Device Management API Feature - http://wso2.org + https://entgra.io This feature contains the APIs required for Device Management console UI diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/pom.xml index 88ddcf2365..1333c8acca 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/pom.xml @@ -30,7 +30,7 @@ io.entgra.device.mgt.core.device.mgt.basics.feature pom WSO2 Carbon - Device Management Basics Feature - http://wso2.org + https://entgra.io This feature contains the core bundles required for Basic Device Management functionality @@ -49,7 +49,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/datasources/cdm-datasources.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/datasources/cdm-datasources.xml index 037512da4a..7923fef1bf 100755 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/datasources/cdm-datasources.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/datasources/cdm-datasources.xml @@ -16,7 +16,7 @@ ~ under the License. --> - + org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/datasources/reporting-mgt-datasources.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/datasources/reporting-mgt-datasources.xml index 96b84711ba..7f675a6e5b 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/datasources/reporting-mgt-datasources.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/datasources/reporting-mgt-datasources.xml @@ -16,7 +16,7 @@ ~ under the License. --> - + org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml index da4191cff2..e3145564e1 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml @@ -240,6 +240,7 @@ am:admin:store:app:review:update am:admin:store:app:sub:view am:admin:store:app:sub:modify + am:admin:store:app:release-versions:view dm:device-type:view and:enterprise:modify and:enterprise:view @@ -361,6 +362,7 @@ and:ops:change-lock-code and:ops:upgrade-firmware and:ops:send-notif + and:ops:secure-folder dm:geo:geo-fence:manage dm:whitelable:view dm:whitelable:update diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql index 342c330376..6ba0077069 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -44,7 +44,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE ( ID INTEGER auto_increment NOT NULL, DESCRIPTION TEXT DEFAULT NULL, NAME VARCHAR(100) DEFAULT NULL, - DEVICE_TYPE_ID INT(11) DEFAULT NULL, + DEVICE_TYPE_ID INT DEFAULT NULL, DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, TENANT_ID INTEGER DEFAULT 0, @@ -194,17 +194,17 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE ( ); CREATE TABLE IF NOT EXISTS DM_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , + ID INT NOT NULL AUTO_INCREMENT , NAME VARCHAR(45) DEFAULT NULL , DESCRIPTION VARCHAR(1000) NULL, PAYLOAD_VERSION VARCHAR (45) NULL, - TENANT_ID INT(11) NOT NULL , - PROFILE_ID INT(11) NOT NULL , + TENANT_ID INT NOT NULL , + PROFILE_ID INT NOT NULL , OWNERSHIP_TYPE VARCHAR(45) NULL, COMPLIANCE VARCHAR(100) NULL, PRIORITY INT NOT NULL, - ACTIVE INT(2) NOT NULL, - UPDATED INT(1) NULL, + ACTIVE INT NOT NULL, + UPDATED INT NULL, POLICY_TYPE VARCHAR(45) NULL, PRIMARY KEY (ID) , CONSTRAINT FK_DM_PROFILE_DM_POLICY @@ -215,11 +215,11 @@ CREATE TABLE IF NOT EXISTS DM_POLICY ( ); CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , - DEVICE_ID INT(11) NOT NULL , - ENROLMENT_ID INT(11) NOT NULL, + ID INT NOT NULL AUTO_INCREMENT , + DEVICE_ID INT NOT NULL , + ENROLMENT_ID INT NOT NULL, DEVICE BLOB NOT NULL, - POLICY_ID INT(11) NOT NULL , + POLICY_ID INT NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_POLICY_DEVICE_POLICY FOREIGN KEY (POLICY_ID ) @@ -234,9 +234,9 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( ); CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( - ID INT(11) NOT NULL , + ID INT NOT NULL , DEVICE_TYPE VARCHAR(300) NOT NULL , - POLICY_ID INT(11) NOT NULL , + POLICY_ID INT NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_DEVICE_TYPE_POLICY FOREIGN KEY (POLICY_ID ) @@ -246,11 +246,11 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( ); CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( - ID INT(11) NOT NULL AUTO_INCREMENT, - PROFILE_ID INT(11) NOT NULL, + ID INT NOT NULL AUTO_INCREMENT, + PROFILE_ID INT NOT NULL, FEATURE_CODE VARCHAR(100) NOT NULL, DEVICE_TYPE VARCHAR(300) NOT NULL, - TENANT_ID INT(11) NOT NULL , + TENANT_ID INT NOT NULL , CONTENT BLOB NULL DEFAULT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES @@ -261,11 +261,11 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( ); CREATE TABLE IF NOT EXISTS DM_POLICY_CORRECTIVE_ACTION ( - ID INT(11) NOT NULL AUTO_INCREMENT, + ID INT NOT NULL AUTO_INCREMENT, ACTION_TYPE VARCHAR(45) NOT NULL, - CORRECTIVE_POLICY_ID INT(11) DEFAULT NULL, - POLICY_ID INT(11) NOT NULL, - FEATURE_ID INT(11) DEFAULT NULL, + CORRECTIVE_POLICY_ID INT DEFAULT NULL, + POLICY_ID INT NOT NULL, + FEATURE_ID INT DEFAULT NULL, IS_REACTIVE BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (ID), CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION @@ -276,9 +276,9 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CORRECTIVE_ACTION ( ); CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , + ID INT NOT NULL AUTO_INCREMENT , ROLE_NAME VARCHAR(45) NOT NULL , - POLICY_ID INT(11) NOT NULL , + POLICY_ID INT NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_ROLE_POLICY_POLICY FOREIGN KEY (POLICY_ID ) @@ -302,11 +302,11 @@ CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( ID INT NOT NULL AUTO_INCREMENT , DEVICE_ID INT NOT NULL , - ENROLMENT_ID INT(11) NOT NULL, + ENROLMENT_ID INT NOT NULL, POLICY_ID INT NOT NULL , POLICY_CONTENT TEXT NULL , TENANT_ID INT NOT NULL, - APPLIED TINYINT(1) NULL , + APPLIED TINYINT NULL , CREATED_TIME TIMESTAMP NULL , UPDATED_TIME TIMESTAMP NULL , APPLIED_TIME TIMESTAMP NULL , @@ -359,7 +359,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES ( CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( ID INT NOT NULL AUTO_INCREMENT, DEVICE_ID INT NOT NULL, - ENROLMENT_ID INT(11) NOT NULL, + ENROLMENT_ID INT NOT NULL, POLICY_ID INT NOT NULL, TENANT_ID INT NOT NULL, STATUS INT NULL, @@ -374,7 +374,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( ID INT NOT NULL AUTO_INCREMENT, POLICY_ID INT NOT NULL, DEVICE_TYPE VARCHAR(300) NOT NULL , - TENANT_ID INT(11) NOT NULL, + TENANT_ID INT NOT NULL, PRIMARY KEY (ID) ); @@ -403,7 +403,7 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION ( LOCATION_URL VARCHAR(100) DEFAULT NULL, IMAGE_URL VARCHAR(100) DEFAULT NULL, APP_PROPERTIES BLOB NULL, - MEMORY_USAGE INTEGER(10) NULL, + MEMORY_USAGE INTEGER NULL, IS_ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, DEVICE_ID INTEGER NOT NULL, ENROLMENT_ID INTEGER NOT NULL, @@ -482,7 +482,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( STATE VARCHAR(45) NULL, COUNTRY VARCHAR(45) NULL, GEO_HASH VARCHAR(45) NULL, - UPDATE_TIMESTAMP BIGINT(15) NOT NULL, + UPDATE_TIMESTAMP BIGINT NOT NULL, ALTITUDE DOUBLE NULL, SPEED FLOAT NULL, BEARING FLOAT NULL, @@ -519,8 +519,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( CPU_USAGE DECIMAL(5) NULL, TOTAL_RAM_MEMORY DECIMAL(30,3) NULL, AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL, - PLUGGED_IN INT(1) NULL, - UPDATE_TIMESTAMP BIGINT(15) NOT NULL, + PLUGGED_IN INT NULL, + UPDATE_TIMESTAMP BIGINT NOT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE FOREIGN KEY (DEVICE_ID) @@ -547,7 +547,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_HISTORY_LAST_SEVEN_DAYS LONGITUDE DOUBLE NULL, SPEED FLOAT NULL, HEADING FLOAT NULL, - TIMESTAMP BIGINT(15) NOT NULL, + TIMESTAMP BIGINT NOT NULL, GEO_HASH VARCHAR(45) NULL, DEVICE_OWNER VARCHAR(45) NULL, DEVICE_ALTITUDE DOUBLE NULL, @@ -828,16 +828,17 @@ CREATE TABLE IF NOT EXISTS DM_TRACCAR_UNSYNCED_DEVICES ( -- END OF DM_TRACCAR_UNSYNCED_DEVICES TABLE -- -- SUB_OPERATION_TEMPLATE TABLE-- -CREATE TABLE SUB_OPERATION_TEMPLATE ( - SUB_OPERATION_TEMPLATE_ID int NOT NULL AUTO_INCREMENT, +CREATE TABLE IF NOT EXISTS SUB_OPERATION_TEMPLATE ( + SUB_OPERATION_TEMPLATE_ID INT NOT NULL AUTO_INCREMENT, OPERATION_DEFINITION TEXT NOT NULL, - OPERATION_CODE varchar(100) NOT NULL, - SUB_TYPE_ID int NOT NULL, + OPERATION_CODE VARCHAR(100) NOT NULL, + SUB_TYPE_ID INT NOT NULL, DEVICE_TYPE VARCHAR(25) NOT NULL, - CREATE_TIMESTAMP timestamp NULL DEFAULT NULL, - UPDATE_TIMESTAMP timestamp NULL DEFAULT NULL, + CREATE_TIMESTAMP TIMESTAMP NULL DEFAULT NULL, + UPDATE_TIMESTAMP TIMESTAMP NULL DEFAULT NULL, PRIMARY KEY (SUB_OPERATION_TEMPLATE_ID), - UNIQUE KEY SUB_OPERATION_TEMPLATE (SUB_TYPE_ID,OPERATION_CODE, DEVICE_TYPE), + CONSTRAINT uk_sub_operation_template UNIQUE (SUB_TYPE_ID, OPERATION_CODE, DEVICE_TYPE), +-- UNIQUE KEY SUB_OPERATION_TEMPLATE (SUB_TYPE_ID, OPERATION_CODE, DEVICE_TYPE), CONSTRAINT fk_SUB_OPERATION_TEMPLATE_DM_DEVICE_SUB_TYPE FOREIGN KEY (SUB_TYPE_ID, DEVICE_TYPE) REFERENCES DM_DEVICE_SUB_TYPE (SUB_TYPE_ID, DEVICE_TYPE) ); @@ -848,8 +849,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_ORGANIZATION ( ORGANIZATION_ID INT NOT NULL AUTO_INCREMENT, TENANT_ID INT DEFAULT 0, - DEVICE_ID INT(11) NOT NULL, - PARENT_DEVICE_ID INT(11) DEFAULT NULL, + DEVICE_ID INT NOT NULL, + PARENT_DEVICE_ID INT DEFAULT NULL, DEVICE_ORGANIZATION_META TEXT DEFAULT NULL, LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, PRIMARY KEY (ORGANIZATION_ID), @@ -875,3 +876,24 @@ CREATE TABLE IF NOT EXISTS DM_CEA_POLICIES ( -- END OF DM_CEA_POLICIES TABLE -- +-- DM_TAG TABLE -- +CREATE TABLE IF NOT EXISTS DM_TAG ( + ID INTEGER AUTO_INCREMENT, + NAME VARCHAR(255) NOT NULL, + DESCRIPTION VARCHAR(255) NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT DM_TAG_NAME_TENANT_UNIQUE UNIQUE (NAME, TENANT_ID) + ); +-- END OF DM_TAG TABLE -- + +-- DM_DEVICE_TAG_MAPPING TABLE -- +CREATE TABLE IF NOT EXISTS DM_DEVICE_TAG_MAPPING ( + ENROLMENT_ID INTEGER NOT NULL, + TAG_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY (ENROLMENT_ID, TAG_ID, TENANT_ID), + FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT(ID), + FOREIGN KEY (TAG_ID) REFERENCES DM_TAG(ID) ON DELETE CASCADE + ); +-- END OF DM_DEVICE_TAG_MAPPING TABLE -- diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql index f6f3232e13..272066798d 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -951,3 +951,25 @@ BEGIN END; -- END OF DM_CEA_POLICIES TABLE -- + +-- DM_TAG TABLE -- +CREATE TABLE IF NOT EXISTS DM_TAG ( + ID INTEGER IDENTITY(1,1) PRIMARY KEY, + NAME NVARCHAR(255) NOT NULL, + DESCRIPTION NVARCHAR(255) NULL, + TENANT_ID INTEGER NOT NULL, + CONSTRAINT DM_TAG_NAME_TENANT_UNIQUE UNIQUE (NAME, TENANT_ID) + ); +-- END OF DM_TAG TABLE -- + +-- DM_DEVICE_TAG_MAPPING TABLE -- +CREATE TABLE IF NOT EXISTS DM_DEVICE_TAG_MAPPING ( + ENROLMENT_ID INTEGER NOT NULL, + TAG_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY (ENROLMENT_ID, TAG_ID, TENANT_ID), + FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT(ID), + FOREIGN KEY (TAG_ID) REFERENCES DM_TAG(ID) ON DELETE CASCADE + ); +-- END OF DM_DEVICE_TAG_MAPPING TABLE -- + diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql index 4390f6a40d..773fe53b34 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -950,3 +950,25 @@ CREATE TABLE IF NOT EXISTS DM_CEA_POLICIES ( ); -- END OF DM_CEA_POLICIES TABLE -- + +-- DM_TAG TABLE -- +CREATE TABLE IF NOT EXISTS DM_TAG ( + ID INTEGER AUTO_INCREMENT PRIMARY KEY, + NAME VARCHAR(255) NOT NULL, + DESCRIPTION VARCHAR(255) NULL, + TENANT_ID INTEGER NOT NULL, + CONSTRAINT DM_TAG_NAME_TENANT_UNIQUE UNIQUE (NAME, TENANT_ID) + ); +-- END OF DM_TAG TABLE -- + +-- DM_DEVICE_TAG_MAPPING TABLE -- +CREATE TABLE IF NOT EXISTS DM_DEVICE_TAG_MAPPING ( + ENROLMENT_ID INTEGER NOT NULL, + TAG_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY (ENROLMENT_ID, TAG_ID, TENANT_ID), + FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT(ID), + FOREIGN KEY (TAG_ID) REFERENCES DM_TAG(ID) ON DELETE CASCADE + ); +-- END OF DM_DEVICE_TAG_MAPPING TABLE -- + diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql index d5a442c69e..1b1071c290 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql @@ -1255,3 +1255,25 @@ END; / -- END OF DM_CEA_POLICIES TABLE -- + +-- DM_TAG TABLE -- +CREATE TABLE DM_TAG ( + ID NUMBER(10) GENERATED BY DEFAULT ON NULL AS IDENTITY PRIMARY KEY, + NAME VARCHAR2(255) NOT NULL, + DESCRIPTION VARCHAR2(255) NULL, + TENANT_ID NUMBER(10) NOT NULL, + CONSTRAINT DM_TAG_NAME_TENANT_UNIQUE UNIQUE (NAME, TENANT_ID) +); +-- END OF DM_TAG TABLE -- + +-- DM_DEVICE_TAG_MAPPING TABLE -- +CREATE TABLE DM_DEVICE_TAG_MAPPING ( + ENROLMENT_ID NUMBER(10) NOT NULL, + TAG_ID NUMBER(10) NOT NULL, + TENANT_ID NUMBER(10) NOT NULL, + PRIMARY KEY (ENROLMENT_ID, TAG_ID, TENANT_ID), + FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT(ID), + FOREIGN KEY (TAG_ID) REFERENCES DM_TAG(ID) ON DELETE CASCADE +); +-- END OF DM_DEVICE_TAG_MAPPING TABLE -- + diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql index 354925efe5..31591893e1 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql @@ -881,3 +881,25 @@ CREATE TABLE IF NOT EXISTS DM_CEA_POLICIES ( ); -- END OF DM_CEA_POLICIES TABLE -- + +-- DM_TAG TABLE -- +CREATE TABLE IF NOT EXISTS DM_TAG ( + ID INTEGER PRIMARY KEY, + NAME VARCHAR(255) NOT NULL, + DESCRIPTION VARCHAR(255) NULL, + TENANT_ID INTEGER NOT NULL, + CONSTRAINT DM_TAG_NAME_TENANT_UNIQUE UNIQUE (NAME, TENANT_ID) + ); +-- END OF DM_TAG TABLE -- + +-- DM_DEVICE_TAG_MAPPING TABLE -- +CREATE TABLE IF NOT EXISTS DM_DEVICE_TAG_MAPPING ( + ENROLMENT_ID INTEGER NOT NULL, + TAG_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY (ENROLMENT_ID, TAG_ID, TENANT_ID), + FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT(ID), + FOREIGN KEY (TAG_ID) REFERENCES DM_TAG(ID) ON DELETE CASCADE + ); +-- END OF DM_DEVICE_TAG_MAPPING TABLE -- + diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions.feature/pom.xml index bc77ca025d..97054900da 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions.feature/pom.xml @@ -30,7 +30,7 @@ io.entgra.device.mgt.core.device.mgt.extensions.feature pom WSO2 Carbon - Device Management Extensions Feature - http://wso2.org + https://entgra.io This feature contains common extensions used by key device management functionalities @@ -49,7 +49,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.feature/pom.xml index 40624fbc02..18eda1c211 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.feature/pom.xml @@ -30,7 +30,7 @@ io.entgra.device.mgt.core.device.mgt.feature pom WSO2 Carbon - Device Management Aggregate Feature - http://wso2.org + https://entgra.io This feature contains all the bundles required for device management related functionalities @@ -44,11 +44,7 @@ javax.servlet.jsp-api - org.wso2.carbon.store - org.wso2.store.sso.common - - - org.wso2.orbit.org.scannotation + io.entgra.org.scannotation scannotation @@ -78,8 +74,7 @@ javax.servlet.jsp:javax.servlet.jsp-api - org.wso2.carbon.store:org.wso2.store.sso.common:${carbon.store.sso.common.version} - org.wso2.orbit.org.scannotation:scannotation:${scannotation.version} + io.entgra.org.scannotation:scannotation:${scannotation.version} diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.server.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.server.feature/pom.xml index fc36953c14..c94d46583e 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.server.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.server.feature/pom.xml @@ -30,7 +30,7 @@ io.entgra.device.mgt.core.device.mgt.server.feature pom WSO2 Carbon - Device Management Server Feature - http://wso2.org + https://entgra.io This feature contains the core bundles required for Back-end Device Management functionality @@ -62,7 +62,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.analytics.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.analytics.feature/pom.xml deleted file mode 100644 index b2b9016fba..0000000000 --- a/features/device-mgt/org.wso2.carbon.device.mgt.analytics.feature/pom.xml +++ /dev/null @@ -1,145 +0,0 @@ - - - - - - - io.entgra.device.mgt.core - device-mgt-feature - 5.0.0-SNAPSHOT - ../pom.xml - - - 4.0.0 - org.wso2.carbon.device.mgt.analytics.feature - pom - WSO2 Carbon - Device Management Server Feature - http://wso2.org - This feature contains bundles related to device analytics data publisher and ws proxy - - - - io.entgra.device.mgt.core - org.wso2.carbon.device.mgt.analytics.data.publisher - - - org.wso2.carbon.registry - org.wso2.carbon.registry.indexing - - - org.wso2.carbon.registry - org.wso2.carbon.registry.common - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy - package - - copy - - - - - io.entgra.device.mgt.core - org.wso2.carbon.device.mgt.analytics.wsproxy - ${project.version} - war - true - - ${project.build.directory}/maven-shared-archive-resources/webapps - - secured-websocket-proxy.war - - - - - - - - maven-resources-plugin - 2.6 - - - copy-resources - generate-resources - - copy-resources - - - src/main/resources - - - resources - - build.properties - p2.inf - - - - - - - - - org.wso2.maven - carbon-p2-plugin - ${carbon.p2.plugin.version} - - - p2-feature-generation - package - - p2-feature-gen - - - org.wso2.carbon.device.mgt.analytics - ../../../features/etc/feature.properties - - - org.wso2.carbon.p2.category.type:server - org.eclipse.equinox.p2.type.group:false - - - - - io.entgra.device.mgt.core:org.wso2.carbon.device.mgt.analytics.data.publisher:${io.entgra.device.mgt.core.version} - - - - org.wso2.carbon.core.server:${carbon.kernel.version} - - - org.wso2.carbon.registry:org.wso2.carbon.registry.indexing:${carbon.registry.version} - org.wso2.carbon.registry:org.wso2.carbon.registry.common:${carbon.registry.version} - - - - - - - - - diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.analytics.feature/src/main/resources/build.properties b/features/device-mgt/org.wso2.carbon.device.mgt.analytics.feature/src/main/resources/build.properties deleted file mode 100644 index 89aee3ff76..0000000000 --- a/features/device-mgt/org.wso2.carbon.device.mgt.analytics.feature/src/main/resources/build.properties +++ /dev/null @@ -1,19 +0,0 @@ -# -# Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. -# -# Entgra (Pvt) Ltd. licenses this file to you 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. -# - -custom = true diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.analytics.feature/src/main/resources/conf/device-analytics-config.xml b/features/device-mgt/org.wso2.carbon.device.mgt.analytics.feature/src/main/resources/conf/device-analytics-config.xml deleted file mode 100644 index 8a39b21a21..0000000000 --- a/features/device-mgt/org.wso2.carbon.device.mgt.analytics.feature/src/main/resources/conf/device-analytics-config.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - true - - tcp://${iot.analytics.host}:${iot.analytics.thrift.port} - - wss://${iot.analytics.host}:${iot.analytics.https.port} - admin - admin - diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.analytics.feature/src/main/resources/p2.inf b/features/device-mgt/org.wso2.carbon.device.mgt.analytics.feature/src/main/resources/p2.inf deleted file mode 100644 index a0a1b3d005..0000000000 --- a/features/device-mgt/org.wso2.carbon.device.mgt.analytics.feature/src/main/resources/p2.inf +++ /dev/null @@ -1,4 +0,0 @@ -instructions.configure = \ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.analytics_${feature.version}/conf/device-analytics-config.xml,target:${installFolder}/../../conf/etc/device-analytics-config.xml,overwrite:true);\ -org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.analytics_${feature.version}/webapps/secured-websocket-proxy.war,target:${installFolder}/../../deployment/server/webapps/secured-websocket-proxy.war,overwrite:true);\ \ No newline at end of file diff --git a/features/device-mgt/pom.xml b/features/device-mgt/pom.xml index c640bb7a27..e4178b397a 100644 --- a/features/device-mgt/pom.xml +++ b/features/device-mgt/pom.xml @@ -30,7 +30,7 @@ device-mgt-feature pom WSO2 Carbon - Device Management Feature - http://wso2.org + https://entgra.io io.entgra.device.mgt.core.device.mgt.basics.feature diff --git a/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/pom.xml b/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/pom.xml index 47250468b0..b5ef62b8e7 100644 --- a/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/pom.xml +++ b/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/pom.xml @@ -37,8 +37,8 @@ - com.h2database.wso2 - h2-database-engine + org.wso2.orbit.com.h2database + h2 io.entgra.device.mgt.core @@ -80,7 +80,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/src/main/resources/datasources/heart-beat-datasources.xml b/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/src/main/resources/datasources/heart-beat-datasources.xml index 84136c25e1..5982b3e054 100644 --- a/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/src/main/resources/datasources/heart-beat-datasources.xml +++ b/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/src/main/resources/datasources/heart-beat-datasources.xml @@ -15,7 +15,7 @@ ~ specific language governing permissions and limitations ~ under the License. --> - + org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader diff --git a/features/jwt-client/io.entgra.device.mgt.core.identity.jwt.client.extension.feature/pom.xml b/features/jwt-client/io.entgra.device.mgt.core.identity.jwt.client.extension.feature/pom.xml index f2b38a0e9d..95a977d2e0 100644 --- a/features/jwt-client/io.entgra.device.mgt.core.identity.jwt.client.extension.feature/pom.xml +++ b/features/jwt-client/io.entgra.device.mgt.core.identity.jwt.client.extension.feature/pom.xml @@ -31,7 +31,7 @@ io.entgra.device.mgt.core.identity.jwt.client.extension.feature pom WSO2 Carbon - JWT Client Feature - http://wso2.org + https://entgra.io This feature contains jwt client implementation from which we can get a access token using the jwt grant type handler @@ -51,7 +51,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/jwt-client/pom.xml b/features/jwt-client/pom.xml index d6e936796c..710785e849 100644 --- a/features/jwt-client/pom.xml +++ b/features/jwt-client/pom.xml @@ -31,7 +31,7 @@ jwt-client-feature pom WSO2 Carbon - JWT Client Extension Feature - http://wso2.org + https://entgra.io io.entgra.device.mgt.core.identity.jwt.client.extension.feature diff --git a/features/logger/io.entgra.device.mgt.core.notification.logger.feature/pom.xml b/features/logger/io.entgra.device.mgt.core.notification.logger.feature/pom.xml index 1e7e05c7bf..fdc21ef2e0 100644 --- a/features/logger/io.entgra.device.mgt.core.notification.logger.feature/pom.xml +++ b/features/logger/io.entgra.device.mgt.core.notification.logger.feature/pom.xml @@ -38,8 +38,9 @@ - org.wso2.carbon - org.wso2.carbon.logging + org.ops4j.pax.logging + pax-logging-api + provided org.testng @@ -59,7 +60,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/oauth-extensions/org.wso2.carbon.device.mgt.oauth.extensions.feature/pom.xml b/features/oauth-extensions/org.wso2.carbon.device.mgt.oauth.extensions.feature/pom.xml index ed92a080a1..29e96f43cd 100644 --- a/features/oauth-extensions/org.wso2.carbon.device.mgt.oauth.extensions.feature/pom.xml +++ b/features/oauth-extensions/org.wso2.carbon.device.mgt.oauth.extensions.feature/pom.xml @@ -31,7 +31,7 @@ io.entgra.device.mgt.core.device.mgt.oauth.extensions.feature pom WSO2 Carbon - Device Mgt OAuth Extensions Feature - http://wso2.org + https://entgra.io This feature contains devicemgt related OAuth extensions diff --git a/features/oauth-extensions/pom.xml b/features/oauth-extensions/pom.xml index 16063e957b..d40fd22467 100644 --- a/features/oauth-extensions/pom.xml +++ b/features/oauth-extensions/pom.xml @@ -30,7 +30,7 @@ oauth-extensions-feature pom WSO2 Carbon - Device Management OAuth Extensions Feature - http://wso2.org + https://entgra.io io.entgra.device.mgt.core.device.mgt.oauth.extensions.feature diff --git a/features/operation-template-mgt-plugin-feature/io.entgra.device.mgt.core.operation.template.feature/pom.xml b/features/operation-template-mgt-plugin-feature/io.entgra.device.mgt.core.operation.template.feature/pom.xml index 26b6faa900..21db4997c9 100644 --- a/features/operation-template-mgt-plugin-feature/io.entgra.device.mgt.core.operation.template.feature/pom.xml +++ b/features/operation-template-mgt-plugin-feature/io.entgra.device.mgt.core.operation.template.feature/pom.xml @@ -46,7 +46,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/policy-mgt/io.entgra.device.mgt.core.policy.mgt.server.feature/pom.xml b/features/policy-mgt/io.entgra.device.mgt.core.policy.mgt.server.feature/pom.xml index 924db60119..8ed8e5f49a 100644 --- a/features/policy-mgt/io.entgra.device.mgt.core.policy.mgt.server.feature/pom.xml +++ b/features/policy-mgt/io.entgra.device.mgt.core.policy.mgt.server.feature/pom.xml @@ -31,7 +31,7 @@ io.entgra.device.mgt.core.policy.mgt.server.feature pom WSO2 Carbon - Policy Management Server Feature - http://wso2.org + https://entgra.io This feature contains the core bundles required for Back-end Device Management functionality @@ -62,7 +62,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/policy-mgt/pom.xml b/features/policy-mgt/pom.xml index 12ad18c744..3adb3ad614 100644 --- a/features/policy-mgt/pom.xml +++ b/features/policy-mgt/pom.xml @@ -32,7 +32,7 @@ policy-mgt-feature pom WSO2 Carbon - Policy Management Feature - http://wso2.org + https://entgra.io io.entgra.device.mgt.core.policy.mgt.server.feature diff --git a/features/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt.feature/pom.xml b/features/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt.feature/pom.xml index 4e5ce66fa1..a06223bd95 100644 --- a/features/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt.feature/pom.xml +++ b/features/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt.feature/pom.xml @@ -46,7 +46,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/task-mgt/io.entgra.device.mgt.core.task.mgt.feature/pom.xml b/features/task-mgt/io.entgra.device.mgt.core.task.mgt.feature/pom.xml index 8175d327c9..d241eff822 100755 --- a/features/task-mgt/io.entgra.device.mgt.core.task.mgt.feature/pom.xml +++ b/features/task-mgt/io.entgra.device.mgt.core.task.mgt.feature/pom.xml @@ -29,7 +29,7 @@ io.entgra.device.mgt.core.task.mgt.feature pom Entgra IoT - Task Manager Feature - http://wso2.org + https://entgra.io @@ -46,7 +46,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.server.feature/pom.xml b/features/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.server.feature/pom.xml index 09d2641ba0..8f40306d87 100644 --- a/features/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.server.feature/pom.xml +++ b/features/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.server.feature/pom.xml @@ -45,7 +45,6 @@ maven-resources-plugin - 2.6 copy-resources @@ -91,7 +90,6 @@ - io.entgra.device.mgt.core:io.entgra.device.mgt.core.tenant.mgt.core:${io.entgra.device.mgt.core.version} diff --git a/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/pom.xml b/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/pom.xml index 0e24480bec..6a50c3a704 100644 --- a/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/pom.xml +++ b/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/pom.xml @@ -30,7 +30,7 @@ io.entgra.device.mgt.core.email.sender.feature pom WSO2 Carbon - Email Sender Feature - http://wso2.org + https://entgra.io This feature contains the core bundles required for email sender related functionality @@ -39,10 +39,6 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.transport.mgt.email.sender.core - - org.wso2.orbit.org.apache.velocity - velocity - @@ -50,7 +46,6 @@ org.apache.maven.plugins maven-resources-plugin - 2.6 copy-resources @@ -97,9 +92,6 @@ io.entgra.device.mgt.core:io.entgra.device.mgt.core.transport.mgt.email.sender.core:${io.entgra.device.mgt.core.version} - - org.wso2.orbit.org.apache.velocity:velocity:${velocity.version} - org.wso2.carbon.core.server:${carbon.kernel.version} diff --git a/features/transport-mgt/email-sender/pom.xml b/features/transport-mgt/email-sender/pom.xml index 1acff47254..ec244897d7 100644 --- a/features/transport-mgt/email-sender/pom.xml +++ b/features/transport-mgt/email-sender/pom.xml @@ -31,7 +31,7 @@ email-sender-feature pom WSO2 Carbon - Email Sender Feature - http://wso2.org + https://entgra.io io.entgra.device.mgt.core.email.sender.feature diff --git a/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.server.feature/pom.xml b/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.server.feature/pom.xml index 1dfeea33d9..679db11051 100644 --- a/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.server.feature/pom.xml +++ b/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.server.feature/pom.xml @@ -49,7 +49,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework.server.feature/pom.xml b/features/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework.server.feature/pom.xml index 61403205d8..b423ee65a0 100644 --- a/features/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework.server.feature/pom.xml +++ b/features/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework.server.feature/pom.xml @@ -30,7 +30,7 @@ io.entgra.device.mgt.core.webapp.authenticator.framework.server.feature pom WSO2 Carbon - Webapp Authenticator Framework Server Feature - http://wso2.org + https://entgra.io This feature contains the core bundles required for Back-end Device Management functionality @@ -45,7 +45,6 @@ maven-resources-plugin - 2.6 copy-resources diff --git a/features/webapp-authenticator-framework/pom.xml b/features/webapp-authenticator-framework/pom.xml index e4238b6fd7..b7579c8e1d 100644 --- a/features/webapp-authenticator-framework/pom.xml +++ b/features/webapp-authenticator-framework/pom.xml @@ -31,7 +31,7 @@ webapp-authenticator-framework-feature pom WSO2 Carbon - Webapp Authenticator Framework Feature - http://wso2.org + https://entgra.io io.entgra.device.mgt.core.webapp.authenticator.framework.server.feature diff --git a/pom.xml b/pom.xml index 01ed367560..f0edb13595 100644 --- a/pom.xml +++ b/pom.xml @@ -25,12 +25,12 @@ pom 5.2.4-SNAPSHOT WSO2 Carbon - Device Management - Parent - http://wso2.org + https://entgra.io WSO2 Connected Device Manager Components org.wso2 wso2 - 1 + 1.3 @@ -172,6 +172,12 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.device.mgt.common ${io.entgra.device.mgt.core.version} + + + com.fasterxml.jackson.core + jackson-annotations + + io.entgra.device.mgt.core @@ -405,6 +411,7 @@ ${io.entgra.device.mgt.core.version} + org.wso2.carbon @@ -616,29 +623,6 @@ - - - org.eclipse.osgi - org.eclipse.osgi - ${eclipse.osgi.version} - - - org.eclipse.equinox - org.eclipse.equinox.common - ${eclipse.equinox.common.version} - - - org.eclipse.osgi - org.eclipse.osgi.services - ${eclipse.equinox.services.version} - - - org.osgi.ut - org.eclipse.osgi - ${eclipse.equinox.services.version} - - - org.testng testng @@ -739,10 +723,6 @@ org.eclipse.equinox org.eclipse.equinox.http.helper - org.wso2.carbon org.wso2.carbon.registry.core @@ -792,6 +772,10 @@ org.wso2.carbon.user.core ${carbon.kernel.version} + + com.fasterxml.jackson.core + jackson-annotations + org.apache.felix javax.servlet @@ -837,11 +821,6 @@ - - org.wso2.carbon - org.wso2.carbon.logging - ${org.wso2.carbon.logging.version} - org.wso2.carbon org.wso2.carbon.core.services @@ -850,12 +829,6 @@ - - com.h2database.wso2 - h2-database-engine - ${orbit.version.h2.engine} - - org.wso2.orbit.com.h2database h2 @@ -888,10 +861,19 @@ - javax.xml.bind + org.wso2.orbit.javax.xml.bind jaxb-api - ${jaxb.api.version} - test + ${version.org.wso2.orbit.javax.xml.bind} + + + com.sun.xml.bind + jaxb-core + 2.3.0.1 + + + com.sun.xml.bind + jaxb-impl + 2.3.1 org.wso2.orbit.javax.xml.bind @@ -952,27 +934,34 @@ axiom ${axiom.wso2.version} - - - - - - org.wso2.carbon.apimgt org.wso2.carbon.apimgt.api ${carbon.api.mgt.version} + + + com.fasterxml.jackson.core + jackson-annotations + + org.wso2.carbon.apimgt org.wso2.carbon.apimgt.impl ${carbon.api.mgt.version} + + + com.fasterxml.jackson.core + jackson-annotations + + + - org.wso2.tomcat + org.wso2.orbit.org.apache.tomcat tomcat ${orbit.version.tomcat} @@ -1034,14 +1023,14 @@ - org.apache.tomcat.wso2 + org.wso2.orbit.org.apache.tomcat jdbc-pool - ${tomcat.jdbc.pooling.version} + ${orbit.version.tomcat} - org.wso2.tomcat + org.wso2.orbit.org.apache.tomcat tomcat-servlet-api - ${orbit.version.tomcat.servlet.api} + ${orbit.version.tomcat} @@ -1199,42 +1188,6 @@ cxf-rt-transports-http ${cxf.version} - - org.apache.cxf - cxf-rt-bindings-soap - ${cxf.version} - - - org.apache.cxf - cxf-rt-databinding-jaxb - - - - - org.apache.cxf - cxf-rt-rs-extension-providers - ${cxf.version} - - - org.apache.cxf - cxf-rt-ws-security - ${cxf.version} - - - net.sf.ehcache - ehcache-core - - - org.apache.ws.security - wss4j - - - commons-logging - commons-logging - - - - org.wso2.carbon.identity.framework @@ -1303,11 +1256,6 @@ - - org.wso2.carbon.identity.inbound.auth.saml2 - org.wso2.carbon.identity.sso.saml - ${identity.inbound.auth.saml.version} - com.googlecode.json-simple.wso2 json-simple @@ -1358,7 +1306,7 @@ ${bcpkix.wso2.version} - org.wso2.orbit.com.google.code.jscep + io.entgra.com.google.code.jscep jscep ${jscep.version} @@ -1378,6 +1326,11 @@ httpmime ${apache.http.mime.version} + + commons-lang + commons-lang + ${commons-lang.version} + commons-lang.wso2 commons-lang @@ -1403,19 +1356,14 @@ okhttp ${squareup.okhttp3.version} - - com.squareup.okio - okio - ${okio.version} - io.github.openfeign feign-okhttp ${github.openfeign.version} - org.apache.httpcomponents - httpclient + org.apache.httpcomponents.client5 + httpclient5 ${apache.http.client.version} @@ -1446,8 +1394,8 @@ ${commons.httpclient.version} - org.wso2.orbit.org.apache.velocity - velocity + org.apache.velocity + velocity-engine-core ${velocity.version} @@ -1460,12 +1408,6 @@ commons-collections ${commons-collections.version} - - javax - javaee-web-api - 6.0 - provided - @@ -1476,11 +1418,6 @@ - - org.wso2.carbon.analytics-common - org.wso2.carbon.databridge.core - ${carbon.analytics.common.version} - org.wso2.carbon.analytics-common org.wso2.carbon.event.stream.core @@ -1506,16 +1443,6 @@ org.wso2.carbon.event.output.adapter.rdbms ${carbon.analytics.common.version} - - - - - - - - - - org.wso2.carbon.analytics-common org.wso2.carbon.databridge.commons @@ -1533,6 +1460,10 @@ org.wso2.carbon.registry.indexing ${carbon.registry.version} + + com.fasterxml.jackson.core + jackson-annotations + org.wso2.carbon.identity org.wso2.carbon.user.mgt.stub @@ -1565,7 +1496,7 @@ - org.wso2.orbit.org.scannotation + io.entgra.org.scannotation scannotation ${scannotation.version} @@ -1575,6 +1506,11 @@ httpcore ${httpcore.version} + + org.apache.httpcomponents.wso2 + httpclient + ${httpclient.wso2.version} + org.wso2.orbit.org.apache.httpcomponents httpclient @@ -1599,20 +1535,21 @@ ${eclipse.paho.version} - - commons-configuration - commons-configuration - ${commons-configuration.version} - io.swagger swagger-annotations - ${swagger.annotations.version} + ${swagger.version} io.swagger swagger-core ${swagger.version} + + + com.fasterxml.jackson.core + jackson-annotations + + io.swagger @@ -1629,16 +1566,6 @@ org.wso2.carbon.event.output.adapter.core ${carbon.analytics.common.version} - - org.wso2.carbon.analytics - org.wso2.carbon.analytics.datasource.commons - ${carbon.analytics.version} - - - org.wso2.carbon.analytics - org.wso2.carbon.analytics.dataservice.commons - ${carbon.analytics.version} - org.wso2.carbon.analytics-common org.wso2.carbon.event.publisher.stub @@ -1720,9 +1647,15 @@ ${jackson-annotations.version} - org.wso2.orbit.com.fasterxml.jackson.core + com.fasterxml.jackson.core jackson-databind - ${jackson-databind.version} + ${fasterxml.jackson.databind.version} + + + com.fasterxml.jackson.core + jackson-annotations + + @@ -1766,11 +1699,6 @@ wss4j ${org.apache.ws.security.wso2.version} - - org.wso2.carbon.store - org.wso2.store.sso.common - ${carbon.store.sso.common.version} - io.github.openfeign feign-core @@ -1796,16 +1724,6 @@ feign-slf4j ${io.github.openfeign.version} - - org.apache.oltu.oauth2 - org.apache.oltu.oauth2.client - ${oltu.client.version} - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - ${jackson.datatype.joda.version} - org.javassist javassist @@ -1828,7 +1746,7 @@ org.powermock - powermock-api-mockito + powermock-api-mockito2 ${power.mock.version} test @@ -1960,6 +1878,52 @@ failureaccess ${com.google.failureaccess.version} + + org.mockito + mockito-core + ${mokito.version} + + + org.ops4j.pax.logging + pax-logging-api + ${pax.logging.api.version} + + + org.apache.cxf.wso2 + cxf-bundle + ${cxf-bundle.version} + test + + + commons-fileupload.wso2 + commons-fileupload + ${commons-fileupload.version} + + + cglib + cglib-nodep + 3.2.7 + + + org.wso2.carbon + javax.cache.wso2 + 4.6.3-m5 + + + org.apache.felix + org.apache.felix.scr.ds-annotations + ${apache.felix.scr.ds.annotations.version} + + + org.slf4j + slf4j-ext + ${slf4j.ext.version} + + + org.wso2.carbon.commons + org.wso2.carbon.tenant.common + ${carbon.commons.version} + @@ -1995,17 +1959,17 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + 3.8.1 UTF-8 - 1.8 - 1.8 + 11 + 11 org.apache.maven.plugins maven-war-plugin - 2.2 + 3.3.1 org.apache.maven.plugins @@ -2025,30 +1989,17 @@ org.apache.maven.plugins maven-compiler-plugin - 2.3.2 + 3.8.1 UTF-8 - 1.8 - 1.8 + 17 + 17 - - org.apache.felix - maven-scr-plugin - 1.7.2 - - - generate-scr-scrdescriptor - - scr - - - - org.apache.felix maven-bundle-plugin - 4.1.0 + 3.2.0 true NONE @@ -2089,7 +2040,13 @@ org.apache.maven.plugins maven-surefire-plugin - 2.18 + 3.1.2 + + + ${basedir}/target/coverage-reports/jacoco-ut.exec + + + org.apache.maven.plugins @@ -2106,6 +2063,26 @@ jacoco-maven-plugin ${jacoco.maven.plugin.version} + + org.codehaus.mojo + exec-maven-plugin + 1.4.0 + + + org.apache.maven.plugins + maven-antrun-plugin + 1.8 + + + com.google.code.maven-replacer-plugin + replacer + 1.5.2 + + + io.swagger + swagger-codegen-maven-plugin + 2.2.1 + @@ -2113,69 +2090,54 @@ 2.2.1 7.4.0 - 4.6.2 + 4.8.1 [4.5.0, 5.0.0) 5.1.2 - 1.3 - 3.1.3 - 4.4.9 - [1.6.1.wso2v11, 1.7.0) - 1.6.1.wso2v11 + [1.6.1, 1.7.0) + 1.6.1-wso2v85 1.1.0-wso2v10 1.0.0.Final - 4.3.1 - 4.4.2 - 1.1.0 - 4.8.2 + 4.13.1 3.6.200.v20130402-1505 3.3.100.v20120522-1822 - 3.9.1.v20140110-1610 - - 1.2.140.wso2v3 + 3.8.1.v20120830-144521 - 7.0.85.wso2v1 - 7.0.85.wso2v1 - 7.0.34.wso2v2 - - - 4.7.15 + 9.0.71.wso2v1 - 5.18.187 - [5.2.0, 7.0.0) - 6.4.111 - 5.5.2 - 1.0.31 - [1.0.31, 2.0.0) + 5.24.8 + [5.14.0, 6.0.0) + 6.9.6 + 2.1.1 + [2.1.1, 3.0.0) [5.14.0, 6.0.0) [6.0.0, 7.0.0) - [5.3.0, 6.0.0) - 4.9.10 + 4.9.20 - 4.8.21 + 4.8.30 - 1.2.11-wso2v10 + 1.2.11-wso2v25 [1.2.11, 1.3.0) - 1.2.11.wso2v10 + 1.2.11-wso2v25 5.2.4-SNAPSHOT - 4.7.35 + 4.9.2 1.4.0.wso2v1 [1.4.0,2.0.0) 2.4.0.wso2v1 @@ -2183,78 +2145,72 @@ [2.6.0,3.0.0) - 9.0.174 + 9.28.116 [9.0.0, 10.0.0) - 5.2.34 - [5.2.34,6.0.0) + 5.3.5 + [5.3.0,6.0.0) 1.3.25 - [1.3.0,2.0.0) - 2.1.23 + 2.3.5 - 4.7.39 + 4.8.13 ${carbon.registry.version} [4.7.0, 5.0.0) - 3.3.6 - + 3.5.5 1.1.wso2v1 - 1.9.0 + 1.9.13 20220924 2.4.5 - 27.0.1-jre - 1.60.0.wso2v1 - 1.60.0.wso2v1 - [1.52.0,1.70.0) + 1.70.0.wso2v1 + 1.70.0.wso2v1 + [1.52.0,1.80.0) - 2.3.0.wso2v2 + 2.3.0.entgrav2 3.0.0.wso2v1 1.3 - 2.8.5 - 31.0.1-jre + 2.9.1 + 32.1.3-jre 4.12.0 3.6.0 - 9.3.1 + 11.0 1.1.1 1.2 - 4.5.13 + 5.2.1 - 4.4.10 - 4.5.8 + 4.4.13 + 4.5.10 1.9 3.1.1 2.0.4.wso2v4 - - github-scm - - 1.0.3.wso2v1 + 1.0.3.entgrav1 [1.0.3, 2.0.0) 1.5.6.wso2v1 4.3.1.wso2v2 [4.3.1, 5.0.0) - 4.3.3.wso2v1 + 4.4.16.wso2v1 3.1.0.wso2v2 + 4.2.5.wso2v1 - 1.7.0.wso2v1 + 2.3 2.4.0.wso2v1 3.2.0.wso2v1 (3.2.0, 3.3.0] - 1.8 5.1.34 @@ -2265,13 +2221,12 @@ 1.0.2 - 7.3.0.wso2v1 + 7.9.0.wso2v1 [7.3, 8) - 2.0.1 - 1.5.10 - 1.6.1 + 2.1.1 + 1.6.9 4.0.1 @@ -2281,14 +2236,12 @@ 2.8.2.wso2v1 1.2.0.wso2v1 - 5.0.2.Final + 5.1.2.Final [0.0.0,1.0.0) [0.0.0,1.0.0) 1.8.10.wso2v2 - 4.2.1 - [1.0.0, 1.1.0) 1.7.0 @@ -2300,55 +2253,46 @@ 1.7 - 2.1.7-wso2v227 - 1.5.11.wso2v15 - - - 1.5.1 + 4.0.0.wso2v20_25 + 1.5.11-wso2v18 - 9.3.1 + 11.0 [9.3.1,10.0.0) - - 1.0.1 - 2.1.5 1.9 (1.9,2.0] - 3.26.0-GA + 3.18.1-GA true - 0.7.8 - 0.7.5.201505241946 + 0.8.10 1.0b3 - 1.7.4 + 2.0.2 1.4.0.wso2v1 1.7.25 + 1.7.29 1.21 2.6.5 - 1.7.6 - v12.18.1 3.1.0 - 7.0.85 + 9.0.24 1.1 - 1.13.1 - 5.1.13.RELEASE + 5.3.23 2.7.18 + 2.6.1.wso2v2 [1.6.0, 2.0.0) [1.2.0,1.3.0) - 4.2.0 - 2.3.1 + 2.23.4 2.8.1.wso2v2 4.3.1.wso2v1 - 1.4.199.wso2v1 + 2.1.214.wso2v1 1.1.3 1.20.0.wso2v1 @@ -2360,6 +2304,17 @@ 0.30.0.wso2v1 0.30.0 0.30.0 + + 1.11.2 + 2.3.1.wso2v1 + 2.4 + 1.2.2.wso2v1 + [9.0,10) + 1.2.4 + [4.7.0, 4.9.0) + [1.0.1, 2.0.0) + [4.7.0, 5.0.0) + 2.14.1