mirror of
https://repository.entgra.net/community/device-mgt-core.git
synced 2025-10-06 02:01:45 +00:00
Migrate to APIM 420
This commit is contained in:
commit
e79a512cf6
@ -37,10 +37,7 @@
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
@ -61,7 +58,6 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-antrun-plugin</artifactId>
|
||||
<version>1.7</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>compile</phase>
|
||||
@ -97,9 +93,8 @@
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<groupId>org.apache.cxf.wso2</groupId>
|
||||
<artifactId>cxf-bundle</artifactId>
|
||||
<version>3.0.0-milestone2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -133,8 +128,8 @@
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.logging</artifactId>
|
||||
<groupId>org.ops4j.pax.logging</groupId>
|
||||
<artifactId>pax-logging-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -299,7 +294,7 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-api-mockito</artifactId>
|
||||
<artifactId>powermock-api-mockito2</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -333,6 +328,11 @@
|
||||
<artifactId>io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<artifactId>io.entgra.device.mgt.core.application.mgt.common</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
|
||||
@ -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(
|
||||
|
||||
@ -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;
|
||||
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -35,6 +35,14 @@
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
@ -48,12 +56,6 @@
|
||||
<Export-Package>
|
||||
io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common.*
|
||||
</Export-Package>
|
||||
<Import-Package>
|
||||
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
|
||||
</Import-Package>
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
@ -35,10 +35,6 @@
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-scr-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
@ -65,6 +61,14 @@
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
@ -77,15 +81,47 @@
|
||||
<Bundle-Description>Grafana API Management Core Bundle</Bundle-Description>
|
||||
<Private-Package>io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.internal</Private-Package>
|
||||
<Import-Package>
|
||||
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)"
|
||||
</Import-Package>
|
||||
<Export-Package>
|
||||
!io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.internal,
|
||||
@ -103,28 +139,31 @@
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi.services</artifactId>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>org.apache.felix.scr.ds-annotations</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.orbit.org.scannotation</groupId>
|
||||
<groupId>io.entgra.org.scannotation</groupId>
|
||||
<artifactId>scannotation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<artifactId>io.entgra.device.mgt.core.device.mgt.common</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<artifactId>io.entgra.device.mgt.core.application.mgt.common</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.utils</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.logging</artifactId>
|
||||
<groupId>org.ops4j.pax.logging</groupId>
|
||||
<artifactId>pax-logging-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -139,6 +178,12 @@
|
||||
<dependency>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<artifactId>io.entgra.device.mgt.core.device.mgt.core</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
@ -147,17 +192,22 @@
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents.wso2</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>4.1.1.wso2v1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<groupId>org.apache.httpcomponents.client5</groupId>
|
||||
<artifactId>httpclient5</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<artifactId>io.entgra.device.mgt.core.identity.jwt.client.extension</artifactId>
|
||||
<scope>provided</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
@ -173,7 +223,7 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-api-mockito</artifactId>
|
||||
<artifactId>powermock-api-mockito2</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
@ -191,8 +241,8 @@
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database.wso2</groupId>
|
||||
<artifactId>h2-database-engine</artifactId>
|
||||
<groupId>org.wso2.orbit.com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -221,7 +271,7 @@
|
||||
<artifactId>org.wso2.carbon.registry.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat.wso2</groupId>
|
||||
<groupId>org.wso2.orbit.org.apache.tomcat</groupId>
|
||||
<artifactId>jdbc-pool</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -240,14 +290,6 @@
|
||||
<groupId>org.apache.ws.commons.axiom.wso2</groupId>
|
||||
<artifactId>axiom</artifactId>
|
||||
</dependency>
|
||||
<!--dependency>
|
||||
<groupId>org.apache.ws.commons.axiom.wso2</groupId>
|
||||
<artifactId>axiom-impl</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.ws.commons.axiom.wso2</groupId>
|
||||
<artifactId>axiom</artifactId>
|
||||
</dependency-->
|
||||
<dependency>
|
||||
<groupId>org.apache.axis2.wso2</groupId>
|
||||
<artifactId>axis2</artifactId>
|
||||
@ -257,11 +299,11 @@
|
||||
<artifactId>org.wso2.carbon.identity.oauth.stub</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.tomcat</groupId>
|
||||
<groupId>org.wso2.orbit.org.apache.tomcat</groupId>
|
||||
<artifactId>tomcat</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.tomcat</groupId>
|
||||
<groupId>org.wso2.orbit.org.apache.tomcat</groupId>
|
||||
<artifactId>tomcat-servlet-api</artifactId>
|
||||
</dependency>
|
||||
|
||||
@ -276,23 +318,19 @@
|
||||
<groupId>commons-collections.wso2</groupId>
|
||||
<artifactId>commons-collections</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<artifactId>io.entgra.device.mgt.core.transport.mgt.email.sender.core</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.swagger</groupId>
|
||||
<artifactId>swagger-annotations</artifactId>
|
||||
@ -321,9 +359,12 @@
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.orbit.javax.xml.bind</groupId>
|
||||
<artifactId>jaxb-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
|
||||
</project>
|
||||
|
||||
@ -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");
|
||||
|
||||
@ -27,9 +27,14 @@
|
||||
<artifactId>io.entgra.device.mgt.core.apimgt.analytics.extension</artifactId>
|
||||
<packaging>bundle</packaging>
|
||||
<name>Entgra - API mgt analytics extension</name>
|
||||
<url>http://wso2.org</url>
|
||||
<url>https://entgra.io</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>org.apache.felix.scr.ds-annotations</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.core</artifactId>
|
||||
@ -40,8 +45,7 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.velocity</groupId>
|
||||
<artifactId>velocity</artifactId>
|
||||
<version>1.7</version>
|
||||
<artifactId>velocity-engine-core</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
@ -57,8 +61,12 @@
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-scr-plugin</artifactId>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
@ -73,10 +81,11 @@
|
||||
<Private-Package>io.entgra.device.mgt.core.apimgt.application.extension.internal</Private-Package>
|
||||
<Import-Packages>
|
||||
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)"
|
||||
</Import-Packages>
|
||||
<Export-Package>
|
||||
io.entgra.device.mgt.core.apimgt.analytics.extension.*
|
||||
|
||||
@ -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 {
|
||||
|
||||
|
||||
@ -31,20 +31,18 @@
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - API Management Annotations</name>
|
||||
<description>WSO2 Carbon - API Management Custom Annotation Module</description>
|
||||
<url>http://wso2.org</url>
|
||||
<url>https://entgra.io</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi</artifactId>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>org.apache.felix.scr.ds-annotations</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi.services</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.logging</artifactId>
|
||||
<groupId>org.ops4j.pax.logging</groupId>
|
||||
<artifactId>pax-logging-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
@ -54,13 +52,16 @@
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-scr-plugin</artifactId>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
<version>1.4.0</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<instructions>
|
||||
@ -71,15 +72,6 @@
|
||||
<Export-Package>
|
||||
io.entgra.device.mgt.core.apimgt.annotations.*
|
||||
</Export-Package>
|
||||
<Import-Package>
|
||||
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
|
||||
</Import-Package>
|
||||
<Embed-Dependency>
|
||||
scribe;scope=compile|runtime;inline=false;
|
||||
</Embed-Dependency>
|
||||
|
||||
@ -30,7 +30,7 @@
|
||||
<packaging>war</packaging>
|
||||
<name>WSO2 Carbon - API Application Management API</name>
|
||||
<description>This module provides capability to create api manager application.</description>
|
||||
<url>http://wso2.org</url>
|
||||
<url>https://entgra.io</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
@ -164,16 +164,12 @@
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<encoding>UTF-8</encoding>
|
||||
<source>${wso2.maven.compiler.source}</source>
|
||||
<target>${wso2.maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>2.2</version>
|
||||
<configuration>
|
||||
<warName>${project.artifactId}</warName>
|
||||
</configuration>
|
||||
|
||||
@ -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) {
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -18,13 +18,13 @@
|
||||
|
||||
package io.entgra.device.mgt.core.apimgt.application.extension.api.util;
|
||||
|
||||
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.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.api.Resource;
|
||||
import org.wso2.carbon.registry.core.Registry;
|
||||
import org.wso2.carbon.registry.core.exceptions.RegistryException;
|
||||
|
||||
@ -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<String> 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<String> getSupportedGrantTypes() {
|
||||
return supportedGrantTypes;
|
||||
}
|
||||
|
||||
public void setSupportedGrantTypes(ArrayList<String> supportedGrantTypes) {
|
||||
this.supportedGrantTypes = supportedGrantTypes;
|
||||
}
|
||||
}
|
||||
|
||||
@ -31,9 +31,14 @@
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - API Application Management</name>
|
||||
<description>This module provides capability to create api manager application.</description>
|
||||
<url>http://wso2.org</url>
|
||||
<url>https://entgra.io</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>org.apache.felix.scr.ds-annotations</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.registry.core</artifactId>
|
||||
@ -47,8 +52,9 @@
|
||||
<artifactId>org.wso2.carbon.utils</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.logging</artifactId>
|
||||
<groupId>org.ops4j.pax.logging</groupId>
|
||||
<artifactId>pax-logging-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.apimgt</groupId>
|
||||
@ -72,6 +78,17 @@
|
||||
<artifactId>io.entgra.device.mgt.core.identity.jwt.client.extension</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<artifactId>io.entgra.device.mgt.core.apimgt.extension.rest.api</artifactId>
|
||||
<!-- <scope>provided</scope>-->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<artifactId>io.entgra.device.mgt.core.device.mgt.common</artifactId>
|
||||
<!-- <scope>provided</scope>-->
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@ -86,8 +103,12 @@
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-scr-plugin</artifactId>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
@ -101,30 +122,32 @@
|
||||
<Bundle-Description>API Management Application Bundle</Bundle-Description>
|
||||
<Private-Package>io.entgra.device.mgt.core.apimgt.application.extension.internal</Private-Package>
|
||||
<Import-Packages>
|
||||
org.apache.commons.lang;version="[2.6,3)",
|
||||
org.apache.commons.logging;version="[1.2,2)",
|
||||
org.json.simple,
|
||||
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.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;version="[1.1,2)",
|
||||
org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
|
||||
org.osgi.service.*;version="${imp.package.version.osgi.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)"
|
||||
</Import-Packages>
|
||||
<Export-Package>
|
||||
!io.entgra.device.mgt.core.apimgt.application.extension.internal,
|
||||
|
||||
@ -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<String> supportedGrantTypes,
|
||||
String callbackUrl,
|
||||
boolean isMappingRequired) throws APIManagerException;
|
||||
|
||||
/**
|
||||
* To get access token for given scopes and for the given validity period
|
||||
|
||||
@ -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,237 @@ 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<String> 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<String, String> headerParams = new HashMap<>();
|
||||
if (!"carbon.super".equals(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true))) {
|
||||
headerParams.put("X-WSO2-Tenant", "carbon.super");
|
||||
}
|
||||
|
||||
Map<String, APIInfo> uniqueApiSet = new HashMap<>();
|
||||
if (tags != null) {
|
||||
for (String tag : tags) {
|
||||
Map<String, String> queryParams = new HashMap<>();
|
||||
queryParams.put("tag", tag);
|
||||
|
||||
APIInfo[] apiInfos = consumerRESTAPIServices.getAllApis(apiApplicationInfo, queryParams, headerParams);
|
||||
Arrays.stream(apiInfos).forEach(apiInfo -> uniqueApiSet.putIfAbsent(apiInfo.getName(), apiInfo));
|
||||
}
|
||||
}
|
||||
|
||||
List<APIInfo> uniqueApiList = new ArrayList<>(uniqueApiSet.values());
|
||||
|
||||
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<io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application> 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()));
|
||||
}
|
||||
|
||||
if (!uniqueApiList.isEmpty()) {
|
||||
addSubscriptions(application, uniqueApiList, apiApplicationInfo);
|
||||
}
|
||||
|
||||
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<APIInfo> uniqueApiList,
|
||||
ApiApplicationInfo apiApplicationInfo, String keyType, String validityTime,
|
||||
ArrayList<String> 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);
|
||||
|
||||
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 {
|
||||
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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
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 (MetadataManagementException e) {
|
||||
String msg = "Error occurred while creating meta data for meta key: " + applicationName;
|
||||
log.error(msg, e);
|
||||
throw new APIManagerException(msg, e);
|
||||
} 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 (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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* 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<APIInfo>}
|
||||
* @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.
|
||||
*/
|
||||
@Override
|
||||
public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String tags[],
|
||||
String keyType, String username, boolean isAllowedAllDomains, String validityTime)
|
||||
throws APIManagerException {
|
||||
private void addSubscriptions(
|
||||
io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application,
|
||||
List<APIInfo> apiInfos, ApiApplicationInfo apiApplicationInfo)
|
||||
throws BadRequestException, UnexpectedResponseException, APIServicesException {
|
||||
|
||||
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, "");
|
||||
ConsumerRESTAPIServices consumerRESTAPIServices =
|
||||
APIApplicationManagerExtensionDataHolder.getInstance().getConsumerRESTAPIServices();
|
||||
|
||||
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);
|
||||
}
|
||||
//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);
|
||||
}
|
||||
List<Subscription> 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);
|
||||
});
|
||||
|
||||
Set<SubscribedAPI> subscribedAPIs =
|
||||
apiConsumer.getSubscribedAPIs(subscriber, applicationName, "");
|
||||
|
||||
log.info("Already subscribed API count: " + subscribedAPIs.size());
|
||||
|
||||
// subscribe to apis.
|
||||
Set<String> tempApiIds = new HashSet<>();
|
||||
APIConsumer apiConsumerAPIPublishedTenant = apiConsumer;
|
||||
if (tags != null && tags.length > 0) {
|
||||
for (String tag : tags) {
|
||||
boolean startedTenantFlow = false;
|
||||
Set<API> 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);
|
||||
}
|
||||
|
||||
apisWithTag = apiConsumerAPIPublishedTenant.getAPIsWithTag(tag, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
|
||||
startedTenantFlow = true;
|
||||
}
|
||||
|
||||
Set<ApiTypeWrapper> 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();
|
||||
}
|
||||
|
||||
/** 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<APIKey> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<String> allowedDomains = new ArrayList<>();
|
||||
if (isAllowedAllDomains) {
|
||||
allowedDomains.add(ApiApplicationConstants.ALLOWED_DOMAINS);
|
||||
} else {
|
||||
allowedDomains.add(APIManagerUtil.getTenantDomain());
|
||||
}
|
||||
|
||||
APIAdmin apiAdmin = new APIAdminImpl();
|
||||
String keyManagerId = null;
|
||||
try {
|
||||
List<KeyManagerConfigurationDTO> 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<String, Object> 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);
|
||||
}
|
||||
} catch (APIManagementException e) {
|
||||
throw new APIManagerException("Failed to create api application for tenant: " + tenantDomain, e);
|
||||
}
|
||||
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 +341,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 +361,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 +381,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 +391,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;
|
||||
}
|
||||
}
|
||||
|
||||
@ -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.
|
||||
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -34,14 +34,19 @@
|
||||
<url>https://entgra.io</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>org.apache.felix.scr.ds-annotations</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-httpclient.wso2</groupId>
|
||||
<artifactId>commons-httpclient</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.logging</artifactId>
|
||||
<groupId>org.ops4j.pax.logging</groupId>
|
||||
<artifactId>pax-logging-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -54,17 +59,6 @@
|
||||
<artifactId>org.wso2.carbon.core</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi.services</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.json.wso2</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
@ -93,13 +87,16 @@
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-scr-plugin</artifactId>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
<version>5.1.7</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<instructions>
|
||||
|
||||
@ -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;
|
||||
|
||||
|
||||
@ -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 {
|
||||
|
||||
@ -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<String, String> queryParams, Map<String, String> headerParams)
|
||||
throws APIServicesException, BadRequestException, UnexpectedResponseException;
|
||||
|
||||
Subscription createSubscription(ApiApplicationInfo apiApplicationInfo, Subscription subscriptions)
|
||||
throws APIServicesException, BadRequestException, UnexpectedResponseException;
|
||||
|
||||
Subscription[] createSubscriptions(ApiApplicationInfo apiApplicationInfo, List<Subscription> 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<String> supportedGrantTypes, String callbackUrl)
|
||||
throws APIServicesException, BadRequestException, UnexpectedResponseException;
|
||||
|
||||
KeyManager[] getAllKeyManagers(ApiApplicationInfo apiApplicationInfo)
|
||||
throws APIServicesException, BadRequestException, UnexpectedResponseException;
|
||||
}
|
||||
@ -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<String, String> queryParams, Map<String, String> headerParams)
|
||||
throws APIServicesException, BadRequestException, UnexpectedResponseException {
|
||||
|
||||
StringBuilder getAPIsURL = new StringBuilder(endPointPrefix + Constants.DEV_PORTAL_API);
|
||||
|
||||
for (Map.Entry<String, String> 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<String, String> 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<Subscription> 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<String> 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;
|
||||
}
|
||||
}
|
||||
@ -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;
|
||||
|
||||
|
||||
@ -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<String> throttlingPolicies;
|
||||
private JSONObject advertiseInfo;
|
||||
private JSONObject businessInformation;
|
||||
private boolean isSubscriptionAvailable;
|
||||
private String monetizationLabel;
|
||||
private String gatewayVendor;
|
||||
private List<String> 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<String> getThrottlingPolicies() {
|
||||
return throttlingPolicies;
|
||||
}
|
||||
|
||||
public void setThrottlingPolicies(List<String> 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<String> getAdditionalProperties() {
|
||||
return additionalProperties;
|
||||
}
|
||||
|
||||
public void setAdditionalProperties(List<String> additionalProperties) {
|
||||
this.additionalProperties = additionalProperties;
|
||||
}
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
@ -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<String> groups;
|
||||
private int subscriptionCount;
|
||||
private List<String> keys;
|
||||
private Map<String, String> attributes;
|
||||
private List<Scopes> 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<String> getGroups() {
|
||||
return groups;
|
||||
}
|
||||
|
||||
public void setGroups(List<String> groups) {
|
||||
this.groups = groups;
|
||||
}
|
||||
|
||||
public int getSubscriptionCount() {
|
||||
return subscriptionCount;
|
||||
}
|
||||
|
||||
public void setSubscriptionCount(int subscriptionCount) {
|
||||
this.subscriptionCount = subscriptionCount;
|
||||
}
|
||||
|
||||
public List<String> getKeys() {
|
||||
return keys;
|
||||
}
|
||||
|
||||
public void setKeys(List<String> keys) {
|
||||
this.keys = keys;
|
||||
}
|
||||
|
||||
public Map<String, String> getAttributes() {
|
||||
return attributes;
|
||||
}
|
||||
|
||||
public void setAttributes(Map<String, String> attributes) {
|
||||
this.attributes = attributes;
|
||||
}
|
||||
|
||||
public List<Scopes> getSubscriptionScopes() {
|
||||
return subscriptionScopes;
|
||||
}
|
||||
|
||||
public void setSubscriptionScopes(List<Scopes> 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;
|
||||
}
|
||||
}
|
||||
@ -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<String> 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<String> getValues() {
|
||||
return values;
|
||||
}
|
||||
|
||||
public void setValues(List<String> values) {
|
||||
this.values = values;
|
||||
}
|
||||
|
||||
public String getDefaults() {
|
||||
return defaults;
|
||||
}
|
||||
|
||||
public void setDefaults(String defaults) {
|
||||
this.defaults = defaults;
|
||||
}
|
||||
}
|
||||
@ -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<String> supportedGrantTypes;
|
||||
|
||||
public String getCallbackUrl() {
|
||||
return callbackUrl;
|
||||
}
|
||||
|
||||
public void setCallbackUrl(String callbackUrl) {
|
||||
this.callbackUrl = callbackUrl;
|
||||
}
|
||||
|
||||
public ArrayList<String> getSupportedGrantTypes() {
|
||||
return supportedGrantTypes;
|
||||
}
|
||||
|
||||
public void setSupportedGrantTypes(ArrayList<String> supportedGrantTypes) {
|
||||
this.supportedGrantTypes = supportedGrantTypes;
|
||||
}
|
||||
}
|
||||
@ -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<String> 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<String> getSupportedGrantTypes() {
|
||||
return supportedGrantTypes;
|
||||
}
|
||||
|
||||
public void setSupportedGrantTypes(List<String> 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;
|
||||
}
|
||||
}
|
||||
@ -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<String> 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<ApplicationConfigurations> 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<String> getAvailableGrantTypes() {
|
||||
return availableGrantTypes;
|
||||
}
|
||||
|
||||
public void setAvailableGrantTypes(List<String> 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<ApplicationConfigurations> getApplicationConfiguration() {
|
||||
return applicationConfiguration;
|
||||
}
|
||||
|
||||
public void setApplicationConfiguration(List<ApplicationConfigurations> applicationConfiguration) {
|
||||
this.applicationConfiguration = applicationConfiguration;
|
||||
}
|
||||
|
||||
public JSONObject getAdditionalProperties() {
|
||||
return additionalProperties;
|
||||
}
|
||||
|
||||
public void setAdditionalProperties(JSONObject additionalProperties) {
|
||||
this.additionalProperties = additionalProperties;
|
||||
}
|
||||
}
|
||||
@ -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<String> 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<String> getRoles() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
public void setRoles(List<String> roles) {
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
@ -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";
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
@ -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");
|
||||
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -29,18 +29,16 @@
|
||||
<packaging>war</packaging>
|
||||
<name>WSO2 Carbon - API Key Management API</name>
|
||||
<description>This module extends the API manager's key management apis.</description>
|
||||
<url>http://wso2.org</url>
|
||||
<url>https://entgra.io</url>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<configuration>
|
||||
<packagingExcludes>WEB-INF/lib/*cxf*.jar</packagingExcludes>
|
||||
|
||||
@ -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<String> 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<String> getSupportedGrantTypes() {
|
||||
return supportedGrantTypes;
|
||||
}
|
||||
|
||||
public void setSupportedGrantTypes(ArrayList<String> supportedGrantTypes) {
|
||||
this.supportedGrantTypes = supportedGrantTypes;
|
||||
}
|
||||
}
|
||||
|
||||
@ -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;
|
||||
|
||||
|
||||
@ -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();
|
||||
|
||||
@ -19,9 +19,9 @@
|
||||
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core"
|
||||
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
|
||||
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
|
||||
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
|
||||
|
||||
<jaxrs:server id="services" address="/">
|
||||
<jaxrs:serviceBeans>
|
||||
|
||||
@ -30,9 +30,14 @@
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - API Key Management</name>
|
||||
<description>This module extends the API manager's key management.</description>
|
||||
<url>http://wso2.org</url>
|
||||
<url>https://entgra.io</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>org.apache.felix.scr.ds-annotations</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec.wso2</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
@ -50,18 +55,26 @@
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<artifactId>io.entgra.device.mgt.core.device.mgt.common</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<artifactId>io.entgra.device.mgt.core.apimgt.extension.rest.api</artifactId>
|
||||
<!-- <scope>provided</scope>-->
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-scr-plugin</artifactId>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
<version>5.1.7</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<instructions>
|
||||
@ -71,10 +84,41 @@
|
||||
<Bundle-Description>API Management Application Bundle</Bundle-Description>
|
||||
<Private-Package>io.entgra.device.mgt.core.apimgt.keymgt.extension.internal</Private-Package>
|
||||
<Import-Packages>
|
||||
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)"
|
||||
</Import-Packages>
|
||||
<Export-Package>
|
||||
!io.entgra.device.mgt.core.apimgt.keymgt.extension.internal,
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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 {
|
||||
|
||||
|
||||
@ -28,5 +28,9 @@ public class KeyMgtException extends Exception {
|
||||
public KeyMgtException(String errorMessage) {
|
||||
super(errorMessage);
|
||||
}
|
||||
|
||||
public KeyMgtException(String errorMessage, Exception e) {
|
||||
super(errorMessage, e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@ -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<String> supportedGrantTypes, String callbackUrl) throws KeyMgtException;
|
||||
|
||||
/***
|
||||
* This method will handle the access token requests
|
||||
|
||||
@ -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<String> 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<String> 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<String> 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();
|
||||
}
|
||||
|
||||
|
||||
@ -31,32 +31,34 @@
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - API Management Webapp Publisher</name>
|
||||
<description>WSO2 Carbon - API Management Webapp Publisher</description>
|
||||
<url>http://wso2.org</url>
|
||||
<url>https://entgra.io</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>org.apache.felix.scr.ds-annotations</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-api-mockito</artifactId>
|
||||
<artifactId>powermock-api-mockito2</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi.services</artifactId>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.tomcat</groupId>
|
||||
<groupId>org.wso2.orbit.org.apache.tomcat</groupId>
|
||||
<artifactId>tomcat</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.tomcat</groupId>
|
||||
<groupId>org.wso2.orbit.org.apache.tomcat</groupId>
|
||||
<artifactId>tomcat-servlet-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -64,8 +66,9 @@
|
||||
<artifactId>org.wso2.carbon.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.logging</artifactId>
|
||||
<groupId>org.ops4j.pax.logging</groupId>
|
||||
<artifactId>pax-logging-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
@ -80,7 +83,7 @@
|
||||
<artifactId>gson</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.orbit.org.scannotation</groupId>
|
||||
<groupId>io.entgra.org.scannotation</groupId>
|
||||
<artifactId>scannotation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -118,8 +121,8 @@
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database.wso2</groupId>
|
||||
<artifactId>h2-database-engine</artifactId>
|
||||
<groupId>org.wso2.orbit.com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -134,19 +137,27 @@
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<artifactId>io.entgra.device.mgt.core.device.mgt.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.orbit.javax.xml.bind</groupId>
|
||||
<artifactId>jaxb-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-scr-plugin</artifactId>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
<version>1.4.0</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<instructions>
|
||||
@ -161,53 +172,45 @@
|
||||
io.entgra.device.mgt.core.apimgt.webapp.publisher.*
|
||||
</Export-Package>
|
||||
<Import-Package>
|
||||
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)"
|
||||
</Import-Package>
|
||||
<Embed-Dependency>
|
||||
jsr311-api;scope=compile|runtime;inline=false
|
||||
|
||||
@ -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<String> 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<ApiScope> 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<String> 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<String> 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<ApiScope> 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<String> 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<String> 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)));
|
||||
|
||||
@ -20,6 +20,9 @@ package io.entgra.device.mgt.core.apimgt.webapp.publisher;
|
||||
|
||||
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;
|
||||
@ -30,25 +33,25 @@ import io.entgra.device.mgt.core.device.mgt.core.config.permission.DefaultPermis
|
||||
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 io.entgra.device.mgt.core.apimgt.webapp.publisher.exception.APIManagerPublisherException;
|
||||
import io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
|
||||
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<APIConfig> failedAPIsStack = new Stack<>();
|
||||
private static Stack<APIConfig> currentAPIsStack;
|
||||
private static final Gson gson = new Gson();
|
||||
|
||||
private static final Stack<APIConfig> failedAPIsStack = new Stack<>();
|
||||
private static int retryTime = 2000;
|
||||
private static Stack<APIConfig> currentAPIsStack;
|
||||
private final List<String> publishedAPIs = new ArrayList<>();
|
||||
private APIPublisherService publisher;
|
||||
|
||||
@Override
|
||||
@ -61,77 +64,94 @@ public class APIPublisherStartupHandler implements ServerStartupObserver {
|
||||
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<APIConfig> 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<APIConfig> 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 {
|
||||
PrivilegedCarbonContext.startTenantFlow();
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
|
||||
updateScopeMetadataEntryWithDefaultScopes();
|
||||
} finally {
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
|
||||
// execute after api publishing
|
||||
for (PostApiPublishingObsever observer : APIPublisherDataHolder.getInstance().getPostApiPublishingObseverList()) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Executing " + observer.getClass().getName());
|
||||
}
|
||||
observer.execute();
|
||||
}
|
||||
log.info("Finish executing PostApiPublishingObsevers");
|
||||
}
|
||||
|
||||
try {
|
||||
publisher.updateScopeRoleMapping();
|
||||
publisher.addDefaultScopesIfNotExist();
|
||||
} catch (APIManagerPublisherException e) {
|
||||
log.error("failed to update scope role mapping.", e);
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
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<APIConfig> apis, Stack<APIConfig> 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);
|
||||
@ -144,34 +164,42 @@ public class APIPublisherStartupHandler implements ServerStartupObserver {
|
||||
* will create that entry and update the value with default permissions.
|
||||
*/
|
||||
private void updateScopeMetadataEntryWithDefaultScopes() {
|
||||
Map<String, String> permScopeMap = APIPublisherDataHolder.getInstance().getPermScopeMapping();
|
||||
Metadata permScopeMapping;
|
||||
|
||||
MetadataManagementService metadataManagementService = APIPublisherDataHolder.getInstance().getMetadataManagementService();
|
||||
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
|
||||
DefaultPermissions defaultPermissions = deviceManagementConfig.getDefaultPermissions();
|
||||
|
||||
try {
|
||||
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
|
||||
DefaultPermissions defaultPermissions = deviceManagementConfig.getDefaultPermissions();
|
||||
Metadata permScopeMapping = metadataManagementService.retrieveMetadata(Constants.PERM_SCOPE_MAPPING_META_KEY);
|
||||
Map<String, String> permScopeMap = (permScopeMapping != null) ? gson.fromJson(permScopeMapping.getMetaValue(), HashMap.class) :
|
||||
new HashMap<>();
|
||||
for (DefaultPermission defaultPermission : defaultPermissions.getDefaultPermissions()) {
|
||||
permScopeMap.putIfAbsent(defaultPermission.getName(),
|
||||
defaultPermission.getScopeMapping().getKey());
|
||||
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<>();
|
||||
}
|
||||
|
||||
APIPublisherDataHolder.getInstance().setPermScopeMapping(permScopeMap);
|
||||
if (permScopeMapping != null) {
|
||||
permScopeMapping.setMetaValue(gson.toJson(permScopeMap));
|
||||
metadataManagementService.updateMetadata(permScopeMapping);
|
||||
return;
|
||||
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));
|
||||
metadataManagementService.createMetadata(permScopeMapping);
|
||||
|
||||
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 (MetadataManagementException e) {
|
||||
log.error("Error encountered while updating permission scope mapping metadata with default scopes");
|
||||
} catch (MetadataKeyAlreadyExistsException e) {
|
||||
log.error("Metadata entry already exists for " + Constants.PERM_SCOPE_MAPPING_META_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -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<APIResourceConfiguration> getAPIResourceConfiguration(StandardContext standardContext, ServletContext servletContext)
|
||||
throws IOException, ClassNotFoundException {
|
||||
List<APIResourceConfiguration> apiResourceConfigurations = new ArrayList<>();
|
||||
String profile = System.getProperty(PROPERTY_PROFILE);
|
||||
if (WebappPublisherConfig.getInstance().getProfiles().getProfile().contains(profile.toLowerCase())) {
|
||||
AnnotationProcessor annotationProcessor = new AnnotationProcessor(standardContext);
|
||||
Set<String> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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<APIConfig> unpublishedApis = new Stack<>();
|
||||
private Map<String, String> permScopeMapping;
|
||||
private Map<String, String> permScopeMapping = new HashMap<>();
|
||||
private APIApplicationServices apiApplicationServices;
|
||||
private PublisherRESTAPIServices publisherRESTAPIServices;
|
||||
private MetadataManagementService metadataManagementService;
|
||||
|
||||
@ -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");
|
||||
|
||||
@ -17,127 +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.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())) {
|
||||
|
||||
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);
|
||||
|
||||
if (isManagedApi) {
|
||||
if (WebappPublisherConfig.getInstance().isPublished() || WebappPublisherConfig.getInstance().isEnabledUpdateApi()) {
|
||||
|
||||
String profile = System.getProperty(PROPERTY_PROFILE);
|
||||
if (WebappPublisherConfig.getInstance().getProfiles().getProfile().contains(profile.toLowerCase())
|
||||
&& isManagedApi) {
|
||||
try {
|
||||
AnnotationProcessor annotationProcessor = new AnnotationProcessor(context);
|
||||
Set<String> annotatedSwaggerAPIClasses = annotationProcessor.
|
||||
scanStandardContext(io.swagger.annotations.SwaggerDefinition.class.getName());
|
||||
List<APIResourceConfiguration> apiDefinitions = annotationProcessor.extractAPIInfo(servletContext,
|
||||
annotatedSwaggerAPIClasses);
|
||||
List<APIResourceConfiguration> apiResourceConfigurations =
|
||||
APIPublisherUtil.getAPIResourceConfiguration(context, servletContext);
|
||||
|
||||
APIPublisherDataHolder apiPublisherDataHolder = APIPublisherDataHolder.getInstance();
|
||||
MetadataManagementService metadataManagementService =
|
||||
apiPublisherDataHolder.getMetadataManagementService();
|
||||
Metadata metadata = metadataManagementService.retrieveMetadata("perm-scope-mapping");
|
||||
if (metadata != null) {
|
||||
HashMap<String, String> permScopeMapping =
|
||||
new Gson().fromJson(metadata.getMetaValue().toString(), HashMap.class);
|
||||
apiPublisherDataHolder.setPermScopeMapping(permScopeMapping);
|
||||
}
|
||||
|
||||
Map<String, String> 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());
|
||||
|
||||
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");
|
||||
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) {
|
||||
@ -150,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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.*;
|
||||
|
||||
@ -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}
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -27,7 +27,7 @@
|
||||
<EveryOneRoleName>everyone</EveryOneRoleName>
|
||||
<ReadOnly>false</ReadOnly>
|
||||
<MaxUserNameListLength>500</MaxUserNameListLength>
|
||||
<Property name="url">jdbc:h2:target/databasetest/CARBON_TEST</Property>
|
||||
<Property name="url">jdbc:h2:./target/databasetest/CARBON_TEST</Property>
|
||||
<Property name="driverName">org.h2.Driver</Property>
|
||||
<Property name="maxActive">50</Property>
|
||||
<Property name="maxWait">60000</Property>
|
||||
|
||||
@ -1,142 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ 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.
|
||||
-->
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<artifactId>apimgt-extensions</artifactId>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<version>5.0.0-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.apimgt.handlers</artifactId>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - API Security Handler Component</name>
|
||||
<description>WSO2 Carbon - API Management Security Handler Module</description>
|
||||
<url>http://wso2.org</url>
|
||||
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.logging</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.synapse</groupId>
|
||||
<artifactId>synapse-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.ws.security.wso2</groupId>
|
||||
<artifactId>wss4j</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<artifactId>io.entgra.device.mgt.core.certificate.mgt.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.json.wso2</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-scr-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
<version>1.4.0</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<instructions>
|
||||
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
|
||||
<Bundle-Name>${project.artifactId}</Bundle-Name>
|
||||
<Bundle-Version>${io.entgra.device.mgt.core.version}</Bundle-Version>
|
||||
<Bundle-Description>WSO2 Carbon - API Security Handler Component</Bundle-Description>
|
||||
<Import-Package>
|
||||
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.*
|
||||
</Import-Package>
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<suiteXmlFiles>
|
||||
<suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
|
||||
</suiteXmlFiles>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@ -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<String, String> headers = (Map<String, String>) 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<String, String> 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<String, String> 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<String, String> 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<String, String> setHeaders() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
String accessToken = Utils.getBase64EncodedToken(iotServerConfiguration);
|
||||
map.put(AUTHORIZATION, BEARER + accessToken);
|
||||
map.put(CONTENT_TYPE, "application/json");
|
||||
return map;
|
||||
}
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@ -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";
|
||||
}
|
||||
}
|
||||
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@ -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<ContextPath> 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<ContextPath> getApis() {
|
||||
return apis;
|
||||
}
|
||||
|
||||
public void setApis(List<ContextPath> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -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<String, String> 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<String> 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);
|
||||
}
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
@ -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";
|
||||
}
|
||||
@ -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<String, String> 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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -1,40 +0,0 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1"?>
|
||||
<!--
|
||||
~ 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.
|
||||
-->
|
||||
|
||||
<ServerConfiguration>
|
||||
<!-- IoT server host name, this is referred from APIM gateway to call to IoT server for certificate validation-->
|
||||
<Hostname>https://${iot.core.host}:${iot.core.https.port}/</Hostname>
|
||||
|
||||
<!--End point to verify the certificate-->
|
||||
<VerificationEndpoint>https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/</VerificationEndpoint>
|
||||
|
||||
<!--Admin username/password - this is to use for oauth token generation-->
|
||||
<Username>admin</Username>
|
||||
<Password>admin</Password>
|
||||
|
||||
<!--Dynamic client registration endpoint-->
|
||||
<DynamicClientRegistrationEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.12/register</DynamicClientRegistrationEndpoint>
|
||||
|
||||
<!--Oauth token endpoint-->
|
||||
<OauthTokenEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token</OauthTokenEndpoint>
|
||||
|
||||
<APIS>
|
||||
<ContextPath>/services</ContextPath>
|
||||
</APIS>
|
||||
</ServerConfiguration>
|
||||
@ -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("<empty/>", 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<String, String> transportHeaders = new HashMap<>();
|
||||
transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert");
|
||||
boolean response = this.handler.handleRequest(createSynapseMessageContext("<empty/>", 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<String, String> transportHeaders = new HashMap<>();
|
||||
transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert");
|
||||
setMockClient();
|
||||
this.mockClient.setResponse(getValidationResponse());
|
||||
boolean response = this.handler.handleRequest(createSynapseMessageContext("<empty/>", 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<String, String> transportHeaders = new HashMap<>();
|
||||
transportHeaders.put(AuthConstants.MUTUAL_AUTH_HEADER, "Test Header");
|
||||
setMockClient();
|
||||
this.mockClient.setResponse(getValidationResponse());
|
||||
MessageContext messageContext = createSynapseMessageContext("<empty/>", 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<String, String> transportHeaders = new HashMap<>();
|
||||
transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem");
|
||||
setMockClient();
|
||||
this.mockClient.setResponse(getValidationResponse());
|
||||
MessageContext messageContext = createSynapseMessageContext("<empty/>", 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<String, String> transportHeaders = new HashMap<>();
|
||||
transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem");
|
||||
setMockClient();
|
||||
this.mockClient.setResponse(getInvalidResponse());
|
||||
MessageContext messageContext = createSynapseMessageContext("<empty/>", 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<String, String> transportHeaders = new HashMap<>();
|
||||
transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem");
|
||||
setMockClient();
|
||||
this.mockClient.setResponse(null);
|
||||
MessageContext messageContext = createSynapseMessageContext("<empty/>", 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<String, String> transportHeaders = new HashMap<>();
|
||||
transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem");
|
||||
setMockClient();
|
||||
this.mockClient.setResponse(null);
|
||||
MessageContext messageContext = createSynapseMessageContext("<empty/>", 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<String, String> transportHeaders = new HashMap<>();
|
||||
transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert");
|
||||
AuthenticationHandler handler = new AuthenticationHandler();
|
||||
boolean response = handler.handleRequest(createSynapseMessageContext("<empty/>", 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<String, String> 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;
|
||||
}
|
||||
}
|
||||
@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@ -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");
|
||||
}
|
||||
}
|
||||
@ -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);
|
||||
}
|
||||
}
|
||||
@ -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<CloseableHttpResponse> 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;
|
||||
}
|
||||
}
|
||||
@ -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) {
|
||||
|
||||
}
|
||||
}
|
||||
@ -1,7 +0,0 @@
|
||||
{
|
||||
"scope": "API_SUBSCRIBER_SCOPE",
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 3600,
|
||||
"refresh_token": "33c3be152ebf0030b3fb76f2c1f80bf8",
|
||||
"access_token": "292ff0fd256814536baca0926f483c8d"
|
||||
}
|
||||
@ -1,658 +0,0 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1"?>
|
||||
|
||||
<!--
|
||||
~ 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.
|
||||
-->
|
||||
|
||||
<!--
|
||||
This is the main server configuration file
|
||||
|
||||
${carbon.home} represents the carbon.home system property.
|
||||
Other system properties can be specified in a similar manner.
|
||||
-->
|
||||
<Server xmlns="http://wso2.org/projects/carbon/carbon.xml">
|
||||
|
||||
<!--
|
||||
Product Name
|
||||
-->
|
||||
<Name>${product.name}</Name>
|
||||
|
||||
<!--
|
||||
machine readable unique key to identify each product
|
||||
-->
|
||||
<ServerKey>${product.key}</ServerKey>
|
||||
|
||||
<!--
|
||||
Product Version
|
||||
-->
|
||||
<Version>${product.version}</Version>
|
||||
|
||||
<!--
|
||||
Host name or IP address of the machine hosting this server
|
||||
e.g. www.wso2.org, 192.168.1.10
|
||||
This is will become part of the End Point Reference of the
|
||||
services deployed on this server instance.
|
||||
-->
|
||||
<!--HostName>www.wso2.org</HostName-->
|
||||
|
||||
<!--
|
||||
Host name to be used for the Carbon management console
|
||||
-->
|
||||
<!--MgtHostName>mgt.wso2.org</MgtHostName-->
|
||||
|
||||
<!--
|
||||
The URL of the back end server. This is where the admin services are hosted and
|
||||
will be used by the clients in the front end server.
|
||||
This is required only for the Front-end server. This is used when seperating BE server from FE server
|
||||
-->
|
||||
<ServerURL>local:/${carbon.context}/services/</ServerURL>
|
||||
<!--
|
||||
<ServerURL>https://${carbon.local.ip}:${carbon.management.port}${carbon.context}/services/</ServerURL>
|
||||
-->
|
||||
<!--
|
||||
The URL of the index page. This is where the user will be redirected after signing in to the
|
||||
carbon server.
|
||||
-->
|
||||
<!-- IndexPageURL>/carbon/admin/index.jsp</IndexPageURL-->
|
||||
|
||||
<!--
|
||||
For cApp deployment, we have to identify the roles that can be acted by the current server.
|
||||
The following property is used for that purpose. Any number of roles can be defined here.
|
||||
Regular expressions can be used in the role.
|
||||
Ex : <Role>.*</Role> means this server can act any role
|
||||
-->
|
||||
<ServerRoles>
|
||||
<Role>${default.server.role}</Role>
|
||||
</ServerRoles>
|
||||
|
||||
<!-- uncommnet this line to subscribe to a bam instance automatically -->
|
||||
<!--<BamServerURL>https://bamhost:bamport/services/</BamServerURL>-->
|
||||
|
||||
<!--
|
||||
The fully qualified name of the server
|
||||
-->
|
||||
<Package>org.wso2.carbon</Package>
|
||||
|
||||
<!--
|
||||
Webapp context root of WSO2 Carbon management console.
|
||||
-->
|
||||
<WebContextRoot>/</WebContextRoot>
|
||||
|
||||
<!--
|
||||
Proxy context path is a useful parameter to add a proxy path when a Carbon server is fronted by reverse proxy. In addtion
|
||||
to the proxy host and proxy port this parameter allows you add a path component to external URLs. e.g.
|
||||
URL of the Carbon server -> https://10.100.1.1:9443/carbon
|
||||
URL of the reverse proxy -> https://prod.abc.com/appserver/carbon
|
||||
|
||||
appserver - proxy context path. This specially required whenever you are generating URLs to displace in
|
||||
Carbon UI components.
|
||||
-->
|
||||
<!--
|
||||
<MgtProxyContextPath></MgtProxyContextPath>
|
||||
<ProxyContextPath></ProxyContextPath>
|
||||
-->
|
||||
|
||||
<!-- In-order to get the registry http Port from the back-end when the default http transport is not the same-->
|
||||
<!--RegistryHttpPort>9763</RegistryHttpPort-->
|
||||
|
||||
<!--
|
||||
Number of items to be displayed on a management console page. This is used at the
|
||||
backend server for pagination of various items.
|
||||
-->
|
||||
<ItemsPerPage>15</ItemsPerPage>
|
||||
|
||||
<!-- The endpoint URL of the cloud instance management Web service -->
|
||||
<!--<InstanceMgtWSEndpoint>https://ec2.amazonaws.com/</InstanceMgtWSEndpoint>-->
|
||||
|
||||
<!--
|
||||
Ports used by this server
|
||||
-->
|
||||
<Ports>
|
||||
|
||||
<!-- Ports offset. This entry will set the value of the ports defined below to
|
||||
the define value + Offset.
|
||||
e.g. Offset=2 and HTTPS port=9443 will set the effective HTTPS port to 9445
|
||||
-->
|
||||
<Offset>0</Offset>
|
||||
|
||||
<!-- The JMX Ports -->
|
||||
<JMX>
|
||||
<!--The port RMI registry is exposed-->
|
||||
<RMIRegistryPort>9999</RMIRegistryPort>
|
||||
<!--The port RMI server should be exposed-->
|
||||
<RMIServerPort>11111</RMIServerPort>
|
||||
</JMX>
|
||||
|
||||
<!-- Embedded LDAP server specific ports -->
|
||||
<EmbeddedLDAP>
|
||||
<!-- Port which embedded LDAP server runs -->
|
||||
<LDAPServerPort>10389</LDAPServerPort>
|
||||
<!-- Port which KDC (Kerberos Key Distribution Center) server runs -->
|
||||
<KDCServerPort>8000</KDCServerPort>
|
||||
</EmbeddedLDAP>
|
||||
|
||||
<!--
|
||||
Override datasources JNDIproviderPort defined in bps.xml and datasources.properties files
|
||||
-->
|
||||
<!--<JNDIProviderPort>2199</JNDIProviderPort>-->
|
||||
<!--Override receive port of thrift based entitlement service.-->
|
||||
<ThriftEntitlementReceivePort>10500</ThriftEntitlementReceivePort>
|
||||
|
||||
</Ports>
|
||||
|
||||
<!--
|
||||
JNDI Configuration
|
||||
-->
|
||||
<JNDI>
|
||||
<!--
|
||||
The fully qualified name of the default initial context factory
|
||||
-->
|
||||
<DefaultInitialContextFactory>org.wso2.carbon.tomcat.jndi.CarbonJavaURLContextFactory</DefaultInitialContextFactory>
|
||||
<!--
|
||||
The restrictions that are done to various JNDI Contexts in a Multi-tenant environment
|
||||
-->
|
||||
<Restrictions>
|
||||
<!--
|
||||
Contexts that will be available only to the super-tenant
|
||||
-->
|
||||
<!-- <SuperTenantOnly>
|
||||
<UrlContexts>
|
||||
<UrlContext>
|
||||
<Scheme>foo</Scheme>
|
||||
</UrlContext>
|
||||
<UrlContext>
|
||||
<Scheme>bar</Scheme>
|
||||
</UrlContext>
|
||||
</UrlContexts>
|
||||
</SuperTenantOnly> -->
|
||||
<!--
|
||||
Contexts that are common to all tenants
|
||||
-->
|
||||
<AllTenants>
|
||||
<UrlContexts>
|
||||
<UrlContext>
|
||||
<Scheme>java</Scheme>
|
||||
</UrlContext>
|
||||
<!-- <UrlContext>
|
||||
<Scheme>foo</Scheme>
|
||||
</UrlContext> -->
|
||||
</UrlContexts>
|
||||
</AllTenants>
|
||||
<!--
|
||||
All other contexts not mentioned above will be available on a per-tenant basis
|
||||
(i.e. will not be shared among tenants)
|
||||
-->
|
||||
</Restrictions>
|
||||
</JNDI>
|
||||
|
||||
<!--
|
||||
Property to determine if the server is running an a cloud deployment environment.
|
||||
This property should only be used to determine deployment specific details that are
|
||||
applicable only in a cloud deployment, i.e when the server deployed *-as-a-service.
|
||||
-->
|
||||
<IsCloudDeployment>false</IsCloudDeployment>
|
||||
|
||||
<!--
|
||||
Property to determine whether usage data should be collected for metering purposes
|
||||
-->
|
||||
<EnableMetering>false</EnableMetering>
|
||||
|
||||
<!-- The Max time a thread should take for execution in seconds -->
|
||||
<MaxThreadExecutionTime>600</MaxThreadExecutionTime>
|
||||
|
||||
<!--
|
||||
A flag to enable or disable Ghost Deployer. By default this is set to false. That is
|
||||
because the Ghost Deployer works only with the HTTP/S transports. If you are using
|
||||
other transports, don't enable Ghost Deployer.
|
||||
-->
|
||||
<GhostDeployment>
|
||||
<Enabled>false</Enabled>
|
||||
</GhostDeployment>
|
||||
|
||||
|
||||
<!--
|
||||
Eager loading or lazy loading is a design pattern commonly used in computer programming which
|
||||
will initialize an object upon creation or load on-demand. In carbon, lazy loading is used to
|
||||
load tenant when a request is received only. Similarly Eager loading is used to enable load
|
||||
existing tenants after carbon server starts up. Using this feature, you will be able to include
|
||||
or exclude tenants which are to be loaded when server startup.
|
||||
|
||||
We can enable only one LoadingPolicy at a given time.
|
||||
|
||||
1. Tenant Lazy Loading
|
||||
This is the default behaviour and enabled by default. With this policy, tenants are not loaded at
|
||||
server startup, but loaded based on-demand (i.e when a request is received for a tenant).
|
||||
The default tenant idle time is 30 minutes.
|
||||
|
||||
2. Tenant Eager Loading
|
||||
This is by default not enabled. It can be be enabled by un-commenting the <EagerLoading> section.
|
||||
The eager loading configurations supported are as below. These configurations can be given as the
|
||||
value for <Include> element with eager loading.
|
||||
(i)Load all tenants when server startup - *
|
||||
(ii)Load all tenants except foo.com & bar.com - *,!foo.com,!bar.com
|
||||
(iii)Load only foo.com & bar.com to be included - foo.com,bar.com
|
||||
-->
|
||||
<Tenant>
|
||||
<LoadingPolicy>
|
||||
<LazyLoading>
|
||||
<IdleTime>30</IdleTime>
|
||||
</LazyLoading>
|
||||
<!-- <EagerLoading>
|
||||
<Include>*,!foo.com,!bar.com</Include>
|
||||
</EagerLoading>-->
|
||||
</LoadingPolicy>
|
||||
</Tenant>
|
||||
|
||||
<!--
|
||||
Caching related configurations
|
||||
-->
|
||||
<Cache>
|
||||
<!-- Default cache timeout in minutes -->
|
||||
<DefaultCacheTimeout>15</DefaultCacheTimeout>
|
||||
</Cache>
|
||||
|
||||
<!--
|
||||
Axis2 related configurations
|
||||
-->
|
||||
<Axis2Config>
|
||||
<!--
|
||||
Location of the Axis2 Services & Modules repository
|
||||
|
||||
This can be a directory in the local file system, or a URL.
|
||||
|
||||
e.g.
|
||||
1. /home/wso2wsas/repository/ - An absolute path
|
||||
2. repository - In this case, the path is relative to CARBON_HOME
|
||||
3. file:///home/wso2wsas/repository/
|
||||
4. http://wso2wsas/repository/
|
||||
-->
|
||||
<RepositoryLocation>${carbon.home}/repository/deployment/server/</RepositoryLocation>
|
||||
|
||||
<!--
|
||||
Deployment update interval in seconds. This is the interval between repository listener
|
||||
executions.
|
||||
-->
|
||||
<DeploymentUpdateInterval>15</DeploymentUpdateInterval>
|
||||
|
||||
<!--
|
||||
Location of the main Axis2 configuration descriptor file, a.k.a. axis2.xml file
|
||||
|
||||
This can be a file on the local file system, or a URL
|
||||
|
||||
e.g.
|
||||
1. /home/repository/axis2.xml - An absolute path
|
||||
2. conf/axis2.xml - In this case, the path is relative to CARBON_HOME
|
||||
3. file:///home/carbon/repository/axis2.xml
|
||||
4. http://repository/conf/axis2.xml
|
||||
-->
|
||||
<ConfigurationFile>${carbon.home}/repository/conf/axis2/axis2.xml</ConfigurationFile>
|
||||
|
||||
<!--
|
||||
ServiceGroupContextIdleTime, which will be set in ConfigurationContex
|
||||
for multiple clients which are going to access the same ServiceGroupContext
|
||||
Default Value is 30 Sec.
|
||||
-->
|
||||
<ServiceGroupContextIdleTime>30000</ServiceGroupContextIdleTime>
|
||||
|
||||
<!--
|
||||
This repository location is used to crete the client side configuration
|
||||
context used by the server when calling admin services.
|
||||
-->
|
||||
<ClientRepositoryLocation>${carbon.home}/repository/deployment/client/</ClientRepositoryLocation>
|
||||
<!-- This axis2 xml is used in createing the configuration context by the FE server
|
||||
calling to BE server -->
|
||||
<clientAxis2XmlLocation>${carbon.home}/repository/conf/axis2/axis2_client.xml</clientAxis2XmlLocation>
|
||||
<!-- If this parameter is set, the ?wsdl on an admin service will not give the admin service wsdl. -->
|
||||
<HideAdminServiceWSDLs>true</HideAdminServiceWSDLs>
|
||||
|
||||
<!--WARNING-Use With Care! Uncommenting bellow parameter would expose all AdminServices in HTTP transport.
|
||||
With HTTP transport your credentials and data routed in public channels are vulnerable for sniffing attacks.
|
||||
Use bellow parameter ONLY if your communication channels are confirmed to be secured by other means -->
|
||||
<!--HttpAdminServices>*</HttpAdminServices-->
|
||||
|
||||
</Axis2Config>
|
||||
|
||||
<!--
|
||||
The default user roles which will be created when the server
|
||||
is started up for the first time.
|
||||
-->
|
||||
<ServiceUserRoles>
|
||||
<Role>
|
||||
<Name>admin</Name>
|
||||
<Description>Default Administrator Role</Description>
|
||||
</Role>
|
||||
<Role>
|
||||
<Name>user</Name>
|
||||
<Description>Default User Role</Description>
|
||||
</Role>
|
||||
</ServiceUserRoles>
|
||||
|
||||
<!--
|
||||
Enable following config to allow Emails as usernames.
|
||||
-->
|
||||
<!--EnableEmailUserName>true</EnableEmailUserName-->
|
||||
|
||||
<!--
|
||||
Security configurations
|
||||
-->
|
||||
<Security>
|
||||
<!--
|
||||
KeyStore which will be used for encrypting/decrypting passwords
|
||||
and other sensitive information.
|
||||
-->
|
||||
<KeyStore>
|
||||
<!-- Keystore file location-->
|
||||
<Location>${carbon.home}/repository/resources/security/wso2carbon.jks</Location>
|
||||
<!-- Keystore type (JKS/PKCS12 etc.)-->
|
||||
<Type>JKS</Type>
|
||||
<!-- Keystore password-->
|
||||
<Password>wso2carbon</Password>
|
||||
<!-- Private Key alias-->
|
||||
<KeyAlias>wso2carbon</KeyAlias>
|
||||
<!-- Private Key password-->
|
||||
<KeyPassword>wso2carbon</KeyPassword>
|
||||
</KeyStore>
|
||||
|
||||
<!--
|
||||
System wide trust-store which is used to maintain the certificates of all
|
||||
the trusted parties.
|
||||
-->
|
||||
<TrustStore>
|
||||
<!-- trust-store file location -->
|
||||
<Location>${carbon.home}/repository/resources/security/client-truststore.jks</Location>
|
||||
<!-- trust-store type (JKS/PKCS12 etc.) -->
|
||||
<Type>JKS</Type>
|
||||
<!-- trust-store password -->
|
||||
<Password>wso2carbon</Password>
|
||||
</TrustStore>
|
||||
|
||||
<!--
|
||||
The Authenticator configuration to be used at the JVM level. We extend the
|
||||
java.net.Authenticator to make it possible to authenticate to given servers and
|
||||
proxies.
|
||||
-->
|
||||
<NetworkAuthenticatorConfig>
|
||||
<!--
|
||||
Below is a sample configuration for a single authenticator. Please note that
|
||||
all child elements are mandatory. Not having some child elements would lead to
|
||||
exceptions at runtime.
|
||||
-->
|
||||
<!-- <Credential> -->
|
||||
<!--
|
||||
the pattern that would match a subset of URLs for which this authenticator
|
||||
would be used
|
||||
-->
|
||||
<!-- <Pattern>regularExpression</Pattern> -->
|
||||
<!--
|
||||
the type of this authenticator. Allowed values are:
|
||||
1. server
|
||||
2. proxy
|
||||
-->
|
||||
<!-- <Type>proxy</Type> -->
|
||||
<!-- the username used to log in to server/proxy -->
|
||||
<!-- <Username>username</Username> -->
|
||||
<!-- the password used to log in to server/proxy -->
|
||||
<!-- <Password>password</Password> -->
|
||||
<!-- </Credential> -->
|
||||
</NetworkAuthenticatorConfig>
|
||||
|
||||
<!--
|
||||
The Tomcat realm to be used for hosted Web applications. Allowed values are;
|
||||
1. UserManager
|
||||
2. Memory
|
||||
|
||||
If this is set to 'UserManager', the realm will pick users & roles from the system's
|
||||
WSO2 User Manager. If it is set to 'memory', the realm will pick users & roles from
|
||||
CARBON_HOME/repository/conf/tomcat/tomcat-users.xml
|
||||
-->
|
||||
<TomcatRealm>UserManager</TomcatRealm>
|
||||
|
||||
<!--Option to disable storing of tokens issued by STS-->
|
||||
<DisableTokenStore>false</DisableTokenStore>
|
||||
|
||||
<!--
|
||||
Security token store class name. If this is not set, default class will be
|
||||
org.wso2.carbon.security.util.SecurityTokenStore
|
||||
-->
|
||||
<!--TokenStoreClassName>org.wso2.carbon.identity.sts.store.DBTokenStore</TokenStoreClassName-->
|
||||
</Security>
|
||||
|
||||
<!--
|
||||
The temporary work directory
|
||||
-->
|
||||
<WorkDirectory>${carbon.home}/tmp/work</WorkDirectory>
|
||||
|
||||
<!--
|
||||
House-keeping configuration
|
||||
-->
|
||||
<HouseKeeping>
|
||||
|
||||
<!--
|
||||
true - Start House-keeping thread on server startup
|
||||
false - Do not start House-keeping thread on server startup.
|
||||
The user will run it manually as and when he wishes.
|
||||
-->
|
||||
<AutoStart>true</AutoStart>
|
||||
|
||||
<!--
|
||||
The interval in *minutes*, between house-keeping runs
|
||||
-->
|
||||
<Interval>10</Interval>
|
||||
|
||||
<!--
|
||||
The maximum time in *minutes*, temp files are allowed to live
|
||||
in the system. Files/directories which were modified more than
|
||||
"MaxTempFileLifetime" minutes ago will be removed by the
|
||||
house-keeping task
|
||||
-->
|
||||
<MaxTempFileLifetime>30</MaxTempFileLifetime>
|
||||
</HouseKeeping>
|
||||
|
||||
<!--
|
||||
Configuration for handling different types of file upload & other file uploading related
|
||||
config parameters.
|
||||
To map all actions to a particular FileUploadExecutor, use
|
||||
<Action>*</Action>
|
||||
-->
|
||||
<FileUploadConfig>
|
||||
<!--
|
||||
The total file upload size limit in MB
|
||||
-->
|
||||
<TotalFileSizeLimit>100</TotalFileSizeLimit>
|
||||
|
||||
<Mapping>
|
||||
<Actions>
|
||||
<Action>keystore</Action>
|
||||
<Action>certificate</Action>
|
||||
<Action>*</Action>
|
||||
</Actions>
|
||||
<Class>org.wso2.carbon.ui.transports.fileupload.AnyFileUploadExecutor</Class>
|
||||
</Mapping>
|
||||
|
||||
<Mapping>
|
||||
<Actions>
|
||||
<Action>jarZip</Action>
|
||||
</Actions>
|
||||
<Class>org.wso2.carbon.ui.transports.fileupload.JarZipUploadExecutor</Class>
|
||||
</Mapping>
|
||||
<Mapping>
|
||||
<Actions>
|
||||
<Action>dbs</Action>
|
||||
</Actions>
|
||||
<Class>org.wso2.carbon.ui.transports.fileupload.DBSFileUploadExecutor</Class>
|
||||
</Mapping>
|
||||
<Mapping>
|
||||
<Actions>
|
||||
<Action>tools</Action>
|
||||
</Actions>
|
||||
<Class>org.wso2.carbon.ui.transports.fileupload.ToolsFileUploadExecutor</Class>
|
||||
</Mapping>
|
||||
<Mapping>
|
||||
<Actions>
|
||||
<Action>toolsAny</Action>
|
||||
</Actions>
|
||||
<Class>org.wso2.carbon.ui.transports.fileupload.ToolsAnyFileUploadExecutor</Class>
|
||||
</Mapping>
|
||||
</FileUploadConfig>
|
||||
|
||||
<!--
|
||||
Processors which process special HTTP GET requests such as ?wsdl, ?policy etc.
|
||||
|
||||
In order to plug in a processor to handle a special request, simply add an entry to this
|
||||
section.
|
||||
|
||||
The value of the Item element is the first parameter in the query string(e.g. ?wsdl)
|
||||
which needs special processing
|
||||
|
||||
The value of the Class element is a class which implements
|
||||
org.wso2.carbon.transport.HttpGetRequestProcessor
|
||||
-->
|
||||
<HttpGetRequestProcessors>
|
||||
<Processor>
|
||||
<Item>info</Item>
|
||||
<Class>org.wso2.carbon.core.transports.util.InfoProcessor</Class>
|
||||
</Processor>
|
||||
<Processor>
|
||||
<Item>wsdl</Item>
|
||||
<Class>org.wso2.carbon.core.transports.util.Wsdl11Processor</Class>
|
||||
</Processor>
|
||||
<Processor>
|
||||
<Item>wsdl2</Item>
|
||||
<Class>org.wso2.carbon.core.transports.util.Wsdl20Processor</Class>
|
||||
</Processor>
|
||||
<Processor>
|
||||
<Item>xsd</Item>
|
||||
<Class>org.wso2.carbon.core.transports.util.XsdProcessor</Class>
|
||||
</Processor>
|
||||
</HttpGetRequestProcessors>
|
||||
|
||||
<!-- Deployment Synchronizer Configuration. t Enabled value to true when running with "svn based" dep sync.
|
||||
In master nodes you need to set both AutoCommit and AutoCheckout to true
|
||||
and in worker nodes set only AutoCheckout to true.
|
||||
-->
|
||||
<DeploymentSynchronizer>
|
||||
<Enabled>false</Enabled>
|
||||
<AutoCommit>false</AutoCommit>
|
||||
<AutoCheckout>true</AutoCheckout>
|
||||
<RepositoryType>svn</RepositoryType>
|
||||
<SvnUrl>http://svnrepo.example.com/repos/</SvnUrl>
|
||||
<SvnUser>username</SvnUser>
|
||||
<SvnPassword>password</SvnPassword>
|
||||
<SvnUrlAppendTenantId>true</SvnUrlAppendTenantId>
|
||||
</DeploymentSynchronizer>
|
||||
|
||||
<!-- Deployment Synchronizer Configuration. Uncomment the following section when running with "registry based" dep sync.
|
||||
In master nodes you need to set both AutoCommit and AutoCheckout to true
|
||||
and in worker nodes set only AutoCheckout to true.
|
||||
-->
|
||||
<!--<DeploymentSynchronizer>
|
||||
<Enabled>true</Enabled>
|
||||
<AutoCommit>false</AutoCommit>
|
||||
<AutoCheckout>true</AutoCheckout>
|
||||
</DeploymentSynchronizer>-->
|
||||
|
||||
<!-- Mediation persistence configurations. Only valid if mediation features are available i.e. ESB -->
|
||||
<!--<MediationConfig>
|
||||
<LoadFromRegistry>false</LoadFromRegistry>
|
||||
<SaveToFile>false</SaveToFile>
|
||||
<Persistence>enabled</Persistence>
|
||||
<RegistryPersistence>enabled</RegistryPersistence>
|
||||
</MediationConfig>-->
|
||||
|
||||
<!--
|
||||
Server intializing code, specified as implementation classes of org.wso2.carbon.core.ServerInitializer.
|
||||
This code will be run when the Carbon server is initialized
|
||||
-->
|
||||
<ServerInitializers>
|
||||
<!--<Initializer></Initializer>-->
|
||||
</ServerInitializers>
|
||||
|
||||
<!--
|
||||
Indicates whether the Carbon Servlet is required by the system, and whether it should be
|
||||
registered
|
||||
-->
|
||||
<RequireCarbonServlet>${require.carbon.servlet}</RequireCarbonServlet>
|
||||
|
||||
<!--
|
||||
Carbon H2 OSGI Configuration
|
||||
By default non of the servers start.
|
||||
name="web" - Start the web server with the H2 Console
|
||||
name="webPort" - The port (default: 8082)
|
||||
name="webAllowOthers" - Allow other computers to connect
|
||||
name="webSSL" - Use encrypted (HTTPS) connections
|
||||
name="tcp" - Start the TCP server
|
||||
name="tcpPort" - The port (default: 9092)
|
||||
name="tcpAllowOthers" - Allow other computers to connect
|
||||
name="tcpSSL" - Use encrypted (SSL) connections
|
||||
name="pg" - Start the PG server
|
||||
name="pgPort" - The port (default: 5435)
|
||||
name="pgAllowOthers" - Allow other computers to connect
|
||||
name="trace" - Print additional trace information; for all servers
|
||||
name="baseDir" - The base directory for H2 databases; for all servers
|
||||
-->
|
||||
<!--H2DatabaseConfiguration>
|
||||
<property name="web" />
|
||||
<property name="webPort">8082</property>
|
||||
<property name="webAllowOthers" />
|
||||
<property name="webSSL" />
|
||||
<property name="tcp" />
|
||||
<property name="tcpPort">9092</property>
|
||||
<property name="tcpAllowOthers" />
|
||||
<property name="tcpSSL" />
|
||||
<property name="pg" />
|
||||
<property name="pgPort">5435</property>
|
||||
<property name="pgAllowOthers" />
|
||||
<property name="trace" />
|
||||
<property name="baseDir">${carbon.home}</property>
|
||||
</H2DatabaseConfiguration-->
|
||||
<!--Disabling statistics reporter by default-->
|
||||
<StatisticsReporterDisabled>true</StatisticsReporterDisabled>
|
||||
|
||||
<!-- Enable accessing Admin Console via HTTP -->
|
||||
<!-- EnableHTTPAdminConsole>true</EnableHTTPAdminConsole -->
|
||||
|
||||
<!--
|
||||
Default Feature Repository of WSO2 Carbon.
|
||||
-->
|
||||
<FeatureRepository>
|
||||
<RepositoryName>default repository</RepositoryName>
|
||||
<RepositoryURL>${p2.repo.url}</RepositoryURL>
|
||||
</FeatureRepository>
|
||||
|
||||
<!--
|
||||
Configure API Management
|
||||
-->
|
||||
<APIManagement>
|
||||
|
||||
<!--Uses the embedded API Manager by default. If you want to use an external
|
||||
API Manager instance to manage APIs, configure below externalAPIManager-->
|
||||
|
||||
<Enabled>true</Enabled>
|
||||
|
||||
<!--Uncomment and configure API Gateway and
|
||||
Publisher URLs to use external API Manager instance-->
|
||||
|
||||
<!--ExternalAPIManager>
|
||||
|
||||
<APIGatewayURL>http://localhost:8281</APIGatewayURL>
|
||||
<APIPublisherURL>http://localhost:8281/publisher</APIPublisherURL>
|
||||
|
||||
</ExternalAPIManager-->
|
||||
|
||||
<LoadAPIContextsInServerStartup>true</LoadAPIContextsInServerStartup>
|
||||
</APIManagement>
|
||||
</Server>
|
||||
@ -1,40 +0,0 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1"?>
|
||||
<!--
|
||||
~ 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.
|
||||
-->
|
||||
|
||||
<ServerConfig>
|
||||
<!-- IoT server host name, this is referred from APIM gateway to call to IoT server for certificate validation-->
|
||||
<Hostname>https://${iot.core.host}:${iot.core.https.port}/</Hostname>
|
||||
|
||||
<!--End point to verify the certificate-->
|
||||
<VerificationEndpoint>https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/</VerificationEndpoint>
|
||||
|
||||
<!--Admin username/password - this is to use for oauth token generation-->
|
||||
<Username>testuser</Username>
|
||||
<Password>testuserpwd</Password>
|
||||
|
||||
<!--Dynamic client registration endpoint-->
|
||||
<DynamicClientRegistrationEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.12/register</DynamicClientRegistrationEndpoint>
|
||||
|
||||
<!--Oauth token endpoint-->
|
||||
<OauthTokenEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token</OauthTokenEndpoint>
|
||||
|
||||
<APIS>
|
||||
<ContextPath>/services</ContextPath>
|
||||
</APIS>
|
||||
</ServerConfig
|
||||
@ -1,40 +0,0 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1"?>
|
||||
<!--
|
||||
~ 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.
|
||||
-->
|
||||
|
||||
<ServerConfig>
|
||||
<!-- IoT server host name, this is referred from APIM gateway to call to IoT server for certificate validation-->
|
||||
<Hostname>https://${iot.core.host}:${iot.core.https.port}/</Hostname>
|
||||
|
||||
<!--End point to verify the certificate-->
|
||||
<VerificationEndpoint>https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/</VerificationEndpoint>
|
||||
|
||||
<!--Admin username/password - this is to use for oauth token generation-->
|
||||
<Username>testuser</Username>
|
||||
<Password>testuserpwd</Password>
|
||||
|
||||
<!--Dynamic client registration endpoint-->
|
||||
<DynamicClientRegistrationEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.12/register</DynamicClientRegistrationEndpoint>
|
||||
|
||||
<!--Oauth token endpoint-->
|
||||
<OauthTokenEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token</OauthTokenEndpoint>
|
||||
|
||||
<APIS>
|
||||
<ContextPath>/services</ContextPath>
|
||||
</APIS>
|
||||
</ServerConfig>
|
||||
@ -1,40 +0,0 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1"?>
|
||||
<!--
|
||||
~ 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.
|
||||
-->
|
||||
|
||||
<ServerConfiguration>
|
||||
<!-- IoT server host name, this is referred from APIM gateway to call to IoT server for certificate validation-->
|
||||
<Hostname>https://${iot.core.host}:${iot.core.https.port}/</Hostname>
|
||||
|
||||
<!--End point to verify the certificate-->
|
||||
<VerificationEndpoint>https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/</VerificationEndpoint>
|
||||
|
||||
<!--Admin username/password - this is to use for oauth token generation-->
|
||||
<Username>testuser</Username>
|
||||
<Password>testuserpwd</Password>
|
||||
|
||||
<!--Dynamic client registration endpoint-->
|
||||
<DynamicClientRegistrationEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.12/register</DynamicClientRegistrationEndpoint>
|
||||
|
||||
<!--Oauth token endpoint-->
|
||||
<OauthTokenEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token</OauthTokenEndpoint>
|
||||
|
||||
<APIS>
|
||||
<ContextPath>/services</ContextPath>
|
||||
</APIS>
|
||||
</ServerConfiguration>
|
||||
@ -1,52 +0,0 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1"?>
|
||||
|
||||
<!--
|
||||
~ 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.
|
||||
-->
|
||||
<wso2registry>
|
||||
|
||||
<!--
|
||||
For details on configuring different config & governance registries see;
|
||||
http://wso2.org/library/tutorials/2010/04/sharing-registry-space-across-multiple-product-instances
|
||||
-->
|
||||
|
||||
<currentDBConfig>wso2registry</currentDBConfig>
|
||||
<readOnly>false</readOnly>
|
||||
<enableCache>true</enableCache>
|
||||
<registryRoot>/</registryRoot>
|
||||
|
||||
<dbConfig name="wso2registry">
|
||||
<url>jdbc:h2:./target/databasetest/CARBON_TEST</url>
|
||||
<!--userName>sa</userName>
|
||||
<password>sa</password-->
|
||||
<driverName>org.h2.Driver</driverName>
|
||||
<maxActive>80</maxActive>
|
||||
<maxWait>60000</maxWait>
|
||||
<minIdle>5</minIdle>
|
||||
</dbConfig>
|
||||
|
||||
<versionResourcesOnChange>false</versionResourcesOnChange>
|
||||
|
||||
<!-- NOTE: You can edit the options under "StaticConfiguration" only before the
|
||||
startup. -->
|
||||
<staticConfiguration>
|
||||
<versioningProperties>true</versioningProperties>
|
||||
<versioningComments>true</versioningComments>
|
||||
<versioningTags>true</versioningTags>
|
||||
<versioningRatings>true</versioningRatings>
|
||||
</staticConfiguration>
|
||||
</wso2registry>
|
||||
@ -1,6 +0,0 @@
|
||||
{
|
||||
"callBackURL": "www.google.lk",
|
||||
"clientName": null,
|
||||
"clientId": "HfEl1jJPdg5tbtrxhAwybN05QGoa",
|
||||
"clientSecret": "l6c0aoLcWR3fwezHhc7XoGOht5Aa"
|
||||
}
|
||||
@ -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-----
|
||||
@ -1,30 +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.
|
||||
-->
|
||||
|
||||
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
|
||||
|
||||
<suite name="DeviceManagementExtensions">
|
||||
<parameter name="useDefaultListeners" value="false"/>
|
||||
|
||||
<test name="API Management Auth Handlers" preserve-order="true">
|
||||
<classes>
|
||||
<class name="org.wso2.carbon.apimgt.handlers.IOTServerConfigurationTest"/>
|
||||
<class name="org.wso2.carbon.apimgt.handlers.AuthenticationHandlerTest"/>
|
||||
</classes>
|
||||
</test>
|
||||
</suite>
|
||||
@ -1,202 +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.
|
||||
-->
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<parent>
|
||||
<artifactId>apimgt-extensions</artifactId>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<version>5.0.0-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.apimgt.integration.client</artifactId>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - API Management Integration Client</name>
|
||||
<description>WSO2 Carbon - API Management Integration Client</description>
|
||||
<url>http://wso2.org</url>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-scr-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
<version>1.4.0</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<instructions>
|
||||
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
|
||||
<Bundle-Name>${project.artifactId}</Bundle-Name>
|
||||
<Bundle-Version>${project.version}</Bundle-Version>
|
||||
<Bundle-Description>APIM Integration</Bundle-Description>
|
||||
<Private-Package>org.wso2.carbon.apimgt.integration.client.internal</Private-Package>
|
||||
<Export-Package>
|
||||
org.wso2.carbon.apimgt.integration.client.*,
|
||||
!org.wso2.carbon.apimgt.integration.client.internal
|
||||
</Export-Package>
|
||||
<Import-Package>
|
||||
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
|
||||
</Import-Package>
|
||||
<Embed-Dependency>
|
||||
jsr311-api,
|
||||
feign-jaxrs,
|
||||
feign-okhttp,
|
||||
okhttp,
|
||||
okio
|
||||
</Embed-Dependency>
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>jacoco-initialize</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>jacoco-site</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
|
||||
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.okio</groupId>
|
||||
<artifactId>okio</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.openfeign</groupId>
|
||||
<artifactId>feign-okhttp</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.logging</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi.services</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
<artifactId>jsr311-api</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.swagger</groupId>
|
||||
<artifactId>swagger-annotations</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.openfeign</groupId>
|
||||
<artifactId>feign-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.openfeign</groupId>
|
||||
<artifactId>feign-jackson</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.openfeign</groupId>
|
||||
<artifactId>feign-jaxrs</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.openfeign</groupId>
|
||||
<artifactId>feign-gson</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<artifactId>io.entgra.device.mgt.core.identity.jwt.client.extension</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<artifactId>org.wso2.carbon.apimgt.integration.generated.client</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user