parent
1282a2d270
commit
8cf830b7c8
@ -1,139 +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>https://entgra.io</url>
|
||||
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.ops4j.pax.logging</groupId>
|
||||
<artifactId>pax-logging-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
<!-- <version>${pax.logging.api.version}</version>-->
|
||||
</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-bundle-plugin</artifactId>
|
||||
<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,204 +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>https://entgra.io</url>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
<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.*;version="${imp.package.version.osgi.framework}",
|
||||
org.osgi.service.*;version="${imp.package.version.osgi.service}",
|
||||
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>org.apache.felix</groupId>
|
||||
<artifactId>org.apache.felix.scr.ds-annotations</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<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.ops4j.pax.logging</groupId>
|
||||
<artifactId>pax-logging-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
<!-- <version>${pax.logging.api.version}</version>-->
|
||||
</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;
|
||||
}
|
||||
}
|
@ -1,142 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.apimgt.integration.client;
|
||||
|
||||
import feign.Feign;
|
||||
import feign.Logger;
|
||||
import feign.RequestInterceptor;
|
||||
import feign.RequestTemplate;
|
||||
import feign.auth.BasicAuthRequestInterceptor;
|
||||
import feign.gson.GsonDecoder;
|
||||
import feign.gson.GsonEncoder;
|
||||
import feign.jaxrs.JAXRSContract;
|
||||
import feign.okhttp.OkHttpClient;
|
||||
import feign.slf4j.Slf4jLogger;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.apimgt.integration.client.configs.APIMConfigReader;
|
||||
import org.wso2.carbon.apimgt.integration.client.exception.APIMClientOAuthException;
|
||||
import org.wso2.carbon.apimgt.integration.client.internal.APIIntegrationClientDataHolder;
|
||||
import org.wso2.carbon.apimgt.integration.client.model.ClientProfile;
|
||||
import org.wso2.carbon.apimgt.integration.client.model.DCRClient;
|
||||
import org.wso2.carbon.apimgt.integration.client.model.OAuthApplication;
|
||||
import org.wso2.carbon.apimgt.integration.client.util.Utils;
|
||||
import org.wso2.carbon.base.MultitenantConstants;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import io.entgra.device.mgt.core.identity.jwt.client.extension.JWTClient;
|
||||
import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.AccessTokenInfo;
|
||||
import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* This is a request interceptor to add oauth token header.
|
||||
*/
|
||||
public class OAuthRequestInterceptor implements RequestInterceptor {
|
||||
|
||||
private static final String APPLICATION_NAME = "api_integration_client";
|
||||
private static final String GRANT_TYPES = "password refresh_token urn:ietf:params:oauth:grant-type:jwt-bearer";
|
||||
private static final String REQUIRED_SCOPE =
|
||||
"apim:api_create apim:api_view apim:api_publish apim:subscribe apim:tier_view apim:tier_manage " +
|
||||
"apim:subscription_view apim:subscription_block";
|
||||
private static final String APIM_SUBSCRIBE_SCOPE = "apim:subscribe";
|
||||
private static final long DEFAULT_REFRESH_TIME_OFFSET_IN_MILLIS = 100000;
|
||||
private DCRClient dcrClient;
|
||||
private OAuthApplication oAuthApplication;
|
||||
private static Map<String, AccessTokenInfo> tenantUserTokenMap = new ConcurrentHashMap<>();
|
||||
private static final Log log = LogFactory.getLog(OAuthRequestInterceptor.class);
|
||||
private String username;
|
||||
private String password;
|
||||
|
||||
/**
|
||||
* Creates an interceptor that authenticates all requests.
|
||||
*/
|
||||
public OAuthRequestInterceptor() {
|
||||
username = APIMConfigReader.getInstance().getConfig().getUsername();
|
||||
password = APIMConfigReader.getInstance().getConfig().getPassword();
|
||||
dcrClient = Feign.builder().client(new OkHttpClient(Utils.getSSLClient())).logger(new Slf4jLogger())
|
||||
.logLevel(Logger.Level.FULL).requestInterceptor(new BasicAuthRequestInterceptor(username, password))
|
||||
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
|
||||
.target(DCRClient.class, Utils.replaceProperties(
|
||||
APIMConfigReader.getInstance().getConfig().getDcrEndpoint()));
|
||||
}
|
||||
|
||||
public OAuthRequestInterceptor(String username, String password) {
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
dcrClient = Feign.builder().client(new OkHttpClient(Utils.getSSLClient())).logger(new Slf4jLogger())
|
||||
.logLevel(Logger.Level.FULL).requestInterceptor(new BasicAuthRequestInterceptor(username, password))
|
||||
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
|
||||
.target(DCRClient.class, Utils.replaceProperties(
|
||||
APIMConfigReader.getInstance().getConfig().getDcrEndpoint()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void apply(RequestTemplate template) {
|
||||
if (oAuthApplication == null) {
|
||||
//had to do on demand initialization due to start up error.
|
||||
ClientProfile clientProfile = new ClientProfile();
|
||||
clientProfile.setClientName(APPLICATION_NAME);
|
||||
clientProfile.setCallbackUrl("");
|
||||
clientProfile.setGrantType(GRANT_TYPES);
|
||||
clientProfile.setOwner(username);
|
||||
clientProfile.setSaasApp(true);
|
||||
oAuthApplication = dcrClient.register(clientProfile);
|
||||
}
|
||||
try {
|
||||
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
|
||||
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
|
||||
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
|
||||
username = username + "@" + tenantDomain;
|
||||
}
|
||||
AccessTokenInfo tenantBasedAccessTokenInfo = tenantUserTokenMap.get(username);
|
||||
if ((tenantBasedAccessTokenInfo == null ||
|
||||
((System.currentTimeMillis() + DEFAULT_REFRESH_TIME_OFFSET_IN_MILLIS) >
|
||||
tenantBasedAccessTokenInfo.getExpiresIn()))) {
|
||||
|
||||
JWTClient jwtClient = APIIntegrationClientDataHolder.getInstance().getJwtClientManagerService()
|
||||
.getJWTClient();
|
||||
tenantBasedAccessTokenInfo = jwtClient.getAccessToken(oAuthApplication.getClientId(),
|
||||
oAuthApplication.getClientSecret(), username, REQUIRED_SCOPE);
|
||||
tenantBasedAccessTokenInfo.setExpiresIn(
|
||||
System.currentTimeMillis() + (tenantBasedAccessTokenInfo.getExpiresIn() * 1000));
|
||||
if (tenantBasedAccessTokenInfo.getScopes() == null) {
|
||||
throw new APIMClientOAuthException("Failed to retrieve scopes from access token");
|
||||
}
|
||||
|
||||
if (tenantBasedAccessTokenInfo.getScopes().contains(APIM_SUBSCRIBE_SCOPE)) {
|
||||
tenantUserTokenMap.put(username, tenantBasedAccessTokenInfo);
|
||||
}
|
||||
|
||||
}
|
||||
if (tenantBasedAccessTokenInfo.getAccessToken() != null) {
|
||||
String headerValue = "Bearer " + tenantBasedAccessTokenInfo.getAccessToken();
|
||||
template.header("Authorization", headerValue);
|
||||
}
|
||||
} catch (JWTClientException e) {
|
||||
throw new APIMClientOAuthException("failed to retrieve oauth token using jwt", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void removeToken(String username, String tenantDomain) {
|
||||
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
|
||||
username = username + "@" + tenantDomain;
|
||||
}
|
||||
tenantUserTokenMap.remove(username);
|
||||
}
|
||||
|
||||
}
|
@ -1,90 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.apimgt.integration.client.configs;
|
||||
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
/**
|
||||
* This holds the configuration api manager integration.
|
||||
*/
|
||||
@XmlRootElement(name = "APIMConfiguration")
|
||||
public class APIMConfig {
|
||||
|
||||
String dcrEndpoint;
|
||||
String tokenEndpoint;
|
||||
String publisherEndpoint;
|
||||
String storeEndpoint;
|
||||
String username;
|
||||
String password;
|
||||
|
||||
@XmlElement(name = "DCREndpoint", required = true)
|
||||
public String getDcrEndpoint() {
|
||||
return dcrEndpoint;
|
||||
}
|
||||
|
||||
public void setDcrEndpoint(String dcrEndpoint) {
|
||||
this.dcrEndpoint = dcrEndpoint;
|
||||
}
|
||||
|
||||
@XmlElement(name = "TokenEndpoint", required = true)
|
||||
public String getTokenEndpoint() {
|
||||
return tokenEndpoint;
|
||||
}
|
||||
|
||||
public void setTokenEndpoint(String tokenEndpoint) {
|
||||
this.tokenEndpoint = tokenEndpoint;
|
||||
}
|
||||
|
||||
@XmlElement(name = "PublisherEndpoint", required = true)
|
||||
public String getPublisherEndpoint() {
|
||||
return publisherEndpoint;
|
||||
}
|
||||
|
||||
public void setPublisherEndpoint(String publisherEndpoint) {
|
||||
this.publisherEndpoint = publisherEndpoint;
|
||||
}
|
||||
|
||||
@XmlElement(name = "StoreEndpoint", required = true)
|
||||
public String getStoreEndpoint() {
|
||||
return storeEndpoint;
|
||||
}
|
||||
|
||||
public void setStoreEndpoint(String storeEndpoint) {
|
||||
this.storeEndpoint = storeEndpoint;
|
||||
}
|
||||
|
||||
@XmlElement(name = "Username", required = true)
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
@XmlElement(name = "Password", required = true)
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
}
|
@ -1,95 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.apimgt.integration.client.configs;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.wso2.carbon.apimgt.integration.client.exception.APIMClientException;
|
||||
import org.wso2.carbon.apimgt.integration.client.exception.InvalidConfigurationStateException;
|
||||
import org.wso2.carbon.utils.CarbonUtils;
|
||||
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.bind.JAXBContext;
|
||||
import javax.xml.bind.JAXBException;
|
||||
import javax.xml.bind.Unmarshaller;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* This holds the configuration parser for api integration.xml
|
||||
*/
|
||||
public class APIMConfigReader {
|
||||
|
||||
private static APIMConfig config;
|
||||
private static APIMConfigReader configReader= new APIMConfigReader();
|
||||
private static boolean isInitialized = false;
|
||||
private static final String API_INTEGRATION_CONFIG_PATH =
|
||||
CarbonUtils.getCarbonConfigDirPath() + File.separator + "apim-integration.xml";
|
||||
|
||||
private APIMConfigReader() {
|
||||
|
||||
}
|
||||
|
||||
private static String apimIntegrationXmlFilePath = "";
|
||||
|
||||
//TOD file may be a part of another file
|
||||
public static APIMConfigReader getInstance() {
|
||||
if (!isInitialized) {
|
||||
try {
|
||||
init();
|
||||
} catch (APIMClientException e) {
|
||||
throw new InvalidConfigurationStateException("Webapp Authenticator Configuration is not " +
|
||||
"initialized properly");
|
||||
}
|
||||
}
|
||||
return configReader;
|
||||
}
|
||||
|
||||
public static void init() throws APIMClientException {
|
||||
try {
|
||||
File apimConfigFile = new File(API_INTEGRATION_CONFIG_PATH);
|
||||
Document doc = convertToDocument(apimConfigFile);
|
||||
|
||||
JAXBContext ctx = JAXBContext.newInstance(APIMConfig.class);
|
||||
Unmarshaller unmarshaller = ctx.createUnmarshaller();
|
||||
config = (APIMConfig) unmarshaller.unmarshal(doc);
|
||||
isInitialized = true;
|
||||
} catch (JAXBException e) {
|
||||
throw new APIMClientException("Error occurred while un-marshalling APIMConfig", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static Document convertToDocument(File file) throws APIMClientException {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setNamespaceAware(true);
|
||||
try {
|
||||
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
DocumentBuilder docBuilder = factory.newDocumentBuilder();
|
||||
return docBuilder.parse(file);
|
||||
} catch (Exception e) {
|
||||
throw new APIMClientException("Error occurred while parsing file 'apim-integration.xml' to a org.w3c.dom.Document", e);
|
||||
}
|
||||
}
|
||||
|
||||
public APIMConfig getConfig() {
|
||||
return config;
|
||||
}
|
||||
|
||||
}
|
@ -1,58 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.apimgt.integration.client.exception;
|
||||
|
||||
/**
|
||||
* This holds api client exception.
|
||||
*/
|
||||
public class APIMClientException extends Exception {
|
||||
|
||||
private static final long serialVersionUID = -3976392476319079281L;
|
||||
private String responseReason;
|
||||
private int responseStatus;
|
||||
private String methodKey;
|
||||
|
||||
APIMClientException(String methodKey, String reason, int status) {
|
||||
super("Exception occured while invoking " + methodKey + " status = " + status + " reason = " + reason);
|
||||
this.methodKey = methodKey;
|
||||
this.responseReason = reason;
|
||||
this.responseStatus = status;
|
||||
}
|
||||
|
||||
APIMClientException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public APIMClientException(String message, Exception e) {
|
||||
super(message, e);
|
||||
}
|
||||
|
||||
public String getResponseReason() {
|
||||
return responseReason;
|
||||
}
|
||||
|
||||
public int getResponseStatus() {
|
||||
return responseStatus;
|
||||
}
|
||||
|
||||
public String getMethodKey() {
|
||||
return methodKey;
|
||||
}
|
||||
|
||||
}
|
@ -1,58 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.apimgt.integration.client.exception;
|
||||
|
||||
/**
|
||||
* This holds api client exception.
|
||||
*/
|
||||
public class APIMClientOAuthException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = -3976392476319079281L;
|
||||
private String responseReason;
|
||||
private int responseStatus;
|
||||
private String methodKey;
|
||||
|
||||
APIMClientOAuthException(String methodKey, String reason, int status) {
|
||||
super("Exception occured while invoking " + methodKey + " status = " + status + " reason = " + reason);
|
||||
this.methodKey = methodKey;
|
||||
this.responseReason = reason;
|
||||
this.responseStatus = status;
|
||||
}
|
||||
|
||||
public APIMClientOAuthException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public APIMClientOAuthException(String message, Exception e) {
|
||||
super(message, e);
|
||||
}
|
||||
|
||||
public String getResponseReason() {
|
||||
return responseReason;
|
||||
}
|
||||
|
||||
public int getResponseStatus() {
|
||||
return responseStatus;
|
||||
}
|
||||
|
||||
public String getMethodKey() {
|
||||
return methodKey;
|
||||
}
|
||||
|
||||
}
|
@ -1,78 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.apimgt.integration.client.exception;
|
||||
|
||||
/**
|
||||
* This error is thrown when there is an issue with the client.
|
||||
*/
|
||||
public class InvalidConfigurationStateException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = -3151279311329070397L;
|
||||
|
||||
private String errorMessage;
|
||||
private int errorCode;
|
||||
|
||||
public InvalidConfigurationStateException(int errorCode, String message) {
|
||||
super(message);
|
||||
this.errorCode = errorCode;
|
||||
}
|
||||
|
||||
public InvalidConfigurationStateException(int errorCode, String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
this.errorCode = errorCode;
|
||||
}
|
||||
|
||||
public int getErrorCode() {
|
||||
return errorCode;
|
||||
}
|
||||
|
||||
|
||||
public String getErrorMessage() {
|
||||
return errorMessage;
|
||||
}
|
||||
|
||||
public void setErrorMessage(String errorMessage) {
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
|
||||
public InvalidConfigurationStateException(String msg, Exception nestedEx) {
|
||||
super(msg, nestedEx);
|
||||
setErrorMessage(msg);
|
||||
}
|
||||
|
||||
public InvalidConfigurationStateException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
setErrorMessage(message);
|
||||
}
|
||||
|
||||
public InvalidConfigurationStateException(String msg) {
|
||||
super(msg);
|
||||
setErrorMessage(msg);
|
||||
}
|
||||
|
||||
public InvalidConfigurationStateException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public InvalidConfigurationStateException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
}
|
@ -1,45 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.apimgt.integration.client.internal;
|
||||
|
||||
|
||||
import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService;
|
||||
|
||||
/**
|
||||
* This holds the required service for this component
|
||||
*/
|
||||
public class APIIntegrationClientDataHolder {
|
||||
private static APIIntegrationClientDataHolder thisInstance = new APIIntegrationClientDataHolder();
|
||||
private JWTClientManagerService jwtClientManagerService;
|
||||
private APIIntegrationClientDataHolder() {
|
||||
}
|
||||
|
||||
|
||||
public static APIIntegrationClientDataHolder getInstance() {
|
||||
return thisInstance;
|
||||
}
|
||||
|
||||
public void setJwtClientManagerService(JWTClientManagerService jwtClientManagerService) {
|
||||
this.jwtClientManagerService = jwtClientManagerService;
|
||||
}
|
||||
|
||||
public JWTClientManagerService getJwtClientManagerService() {
|
||||
return jwtClientManagerService;
|
||||
}
|
||||
}
|
@ -1,81 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.apimgt.integration.client.internal;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.osgi.framework.BundleContext;
|
||||
import org.osgi.service.component.ComponentContext;
|
||||
import org.wso2.carbon.apimgt.integration.client.IntegrationClientServiceImpl;
|
||||
import org.wso2.carbon.apimgt.integration.client.configs.APIMConfigReader;
|
||||
import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService;
|
||||
import org.osgi.service.component.annotations.*;
|
||||
import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService;
|
||||
|
||||
@Component(
|
||||
name = "org.wso2.carbon.api.integration.client",
|
||||
immediate = true)
|
||||
public class APIIntegrationClientServiceComponent {
|
||||
|
||||
private static Log log = LogFactory.getLog(APIIntegrationClientServiceComponent.class);
|
||||
|
||||
@Activate
|
||||
protected void activate(ComponentContext componentContext) {
|
||||
try {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Initializing apimgt client bundle");
|
||||
}
|
||||
|
||||
/* Initializing webapp publisher configuration */
|
||||
APIMConfigReader.init();
|
||||
BundleContext bundleContext = componentContext.getBundleContext();
|
||||
bundleContext.registerService(IntegrationClientService.class.getName(), IntegrationClientServiceImpl.getInstance(), null);
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("apimgt client bundle has been successfully initialized");
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
log.error("Error occurred while initializing apimgt client bundle", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Deactivate
|
||||
protected void deactivate(ComponentContext componentContext) {
|
||||
//do nothing
|
||||
}
|
||||
|
||||
@Reference(
|
||||
name = "api.integration.client.service",
|
||||
service = org.wso2.carbon.apimgt.impl.APIManagerConfigurationService.class,
|
||||
cardinality = ReferenceCardinality.MANDATORY,
|
||||
policy = ReferencePolicy.DYNAMIC,
|
||||
bind = "setJWTClientManagerService",
|
||||
unbind = "unsetJWTClientManagerService")
|
||||
protected void setJWTClientManagerService(JWTClientManagerService jwtClientManagerService) {
|
||||
if (jwtClientManagerService != null) {
|
||||
log.debug("jwtClientManagerService service is initialized");
|
||||
}
|
||||
APIIntegrationClientDataHolder.getInstance().setJwtClientManagerService(jwtClientManagerService);
|
||||
}
|
||||
|
||||
protected void unsetJWTClientManagerService(JWTClientManagerService jwtClientManagerService) {
|
||||
APIIntegrationClientDataHolder.getInstance().setJwtClientManagerService(null);
|
||||
}
|
||||
|
||||
}
|
@ -1,96 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.apimgt.integration.client.model;
|
||||
|
||||
/**
|
||||
* DTO fo DCR request.
|
||||
*/
|
||||
public class ClientProfile {
|
||||
|
||||
private String clientName;
|
||||
private String callbackUrl;
|
||||
private String tokenScope;
|
||||
private String owner;
|
||||
private String grantType;
|
||||
private boolean saasApp;
|
||||
|
||||
public String getClientName() {
|
||||
return clientName;
|
||||
}
|
||||
|
||||
public void setClientName(String clientName) {
|
||||
this.clientName = clientName;
|
||||
}
|
||||
|
||||
public String getCallbackUrl() {
|
||||
return callbackUrl;
|
||||
}
|
||||
|
||||
public void setCallbackUrl(String callbackUrl) {
|
||||
this.callbackUrl = callbackUrl;
|
||||
}
|
||||
|
||||
public String getTokenScope() {
|
||||
return tokenScope;
|
||||
}
|
||||
|
||||
public void setTokenScope(String tokenScope) {
|
||||
this.tokenScope = tokenScope;
|
||||
}
|
||||
|
||||
public String getOwner() {
|
||||
return owner;
|
||||
}
|
||||
|
||||
public void setOwner(String owner) {
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
public String getGrantType() {
|
||||
return grantType;
|
||||
}
|
||||
|
||||
public void setGrantType(String grantTypem) {
|
||||
this.grantType = grantTypem;
|
||||
}
|
||||
|
||||
public boolean isSaasApp() {
|
||||
return saasApp;
|
||||
}
|
||||
|
||||
public void setSaasApp(boolean saasApp) {
|
||||
this.saasApp = saasApp;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("{\n");
|
||||
|
||||
sb.append(" clientName: ").append(clientName).append("\n");
|
||||
sb.append(" callbackUrl: ").append("callbackUrl").append("\n");
|
||||
sb.append(" grantType: ").append(grantType).append("\n");
|
||||
sb.append(" tokenScope: ").append(tokenScope).append("\n");
|
||||
sb.append(" owner: ").append(owner).append("\n");
|
||||
sb.append(" saasApp: ").append(saasApp).append("\n");
|
||||
sb.append("}\n");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
@ -1,36 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.apimgt.integration.client.model;
|
||||
|
||||
import javax.ws.rs.*;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
|
||||
/**
|
||||
* DCR Rest resource.
|
||||
*/
|
||||
@Path("/")
|
||||
public interface DCRClient {
|
||||
|
||||
// DCR APIs
|
||||
@POST
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
OAuthApplication register(ClientProfile registrationProfile);
|
||||
|
||||
}
|
@ -1,103 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.apimgt.integration.client.model;
|
||||
|
||||
public class OAuthApplication {
|
||||
|
||||
private String jsonString;
|
||||
private String appOwner;
|
||||
private String clientName;
|
||||
private String callBackURL;
|
||||
private String isSaasApplication;
|
||||
private String clientId;
|
||||
private String clientSecret;
|
||||
|
||||
public String getJsonString() {
|
||||
return jsonString;
|
||||
}
|
||||
|
||||
public void setJsonString(String jsonString) {
|
||||
this.jsonString = jsonString;
|
||||
}
|
||||
|
||||
public String getAppOwner() {
|
||||
return appOwner;
|
||||
}
|
||||
|
||||
public void setAppOwner(String appOwner) {
|
||||
this.appOwner = appOwner;
|
||||
}
|
||||
|
||||
public String getClientName() {
|
||||
return clientName;
|
||||
}
|
||||
|
||||
public void setClientName(String clientName) {
|
||||
this.clientName = clientName;
|
||||
}
|
||||
|
||||
public String getCallBackURL() {
|
||||
return callBackURL;
|
||||
}
|
||||
|
||||
public void setCallBackURL(String callBackURL) {
|
||||
this.callBackURL = callBackURL;
|
||||
}
|
||||
|
||||
public String getIsSaasApplication() {
|
||||
return isSaasApplication;
|
||||
}
|
||||
|
||||
public void setIsSaasApplication(String isSaasApplication) {
|
||||
this.isSaasApplication = isSaasApplication;
|
||||
}
|
||||
|
||||
public String getClientId() {
|
||||
return clientId;
|
||||
}
|
||||
|
||||
public void setClientId(String clientId) {
|
||||
this.clientId = clientId;
|
||||
}
|
||||
|
||||
public String getClientSecret() {
|
||||
return clientSecret;
|
||||
}
|
||||
|
||||
public void setClientSecret(String clientSecret) {
|
||||
this.clientSecret = clientSecret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class OAuthApplication {\n");
|
||||
|
||||
sb.append(" jsonString: ").append(jsonString).append("\n");
|
||||
sb.append(" appOwner: ").append(appOwner).append("\n");
|
||||
sb.append(" clientName: ").append(clientName).append("\n");
|
||||
sb.append(" callBackURL: ").append(callBackURL).append("\n");
|
||||
sb.append(" isSaasApplication: ").append(isSaasApplication).append("\n");
|
||||
sb.append(" clientId: ").append(isSaasApplication).append("\n");
|
||||
sb.append(" clientSecret: ").append(clientSecret).append("\n");
|
||||
sb.append("}\n");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
@ -1,96 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.wso2.carbon.apimgt.integration.client.publisher;
|
||||
|
||||
import feign.Feign;
|
||||
import feign.Logger;
|
||||
import feign.RequestInterceptor;
|
||||
import feign.gson.GsonDecoder;
|
||||
import feign.gson.GsonEncoder;
|
||||
import feign.okhttp.OkHttpClient;
|
||||
import feign.slf4j.Slf4jLogger;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.apimgt.integration.client.configs.APIMConfigReader;
|
||||
import org.wso2.carbon.apimgt.integration.generated.client.publisher.api.*;
|
||||
import org.wso2.carbon.core.util.Utils;
|
||||
|
||||
/**
|
||||
* Publisher client generated using swagger.
|
||||
*/
|
||||
public class PublisherClient {
|
||||
|
||||
private static final Log log = LogFactory.getLog(PublisherClient.class);
|
||||
private APIIndividualApi api = null;
|
||||
private APICollectionApi apis = null;
|
||||
private DocumentIndividualApi document = null;
|
||||
private ApplicationIndividualApi application = null;
|
||||
private EnvironmentCollectionApi environments = null;
|
||||
private SubscriptionCollectionApi subscriptions = null;
|
||||
private ThrottlingTierCollectionApi tiers = null;
|
||||
|
||||
|
||||
/**
|
||||
* PublisherClient constructor - Initialize a PublisherClient instance
|
||||
*
|
||||
*/
|
||||
public PublisherClient(RequestInterceptor requestInterceptor) {
|
||||
Feign.Builder builder = Feign.builder().client(new OkHttpClient(
|
||||
org.wso2.carbon.apimgt.integration.client.util.Utils.getSSLClient())).logger(new
|
||||
Slf4jLogger())
|
||||
.logLevel(Logger.Level.FULL)
|
||||
.requestInterceptor(requestInterceptor).encoder(new GsonEncoder()).decoder(new GsonDecoder());
|
||||
String basePath = Utils.replaceSystemProperty(APIMConfigReader.getInstance().getConfig().getPublisherEndpoint());
|
||||
|
||||
api = builder.target(APIIndividualApi.class, basePath);
|
||||
apis = builder.target(APICollectionApi.class, basePath);
|
||||
document = builder.target(DocumentIndividualApi.class, basePath);
|
||||
application = builder.target(ApplicationIndividualApi.class, basePath);
|
||||
environments = builder.target(EnvironmentCollectionApi.class, basePath);
|
||||
subscriptions = builder.target(SubscriptionCollectionApi.class, basePath);
|
||||
tiers = builder.target(ThrottlingTierCollectionApi.class, basePath);
|
||||
}
|
||||
|
||||
public APIIndividualApi getApi() {
|
||||
return api;
|
||||
}
|
||||
|
||||
public APICollectionApi getApis() {
|
||||
return apis;
|
||||
}
|
||||
|
||||
public DocumentIndividualApi getDocument() {
|
||||
return document;
|
||||
}
|
||||
|
||||
public ApplicationIndividualApi getApplication() {
|
||||
return application;
|
||||
}
|
||||
|
||||
public EnvironmentCollectionApi getEnvironments() {
|
||||
return environments;
|
||||
}
|
||||
|
||||
public SubscriptionCollectionApi getSubscriptions() {
|
||||
return subscriptions;
|
||||
}
|
||||
|
||||
public ThrottlingTierCollectionApi getTiers() {
|
||||
return tiers;
|
||||
}
|
||||
}
|
@ -1,44 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.wso2.carbon.apimgt.integration.client.service;
|
||||
|
||||
|
||||
import org.wso2.carbon.apimgt.integration.client.publisher.PublisherClient;
|
||||
import org.wso2.carbon.apimgt.integration.client.store.StoreClient;
|
||||
|
||||
/**
|
||||
* This is a service that can be called upon to access store and publisher.
|
||||
*/
|
||||
public interface IntegrationClientService {
|
||||
|
||||
|
||||
void resetUserInfo(String username, String tenantDomain);
|
||||
|
||||
/**
|
||||
*
|
||||
* @return API Store Client.
|
||||
*/
|
||||
StoreClient getStoreClient();
|
||||
|
||||
/**
|
||||
*
|
||||
* @return API Publisher Client.
|
||||
*/
|
||||
PublisherClient getPublisherClient();
|
||||
|
||||
}
|
@ -1,117 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.wso2.carbon.apimgt.integration.client.store;
|
||||
|
||||
import feign.Feign;
|
||||
import feign.Logger;
|
||||
import feign.Request;
|
||||
import feign.RequestInterceptor;
|
||||
import feign.Retryer;
|
||||
import feign.gson.GsonDecoder;
|
||||
import feign.gson.GsonEncoder;
|
||||
import feign.okhttp.OkHttpClient;
|
||||
import feign.slf4j.Slf4jLogger;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.apimgt.integration.client.configs.APIMConfigReader;
|
||||
import org.wso2.carbon.apimgt.integration.generated.client.store.api.*;
|
||||
import org.wso2.carbon.core.util.Utils;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* API Store client, created using swagger gen.
|
||||
*/
|
||||
public class StoreClient {
|
||||
|
||||
private static final org.apache.commons.logging.Log log = LogFactory.getLog(StoreClient.class);
|
||||
private APICollectionApi apis = null;
|
||||
private APIIndividualApi individualApi = null;
|
||||
private ApplicationCollectionApi applications = null;
|
||||
private ApplicationIndividualApi individualApplication = null;
|
||||
private SubscriptionCollectionApi subscriptions = null;
|
||||
private SubscriptionIndividualApi individualSubscription = null;
|
||||
private SubscriptionMultitpleApi subscriptionMultitpleApi = null;
|
||||
private ThrottlingTierIndividualApi individualTier = null;
|
||||
private TagCollectionApi tags = null;
|
||||
private ThrottlingTierCollectionApi tiers = null;
|
||||
|
||||
|
||||
public StoreClient(RequestInterceptor requestInterceptor) {
|
||||
|
||||
Feign.Builder builder = Feign.builder().client(new OkHttpClient(
|
||||
org.wso2.carbon.apimgt.integration.client.util.Utils.getSSLClient())).logger(new
|
||||
Slf4jLogger())
|
||||
.logLevel(Logger.Level.FULL)
|
||||
.requestInterceptor(requestInterceptor).encoder(new GsonEncoder()).decoder(new GsonDecoder());
|
||||
String basePath = Utils.replaceSystemProperty(APIMConfigReader.getInstance().getConfig().getStoreEndpoint());
|
||||
|
||||
apis = builder.target(APICollectionApi.class, basePath);
|
||||
individualApi = builder.target(APIIndividualApi.class, basePath);
|
||||
applications = builder.target(ApplicationCollectionApi.class, basePath);
|
||||
individualApplication = builder.target(ApplicationIndividualApi.class, basePath);
|
||||
subscriptions = builder.target(SubscriptionCollectionApi.class, basePath);
|
||||
individualSubscription = builder.target(SubscriptionIndividualApi.class, basePath);
|
||||
subscriptionMultitpleApi = builder.target(SubscriptionMultitpleApi.class, basePath);
|
||||
tags = builder.target(TagCollectionApi.class, basePath);
|
||||
individualTier = builder.target(ThrottlingTierIndividualApi.class, basePath);
|
||||
tiers = builder.retryer(new Retryer.Default(100L, TimeUnit.SECONDS.toMillis(1L), 1))
|
||||
.options(new Request.Options(10000, 5000))
|
||||
.target(ThrottlingTierCollectionApi.class, basePath);
|
||||
|
||||
}
|
||||
|
||||
public APICollectionApi getApis() {
|
||||
return apis;
|
||||
}
|
||||
|
||||
public APIIndividualApi getIndividualApi() {
|
||||
return individualApi;
|
||||
}
|
||||
|
||||
public ApplicationCollectionApi getApplications() {
|
||||
return applications;
|
||||
}
|
||||
|
||||
public ApplicationIndividualApi getIndividualApplication() {
|
||||
return individualApplication;
|
||||
}
|
||||
|
||||
public SubscriptionCollectionApi getSubscriptions() {
|
||||
return subscriptions;
|
||||
}
|
||||
|
||||
public SubscriptionIndividualApi getIndividualSubscription() {
|
||||
return individualSubscription;
|
||||
}
|
||||
|
||||
public ThrottlingTierIndividualApi getIndividualTier() {
|
||||
return individualTier;
|
||||
}
|
||||
|
||||
public TagCollectionApi getTags() {
|
||||
return tags;
|
||||
}
|
||||
|
||||
public ThrottlingTierCollectionApi getTiers() {
|
||||
return tiers;
|
||||
}
|
||||
|
||||
public SubscriptionMultitpleApi getSubscriptionMultitpleApi() {
|
||||
return subscriptionMultitpleApi;
|
||||
}
|
||||
}
|
@ -1,238 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.apimgt.integration.client.util;
|
||||
|
||||
import okhttp3.OkHttpClient;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.base.ServerConfiguration;
|
||||
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.KeyManagerFactory;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSession;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Proxy;
|
||||
import java.net.ProxySelector;
|
||||
import java.net.SocketAddress;
|
||||
import java.net.URI;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.KeyStore;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.UnrecoverableKeyException;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class Utils {
|
||||
|
||||
private static final Log log = LogFactory.getLog(Utils.class);
|
||||
|
||||
private static final String KEY_STORE_TYPE = "JKS";
|
||||
/**
|
||||
* Default truststore type of the client
|
||||
*/
|
||||
private static final String TRUST_STORE_TYPE = "JKS";
|
||||
/**
|
||||
* Default keymanager type of the client
|
||||
*/
|
||||
private static final String KEY_MANAGER_TYPE = "SunX509"; //Default Key Manager Type
|
||||
/**
|
||||
* Default trustmanager type of the client
|
||||
*/
|
||||
private static final String TRUST_MANAGER_TYPE = "SunX509"; //Default Trust Manager Type
|
||||
|
||||
private static final String SSLV3 = "SSLv3";
|
||||
|
||||
private static final String DEFAULT_HOST = "localhost";
|
||||
|
||||
private static final String DEFAULT_HOST_IP = "127.0.0.1";
|
||||
|
||||
|
||||
//This method is only used if the mb features are within DAS.
|
||||
public static String replaceProperties(String text) {
|
||||
String regex = "\\$\\{(.*?)\\}";
|
||||
Pattern pattern = Pattern.compile(regex);
|
||||
Matcher matchPattern = pattern.matcher(text);
|
||||
while (matchPattern.find()) {
|
||||
String sysPropertyName = matchPattern.group(1);
|
||||
String sysPropertyValue = System.getProperty(sysPropertyName);
|
||||
if (sysPropertyValue != null && !sysPropertyName.isEmpty()) {
|
||||
text = text.replaceAll("\\$\\{(" + sysPropertyName + ")\\}", sysPropertyValue);
|
||||
}
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
public static OkHttpClient getSSLClient() {
|
||||
|
||||
boolean isIgnoreHostnameVerification = Boolean.parseBoolean(System.getProperty("org.wso2"
|
||||
+ ".ignoreHostnameVerification"));
|
||||
OkHttpClient okHttpClient;
|
||||
final String proxyHost = System.getProperty("http.proxyHost");
|
||||
final String proxyPort = System.getProperty("http.proxyPort");
|
||||
final String nonProxyHostsValue = System.getProperty("http.nonProxyHosts");
|
||||
|
||||
final ProxySelector proxySelector = new ProxySelector() {
|
||||
@Override
|
||||
public List<Proxy> select(URI uri) {
|
||||
List<Proxy> proxyList = new ArrayList<>();
|
||||
String host = uri.getHost();
|
||||
|
||||
if (!StringUtils.isEmpty(host)) {
|
||||
if (host.startsWith(DEFAULT_HOST_IP) || host.startsWith(DEFAULT_HOST) || StringUtils
|
||||
.isEmpty(nonProxyHostsValue) || StringUtils.contains(nonProxyHostsValue, host) ||
|
||||
StringUtils.isEmpty(proxyHost) || StringUtils.isEmpty(proxyPort)) {
|
||||
proxyList.add(Proxy.NO_PROXY);
|
||||
} else {
|
||||
proxyList.add(new Proxy(Proxy.Type.HTTP,
|
||||
new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort))));
|
||||
}
|
||||
} else {
|
||||
log.error("Host is null. Host could not be empty or null");
|
||||
}
|
||||
return proxyList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
|
||||
throw new UnsupportedOperationException("Not supported yet.");
|
||||
}
|
||||
};
|
||||
|
||||
X509TrustManager trustAllCerts = new X509TrustManager() {
|
||||
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
|
||||
return new java.security.cert.X509Certificate[0];
|
||||
}
|
||||
public void checkClientTrusted(
|
||||
java.security.cert.X509Certificate[] certs, String authType) {
|
||||
}
|
||||
public void checkServerTrusted(
|
||||
java.security.cert.X509Certificate[] certs, String authType) {
|
||||
}
|
||||
};
|
||||
if(isIgnoreHostnameVerification) {
|
||||
okHttpClient = new OkHttpClient.Builder()
|
||||
.sslSocketFactory(getSimpleTrustedSSLSocketFactory(), trustAllCerts)
|
||||
.hostnameVerifier(new HostnameVerifier() {
|
||||
@Override
|
||||
public boolean verify(String s, SSLSession sslSession) {
|
||||
return true;
|
||||
}
|
||||
}).proxySelector(proxySelector).build();
|
||||
return okHttpClient;
|
||||
}else {
|
||||
SSLSocketFactory trustedSSLSocketFactory = getTrustedSSLSocketFactory();
|
||||
okHttpClient = new OkHttpClient.Builder().sslSocketFactory(trustedSSLSocketFactory)
|
||||
.proxySelector(proxySelector).build();
|
||||
return okHttpClient;
|
||||
}
|
||||
}
|
||||
|
||||
private static SSLSocketFactory getSimpleTrustedSSLSocketFactory() {
|
||||
try {
|
||||
TrustManager[] trustAllCerts = new TrustManager[]{
|
||||
new X509TrustManager() {
|
||||
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
|
||||
return null;
|
||||
}
|
||||
public void checkClientTrusted(
|
||||
java.security.cert.X509Certificate[] certs, String authType) {
|
||||
}
|
||||
public void checkServerTrusted(
|
||||
java.security.cert.X509Certificate[] certs, String authType) {
|
||||
}
|
||||
}
|
||||
};
|
||||
SSLContext sc = SSLContext.getInstance("SSL");
|
||||
sc.init(null, trustAllCerts, new java.security.SecureRandom());
|
||||
return sc.getSocketFactory();
|
||||
} catch (KeyManagementException | NoSuchAlgorithmException e) {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static SSLSocketFactory getTrustedSSLSocketFactory() {
|
||||
try {
|
||||
String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password");
|
||||
String keyStoreLocation = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Location");
|
||||
String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty(
|
||||
"Security.TrustStore.Password");
|
||||
String trustStoreLocation = ServerConfiguration.getInstance().getFirstProperty(
|
||||
"Security.TrustStore.Location");
|
||||
KeyStore keyStore = loadKeyStore(keyStoreLocation,keyStorePassword,KEY_STORE_TYPE);
|
||||
KeyStore trustStore = loadTrustStore(trustStoreLocation,trustStorePassword);
|
||||
|
||||
return initSSLConnection(keyStore,keyStorePassword,trustStore);
|
||||
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException
|
||||
|CertificateException | IOException | UnrecoverableKeyException e) {
|
||||
log.error("Error while creating the SSL socket factory due to "+e.getMessage(),e);
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static SSLSocketFactory initSSLConnection(KeyStore keyStore,String keyStorePassword,KeyStore trustStore) throws NoSuchAlgorithmException, UnrecoverableKeyException,
|
||||
KeyStoreException, KeyManagementException {
|
||||
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
|
||||
keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
|
||||
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
|
||||
trustManagerFactory.init(trustStore);
|
||||
|
||||
// Create and initialize SSLContext for HTTPS communication
|
||||
SSLContext sslContext = SSLContext.getInstance(SSLV3);
|
||||
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
|
||||
SSLContext.setDefault(sslContext);
|
||||
return sslContext.getSocketFactory();
|
||||
}
|
||||
|
||||
|
||||
private static KeyStore loadKeyStore(String keyStorePath, String ksPassword,String type)
|
||||
throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
|
||||
InputStream fileInputStream = null;
|
||||
try {
|
||||
char[] keypassChar = ksPassword.toCharArray();
|
||||
KeyStore keyStore = KeyStore.getInstance(type);
|
||||
fileInputStream = new FileInputStream(keyStorePath);
|
||||
keyStore.load(fileInputStream, keypassChar);
|
||||
return keyStore;
|
||||
} finally {
|
||||
if (fileInputStream != null) {
|
||||
fileInputStream.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static KeyStore loadTrustStore(String trustStorePath, String tsPassword)
|
||||
throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
|
||||
return loadKeyStore(trustStorePath,tsPassword,TRUST_STORE_TYPE);
|
||||
}
|
||||
}
|
@ -1,212 +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.generated.client</artifactId>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - API Management Integration Generated Client</name>
|
||||
<description>WSO2 Carbon - API Management Integration Client</description>
|
||||
<url>https://entgra.io</url>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<!--swagger yaml is used to generate code-->
|
||||
<plugin>
|
||||
<groupId>io.swagger</groupId>
|
||||
<artifactId>swagger-codegen-maven-plugin</artifactId>
|
||||
<version>2.2.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>process-resources</phase>
|
||||
<id>publisher</id>
|
||||
<goals>
|
||||
<goal>generate</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<inputSpec>${project.basedir}/src/main/resources/publisher-api.yaml</inputSpec>
|
||||
<language>java</language>
|
||||
<configOptions>
|
||||
<apiPackage>${project.artifactId}.publisher.api</apiPackage>
|
||||
<modelPackage>${project.artifactId}.publisher.model</modelPackage>
|
||||
</configOptions>
|
||||
<library>feign</library>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<phase>process-resources</phase>
|
||||
<id>store</id>
|
||||
<goals>
|
||||
<goal>generate</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<inputSpec>${project.basedir}/src/main/resources/store-api.yaml</inputSpec>
|
||||
<language>java</language>
|
||||
<configOptions>
|
||||
<apiPackage>${project.artifactId}.store.api</apiPackage>
|
||||
<modelPackage>${project.artifactId}.store.model</modelPackage>
|
||||
</configOptions>
|
||||
<library>feign</library>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>com.google.code.maven-replacer-plugin</groupId>
|
||||
<artifactId>replacer</artifactId>
|
||||
<executions>
|
||||
<!-- Replace java code that is generated from swagger to fix swagger client generation issues. -->
|
||||
<execution>
|
||||
<phase>process-resources</phase>
|
||||
<id>replace-for-swagger-genenerated-code-publisher</id>
|
||||
<goals>
|
||||
<goal>replace</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<file>${project.basedir}/target/generated-sources/swagger/src/main/java/org/wso2/carbon/apimgt/integration/generated/client/publisher/model/API.java</file>
|
||||
<replacements>
|
||||
<replacement>
|
||||
<token>CURRENT_TENANT</token>
|
||||
<value>current_tenant</value>
|
||||
</replacement>
|
||||
<replacement>
|
||||
<token>ALL_TENANTS</token>
|
||||
<value>all_tenants</value>
|
||||
</replacement>
|
||||
<replacement>
|
||||
<token>SPECIFIC_TENANTS</token>
|
||||
<value>specific_tenants</value>
|
||||
</replacement>
|
||||
</replacements>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
<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>
|
||||
<Export-Package>
|
||||
org.wso2.carbon.apimgt.integration.generated.client.publisher.api.*,
|
||||
org.wso2.carbon.apimgt.integration.generated.client.publisher.model.*,
|
||||
org.wso2.carbon.apimgt.integration.generated.client.store.api.*,
|
||||
org.wso2.carbon.apimgt.integration.generated.client.store.model.*
|
||||
</Export-Package>
|
||||
<Import-Package>
|
||||
feign;version="${io.github.openfeign.version.range}",
|
||||
feign.jackson;version="${io.github.openfeign.version.range}",
|
||||
feign.codec;version="${io.github.openfeign.version.range}",
|
||||
feign.auth;version="${io.github.openfeign.version.range}",
|
||||
feign.gson;version="${io.github.openfeign.version.range}",
|
||||
feign.slf4j;version="${io.github.openfeign.version.range}",
|
||||
com.google.gson,
|
||||
com.fasterxml.jackson.core;resolution:=optional,
|
||||
com.fasterxml.jackson.annotation,
|
||||
com.fasterxml.jackson.databind;resolution:=optional,
|
||||
io.swagger.annotations,
|
||||
javax.net.ssl,
|
||||
com.fasterxml.jackson.datatype.joda;resolution:=optional,
|
||||
org.apache.oltu.oauth2.client.*;resolution:=optional,
|
||||
org.apache.oltu.oauth2.common.*;resolution:=optional,
|
||||
org.junit;resolution:=optional,
|
||||
</Import-Package>
|
||||
<Embed-Dependency>
|
||||
jsr311-api,
|
||||
feign-jaxrs
|
||||
</Embed-Dependency>
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<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>org.apache.oltu.oauth2</groupId>
|
||||
<artifactId>org.apache.oltu.oauth2.client</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.openfeign</groupId>
|
||||
<artifactId>feign-slf4j</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.orbit.com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson-databind.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-joda</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<maven.javadoc.skip>true</maven.javadoc.skip>
|
||||
</properties>
|
||||
</project>
|
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
@ -1,158 +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>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<artifactId>device-mgt</artifactId>
|
||||
<version>5.0.0-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - Device Analytics</name>
|
||||
<description>WSO2 Carbon - Device Analytics</description>
|
||||
<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.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.tomcat</groupId>
|
||||
<artifactId>tomcat</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.tomcat</groupId>
|
||||
<artifactId>tomcat-servlet-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.ops4j.pax.logging</groupId>
|
||||
<artifactId>pax-logging-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.utils</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics-common</groupId>
|
||||
<artifactId>org.wso2.carbon.databridge.agent</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics-common</groupId>
|
||||
<artifactId>org.wso2.carbon.databridge.commons</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.securevault</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.sling</groupId>
|
||||
<artifactId>org.apache.sling.testing.osgi-mock</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
<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>Data Publisher</Bundle-Description>
|
||||
<Private-Package>org.wso2.carbon.device.mgt.analytics.data.publisher.internal</Private-Package>
|
||||
<Export-Package>
|
||||
!org.wso2.carbon.device.mgt.analytics.data.publisher.internal,
|
||||
org.wso2.carbon.device.mgt.analytics.data.publisher.*;version="${io.entgra.device.mgt.core.version}"
|
||||
</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.*,
|
||||
org.wso2.carbon.utils.multitenancy,
|
||||
org.wso2.carbon.context;version="${carbon.kernel.version.range}",
|
||||
org.wso2.carbon.utils;version="${carbon.kernel.version.range}",
|
||||
org.wso2.carbon.databridge.*;version="${carbon.analytics.common.version.range}",
|
||||
org.json;version="${commons-json.version}",
|
||||
javax.xml.*,
|
||||
javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional,
|
||||
org.w3c.dom,
|
||||
org.wso2.carbon.base,
|
||||
org.wso2.carbon.utils.multitenancy
|
||||
</Import-Package>
|
||||
</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>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<suiteXmlFiles>
|
||||
<suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
|
||||
</suiteXmlFiles>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
@ -1,124 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.analytics.data.publisher;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.w3c.dom.Document;
|
||||
import org.wso2.carbon.databridge.agent.exception.DataEndpointConfigurationException;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
|
||||
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class DataPublisherUtil {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DataPublisherUtil.class);
|
||||
|
||||
private DataPublisherUtil(){
|
||||
}
|
||||
|
||||
public static Document convertToDocument(File file) throws DataPublisherConfigurationException {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setNamespaceAware(true);
|
||||
try {
|
||||
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||
DocumentBuilder docBuilder = factory.newDocumentBuilder();
|
||||
return docBuilder.parse(file);
|
||||
} catch (Exception e) {
|
||||
throw new DataPublisherConfigurationException("Error occurred while parsing file, while converting " +
|
||||
"to a org.w3c.dom.Document", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static ArrayList<String> getEndpointGroups(String urlSet) {
|
||||
ArrayList<String> urlGroups = new ArrayList<>();
|
||||
Pattern regex = Pattern.compile("\\{.*?\\}");
|
||||
Matcher regexMatcher = regex.matcher(urlSet);
|
||||
|
||||
while(regexMatcher.find()) {
|
||||
urlGroups.add(regexMatcher.group().replace("{", "").replace("}", ""));
|
||||
}
|
||||
|
||||
if (urlGroups.size() == 0) {
|
||||
urlGroups.add(urlSet.replace("{", "").replace("}", ""));
|
||||
}
|
||||
return urlGroups;
|
||||
}
|
||||
|
||||
public static String[] getEndpoints(String aURLGroup) throws DataEndpointConfigurationException {
|
||||
boolean isLBURL = false;
|
||||
boolean isFailOverURL = false;
|
||||
if (aURLGroup.contains(",")) {
|
||||
isLBURL = true;
|
||||
}
|
||||
|
||||
if (aURLGroup.contains("|")) {
|
||||
isFailOverURL = true;
|
||||
}
|
||||
|
||||
if (isLBURL && isFailOverURL) {
|
||||
String msg = "Invalid data endpoints URL set provided : " + aURLGroup +
|
||||
", a URL group can be configured as failover OR load balancing endpoints.";
|
||||
log.error(msg);
|
||||
throw new DataEndpointConfigurationException(msg);
|
||||
} else {
|
||||
String[] urls;
|
||||
if (isLBURL) {
|
||||
urls = aURLGroup.split(",");
|
||||
} else if (isFailOverURL) {
|
||||
urls = aURLGroup.split("\\|");
|
||||
} else {
|
||||
urls = new String[]{aURLGroup};
|
||||
}
|
||||
return urls;
|
||||
}
|
||||
}
|
||||
|
||||
public static int obtainHashId(String deviceId, int urlGroupsCount) {
|
||||
byte[] chars = deviceId.getBytes();
|
||||
int sum = 0;
|
||||
for (byte b : chars) {
|
||||
sum += b;
|
||||
}
|
||||
return sum % urlGroupsCount;
|
||||
}
|
||||
|
||||
@SuppressWarnings("Duplicates")
|
||||
public static String replaceProperty(String urlWithPlaceholders) {
|
||||
String regex = "\\$\\{(.*?)\\}";
|
||||
Pattern pattern = Pattern.compile(regex);
|
||||
Matcher matchPattern = pattern.matcher(urlWithPlaceholders);
|
||||
while (matchPattern.find()) {
|
||||
String sysPropertyName = matchPattern.group(1);
|
||||
String sysPropertyValue = System.getProperty(sysPropertyName);
|
||||
if (sysPropertyValue != null && !sysPropertyName.isEmpty()) {
|
||||
urlWithPlaceholders = urlWithPlaceholders.replaceAll("\\$\\{(" + sysPropertyName + ")\\}", sysPropertyValue);
|
||||
}
|
||||
}
|
||||
return urlWithPlaceholders;
|
||||
}
|
||||
|
||||
}
|
@ -1,110 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.analytics.data.publisher;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.databridge.agent.DataPublisher;
|
||||
import org.wso2.carbon.databridge.agent.exception.DataEndpointAgentConfigurationException;
|
||||
import org.wso2.carbon.databridge.agent.exception.DataEndpointAuthenticationException;
|
||||
import org.wso2.carbon.databridge.agent.exception.DataEndpointConfigurationException;
|
||||
import org.wso2.carbon.databridge.agent.exception.DataEndpointException;
|
||||
import org.wso2.carbon.databridge.commons.exception.TransportException;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.config.AnalyticsConfiguration;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherServiceImpl;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* This is used to manage data publisher per tenant.
|
||||
*/
|
||||
public class DeviceDataPublisher {
|
||||
|
||||
private static Log log = LogFactory.getLog(EventsPublisherServiceImpl.class);
|
||||
|
||||
private Map<String, DataPublisher> dataPublishers;
|
||||
private static DeviceDataPublisher deviceDataPublisher;
|
||||
|
||||
private DeviceDataPublisher() {
|
||||
dataPublishers = new HashMap<>();
|
||||
}
|
||||
|
||||
public static DeviceDataPublisher getInstance() {
|
||||
if (deviceDataPublisher == null) {
|
||||
synchronized (DeviceDataPublisher.class) {
|
||||
if (deviceDataPublisher == null) {
|
||||
deviceDataPublisher = new DeviceDataPublisher();
|
||||
}
|
||||
}
|
||||
}
|
||||
return deviceDataPublisher;
|
||||
}
|
||||
|
||||
/**
|
||||
* This returns the data publisher for the tenant based on the analytics node id.
|
||||
*
|
||||
* @param analyticsConfig Analytics configurations
|
||||
* @param receiverURLSet Data receiver URL set as string
|
||||
* @return instance of data publisher
|
||||
* @throws DataPublisherConfigurationException on exception
|
||||
*/
|
||||
public DataPublisher getDataPublisher(AnalyticsConfiguration analyticsConfig, String receiverURLSet)
|
||||
throws DataPublisherConfigurationException {
|
||||
synchronized (this) {
|
||||
if (this.dataPublishers.containsKey(receiverURLSet)) {
|
||||
return this.dataPublishers.get(receiverURLSet);
|
||||
} else {
|
||||
String analyticsServerUrlGroups = analyticsConfig.getReceiverServerUrl();
|
||||
String analyticsServerUsername = analyticsConfig.getAdminUsername();
|
||||
String analyticsServerPassword = analyticsConfig.getAdminPassword();
|
||||
|
||||
try {
|
||||
DataPublisher dataPublisher = new DataPublisher(receiverURLSet, analyticsServerUsername,
|
||||
analyticsServerPassword);
|
||||
this.dataPublishers.put(receiverURLSet, dataPublisher);
|
||||
return dataPublisher;
|
||||
} catch (DataEndpointAgentConfigurationException e) {
|
||||
String msg = "Configuration Exception on data publisher for " +
|
||||
"ReceiverGroup = " + analyticsServerUrlGroups + " for username " + analyticsServerUsername;
|
||||
log.error(msg, e);
|
||||
throw new DataPublisherConfigurationException(msg, e);
|
||||
} catch (DataEndpointException e) {
|
||||
String msg = "Invalid ReceiverGroup = " + analyticsServerUrlGroups;
|
||||
log.error(msg, e);
|
||||
throw new DataPublisherConfigurationException(msg, e);
|
||||
} catch (DataEndpointConfigurationException e) {
|
||||
String msg = "Invalid Data endpoint configuration.";
|
||||
log.error(msg, e);
|
||||
throw new DataPublisherConfigurationException(msg, e);
|
||||
} catch (DataEndpointAuthenticationException e) {
|
||||
String msg = "Authentication Failed for user " + analyticsServerUsername;
|
||||
log.error(msg, e);
|
||||
throw new DataPublisherConfigurationException(msg, e);
|
||||
} catch (TransportException e) {
|
||||
String msg = "Error occurred while retrieving data publisher";
|
||||
log.error(msg, e);
|
||||
throw new DataPublisherConfigurationException(msg, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,135 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.analytics.data.publisher.config;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.w3c.dom.Document;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.DataPublisherUtil;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
|
||||
import org.wso2.carbon.utils.CarbonUtils;
|
||||
|
||||
import javax.xml.bind.JAXBContext;
|
||||
import javax.xml.bind.JAXBException;
|
||||
import javax.xml.bind.Unmarshaller;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* Configurations related to DAS data publisher and DAL.
|
||||
*/
|
||||
@XmlRootElement(name = "AnalyticsConfiguration")
|
||||
public class AnalyticsConfiguration {
|
||||
|
||||
private String receiverServerUrl;
|
||||
private String analyticsPublisherUrl;
|
||||
private String adminUsername;
|
||||
private String adminPassword;
|
||||
private boolean enable;
|
||||
|
||||
private static AnalyticsConfiguration config;
|
||||
|
||||
private static final Log log = LogFactory.getLog(AnalyticsConfiguration.class);
|
||||
private static final String DEVICE_ANALYTICS_CONFIG_PATH =
|
||||
CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "device-analytics-config.xml";
|
||||
|
||||
private AnalyticsConfiguration() {
|
||||
}
|
||||
|
||||
public static AnalyticsConfiguration getInstance() {
|
||||
if (config == null) {
|
||||
throw new InvalidConfigurationStateException("Device analytics configuration is not " +
|
||||
"initialized properly");
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
|
||||
@XmlElement(name = "AdminUsername", required = true)
|
||||
public String getAdminUsername() {
|
||||
return adminUsername;
|
||||
}
|
||||
|
||||
public void setAdminUsername(String adminUsername) {
|
||||
this.adminUsername = adminUsername;
|
||||
}
|
||||
|
||||
@XmlElement(name = "AdminPassword", required = true)
|
||||
public String getAdminPassword() {
|
||||
return adminPassword;
|
||||
}
|
||||
|
||||
public void setAdminPassword(String adminPassword) {
|
||||
this.adminPassword = adminPassword;
|
||||
}
|
||||
|
||||
@XmlElement(name = "ReceiverServerUrl", required = true)
|
||||
public String getReceiverServerUrl() {
|
||||
return DataPublisherUtil.replaceProperty(receiverServerUrl);
|
||||
}
|
||||
|
||||
public void setReceiverServerUrl(String receiverServerUrl) {
|
||||
this.receiverServerUrl = receiverServerUrl;
|
||||
}
|
||||
|
||||
@XmlElement(name = "AnalyticsPublisherUrl", required = true)
|
||||
public String getAnalyticsPublisherUrl() {
|
||||
return DataPublisherUtil.replaceProperty(analyticsPublisherUrl);
|
||||
}
|
||||
|
||||
public void setAnalyticsPublisherUrl(String analyticsPublisherUrl) {
|
||||
this.analyticsPublisherUrl = analyticsPublisherUrl;
|
||||
}
|
||||
|
||||
@XmlElement(name = "Enabled", required = true)
|
||||
public boolean isEnable() {
|
||||
return enable;
|
||||
}
|
||||
|
||||
public void setEnable(boolean status) {
|
||||
this.enable = status;
|
||||
}
|
||||
|
||||
public static void init() throws DataPublisherConfigurationException {
|
||||
init(AnalyticsConfiguration.DEVICE_ANALYTICS_CONFIG_PATH);
|
||||
}
|
||||
|
||||
public static void init(String analyticsConfigPath) throws DataPublisherConfigurationException {
|
||||
File authConfig = new File(analyticsConfigPath);
|
||||
if (!authConfig.exists()) {
|
||||
log.warn(DEVICE_ANALYTICS_CONFIG_PATH + " does not exist. Disabling AnalyticsConfiguration.");
|
||||
config = new AnalyticsConfiguration();
|
||||
config.setEnable(false);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Document doc = DataPublisherUtil.convertToDocument(authConfig);
|
||||
|
||||
/* Un-marshaling device analytics configuration */
|
||||
JAXBContext ctx = JAXBContext.newInstance(AnalyticsConfiguration.class);
|
||||
Unmarshaller unmarshaller = ctx.createUnmarshaller();
|
||||
config = (AnalyticsConfiguration) unmarshaller.unmarshal(doc);
|
||||
} catch (JAXBException e) {
|
||||
throw new DataPublisherConfigurationException("Error occurred while un-marshalling device analytics " +
|
||||
"Config", e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,29 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.analytics.data.publisher.config;
|
||||
|
||||
public class InvalidConfigurationStateException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = -3151274311329070297L;
|
||||
|
||||
public InvalidConfigurationStateException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
}
|
@ -1,31 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.analytics.data.publisher.exception;
|
||||
|
||||
public class DataPublisherConfigurationException extends Exception {
|
||||
|
||||
public DataPublisherConfigurationException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public DataPublisherConfigurationException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
}
|
@ -1,67 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.analytics.data.publisher.internal;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.osgi.framework.BundleContext;
|
||||
import org.osgi.framework.ServiceRegistration;
|
||||
import org.osgi.service.component.ComponentContext;
|
||||
import org.osgi.service.component.annotations.*;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.config.AnalyticsConfiguration;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherServiceImpl;
|
||||
|
||||
@Component(
|
||||
name = "org.wso2.carbon.device.mgt.analytics.data.publisher.internal.DataPublisherServiceComponent",
|
||||
immediate = true)
|
||||
public class DataPublisherServiceComponent {
|
||||
|
||||
private ServiceRegistration analyticsServiceRef;
|
||||
private static Log log = LogFactory.getLog(DataPublisherServiceComponent.class);
|
||||
|
||||
protected void activate(ComponentContext componentCtx) {
|
||||
try {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Initializing device analytics bundle");
|
||||
}
|
||||
AnalyticsConfiguration.init();
|
||||
BundleContext bundleCtx = componentCtx.getBundleContext();
|
||||
this.analyticsServiceRef =
|
||||
bundleCtx.registerService(EventsPublisherService.class, new EventsPublisherServiceImpl(), null);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Device management analytics bundle has been successfully initialized");
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
log.error("Error occurred while initializing device analytics bundle", e);
|
||||
}
|
||||
}
|
||||
|
||||
protected void deactivate(ComponentContext componentCtx) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Deactivating device analytics bundle");
|
||||
}
|
||||
if (analyticsServiceRef != null) {
|
||||
analyticsServiceRef.unregister();
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Device analytics bundle has been successfully deactivated");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,41 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.analytics.data.publisher.service;
|
||||
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
|
||||
|
||||
/**
|
||||
* This service can be used to publish and retrieve data from the Analytics Server.
|
||||
*/
|
||||
public interface EventsPublisherService {
|
||||
|
||||
/**
|
||||
* This is used to publish an event to DAS.
|
||||
* @param streamName is the name of the stream that the data needs to pushed
|
||||
* @param version is the version of the stream
|
||||
* @param metaDataArray - meta data that needs to pushed
|
||||
* @param correlationDataArray - correlation data that needs to be pushed
|
||||
* @param payloadDataArray - payload data that needs to be pushed
|
||||
* @return if success returns true
|
||||
* @throws DataPublisherConfigurationException on exception
|
||||
*/
|
||||
boolean publishEvent(String streamName, String version, Object[] metaDataArray, Object[] correlationDataArray,
|
||||
Object[] payloadDataArray) throws DataPublisherConfigurationException;
|
||||
|
||||
}
|
@ -1,100 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.analytics.data.publisher.service;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.databridge.agent.DataPublisher;
|
||||
import org.wso2.carbon.databridge.commons.utils.DataBridgeCommonsUtils;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.DataPublisherUtil;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.DeviceDataPublisher;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.config.AnalyticsConfiguration;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
|
||||
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* This is the implementation of Osgi Service which can be used to publish and retireved
|
||||
* event/records.
|
||||
*/
|
||||
public class EventsPublisherServiceImpl implements EventsPublisherService {
|
||||
|
||||
private static Log log = LogFactory.getLog(EventsPublisherServiceImpl.class);
|
||||
|
||||
/**
|
||||
* @param streamName is the name of the stream that the data needs to pushed
|
||||
* @param version is the version of the stream
|
||||
* @param metaDataArray meta data that needs to pushed
|
||||
* @param correlationDataArray correlation data that needs to be pushed
|
||||
* @param payloadDataArray payload data that needs to be pushed
|
||||
* @return if success returns true
|
||||
* @throws DataPublisherConfigurationException on exception
|
||||
*/
|
||||
@Override
|
||||
public boolean publishEvent(String streamName, String version, Object[] metaDataArray,
|
||||
Object[] correlationDataArray,
|
||||
Object[] payloadDataArray) throws DataPublisherConfigurationException {
|
||||
AnalyticsConfiguration analyticsConfig = AnalyticsConfiguration.getInstance();
|
||||
if (!analyticsConfig.isEnable()) {
|
||||
log.warn("Analytics data publishing not enabled.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (metaDataArray == null || metaDataArray.length == 0) {
|
||||
String msg = "meta data[0] must have the device Id field";
|
||||
log.error(msg);
|
||||
throw new DataPublisherConfigurationException(msg);
|
||||
}
|
||||
|
||||
ArrayList<String> receiverURLGroups = DataPublisherUtil.getEndpointGroups(analyticsConfig.getReceiverServerUrl());
|
||||
int hashId = DataPublisherUtil.obtainHashId(metaDataArray[0].toString(), receiverURLGroups.size());
|
||||
if (receiverURLGroups.size() <= hashId) {
|
||||
String msg = "Invalid receiver url group size. Expected to be higher than: " + hashId + " Actual: " +
|
||||
receiverURLGroups.size();
|
||||
log.error(msg);
|
||||
throw new DataPublisherConfigurationException(msg);
|
||||
}
|
||||
|
||||
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
|
||||
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
|
||||
metaDataArray[0] = tenantDomain + "@" + metaDataArray[0];
|
||||
}
|
||||
|
||||
PrivilegedCarbonContext.startTenantFlow();
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext()
|
||||
.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
|
||||
try {
|
||||
DataPublisher dataPublisher = DeviceDataPublisher.getInstance()
|
||||
.getDataPublisher(analyticsConfig, receiverURLGroups.get(hashId));
|
||||
if (dataPublisher != null) {
|
||||
String streamId = DataBridgeCommonsUtils.generateStreamId(streamName, version);
|
||||
return dataPublisher.tryPublish(streamId, System.currentTimeMillis(), metaDataArray,
|
||||
correlationDataArray,
|
||||
payloadDataArray);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} finally {
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,57 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.analytics.data.publisher;
|
||||
|
||||
import org.testng.annotations.BeforeSuite;
|
||||
import org.wso2.carbon.base.MultitenantConstants;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class BaseAnalyticsDataPublisherTest {
|
||||
|
||||
@BeforeSuite
|
||||
public void init() {
|
||||
setUpCarbonHome();
|
||||
}
|
||||
|
||||
private void setUpCarbonHome() {
|
||||
if (System.getProperty("carbon.home") == null) {
|
||||
File file = new File("src/test/resources/carbon-home");
|
||||
if (file.exists()) {
|
||||
System.setProperty("carbon.home", file.getAbsolutePath());
|
||||
}
|
||||
file = new File("carbon-home");
|
||||
if (file.exists()) {
|
||||
System.setProperty("carbon.home", file.getAbsolutePath());
|
||||
}
|
||||
file = new File("../../resources/carbon-home");
|
||||
if (file.exists()) {
|
||||
System.setProperty("carbon.home", file.getAbsolutePath());
|
||||
}
|
||||
file = new File("../../../resources/carbon-home");
|
||||
if (file.exists()) {
|
||||
System.setProperty("carbon.home", file.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants
|
||||
.SUPER_TENANT_DOMAIN_NAME);
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
|
||||
}
|
||||
|
||||
}
|
@ -1,83 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.analytics.data.publisher;
|
||||
|
||||
import junit.framework.Assert;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.config.AnalyticsConfiguration;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.config.InvalidConfigurationStateException;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
|
||||
|
||||
import java.io.File;
|
||||
import java.lang.reflect.Field;
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
* This test class will validate the Data publisher configuration creation.
|
||||
*/
|
||||
public class DataPublisherConfigTest extends BaseAnalyticsDataPublisherTest {
|
||||
|
||||
@Test(description = "Validating the behaviour of getInstance config before calling the init",
|
||||
expectedExceptions = InvalidConfigurationStateException.class)
|
||||
public void testGetInstanceWithoutInit() throws NoSuchFieldException, IllegalAccessException {
|
||||
Field configField = AnalyticsConfiguration.class.getDeclaredField("config");
|
||||
configField.setAccessible(true);
|
||||
configField.set(configField, null);
|
||||
AnalyticsConfiguration.getInstance();
|
||||
}
|
||||
|
||||
@Test(description = "Analytics configuration initialization with invalid config",
|
||||
expectedExceptions = DataPublisherConfigurationException.class,
|
||||
dependsOnMethods = "testGetInstanceWithoutInit")
|
||||
public void testInitWithInvalidConfig() throws DataPublisherConfigurationException {
|
||||
ClassLoader classLoader = this.getClass().getClassLoader();
|
||||
URL invalidConfig = classLoader.getResource("carbon-home/repository/conf/etc/" +
|
||||
"device-analytics-config-invalid.xml");
|
||||
Assert.assertTrue("No configuration - device-analytics-config-invalid.xml found in resource dir",
|
||||
invalidConfig != null);
|
||||
File file = new File(invalidConfig.getFile());
|
||||
AnalyticsConfiguration.init(file.getAbsolutePath());
|
||||
}
|
||||
|
||||
|
||||
@Test(description = "Analytics config initialization with invalid xml",
|
||||
expectedExceptions = DataPublisherConfigurationException.class,
|
||||
dependsOnMethods = "testInitWithInvalidConfig")
|
||||
public void testInitWithInvalidXML() throws DataPublisherConfigurationException {
|
||||
ClassLoader classLoader = this.getClass().getClassLoader();
|
||||
URL invalidConfig = classLoader.getResource("carbon-home/repository/conf/etc/" +
|
||||
"device-analytics-config-invalid-xml.xml");
|
||||
Assert.assertTrue("No configuration - device-analytics-config-invalid-xml.xml found in resource dir",
|
||||
invalidConfig != null);
|
||||
File file = new File(invalidConfig.getFile());
|
||||
AnalyticsConfiguration.init(file.getAbsolutePath());
|
||||
}
|
||||
|
||||
|
||||
@Test(description = "Validating the init method with all required params",
|
||||
dependsOnMethods = "testInitWithInvalidXML")
|
||||
public void testInitWithValidConfig() throws DataPublisherConfigurationException {
|
||||
AnalyticsConfiguration.init();
|
||||
AnalyticsConfiguration analyticsConfiguration = AnalyticsConfiguration.getInstance();
|
||||
Assert.assertEquals(analyticsConfiguration.getAdminPassword(), "testuserpwd");
|
||||
Assert.assertEquals(analyticsConfiguration.getAdminUsername(), "testuser");
|
||||
Assert.assertEquals(analyticsConfiguration.getReceiverServerUrl(), "tcp://localhost:7615");
|
||||
Assert.assertTrue(analyticsConfiguration.isEnable());
|
||||
}
|
||||
|
||||
}
|
@ -1,67 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.analytics.data.publisher;
|
||||
|
||||
|
||||
import org.apache.sling.testing.mock.osgi.MockOsgi;
|
||||
import org.osgi.service.component.ComponentContext;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.internal.DataPublisherServiceComponent;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.util.TestComponentContext;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* This tesclass will be validating the behaviour of {@link DataPublisherServiceComponent}
|
||||
*/
|
||||
public class DataPublisherServiceComponentTest extends BaseAnalyticsDataPublisherTest {
|
||||
private DataPublisherServiceComponent serviceComponent;
|
||||
|
||||
@BeforeClass
|
||||
public void initTest() {
|
||||
this.serviceComponent = new DataPublisherServiceComponent();
|
||||
}
|
||||
|
||||
@Test (description = "Test bundle activation with exception thrown when service resgistration")
|
||||
public void activateWithException() throws NoSuchMethodException, IllegalAccessException,
|
||||
InvocationTargetException {
|
||||
this.activate(new TestComponentContext());
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "activateWithException", description = "Test the bundle activation with succesful path")
|
||||
public void activateWithoutException() throws NoSuchMethodException, InvocationTargetException,
|
||||
IllegalAccessException {
|
||||
this.activate(MockOsgi.newComponentContext());
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = "activateWithoutException", description = "Test bundle deactivation")
|
||||
public void deActivate() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
|
||||
Method method = this.serviceComponent.getClass().getDeclaredMethod("deactivate", ComponentContext.class);
|
||||
method.setAccessible(true);
|
||||
method.invoke(this.serviceComponent, MockOsgi.newComponentContext());
|
||||
}
|
||||
|
||||
private void activate(ComponentContext componentContext) throws NoSuchMethodException, InvocationTargetException,
|
||||
IllegalAccessException {
|
||||
Method method = this.serviceComponent.getClass().getDeclaredMethod("activate", ComponentContext.class);
|
||||
method.setAccessible(true);
|
||||
method.invoke(this.serviceComponent, componentContext);
|
||||
}
|
||||
}
|
@ -1,144 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.analytics.data.publisher;
|
||||
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.databridge.agent.AgentHolder;
|
||||
import org.wso2.carbon.databridge.agent.exception.DataEndpointAgentConfigurationException;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.config.AnalyticsConfiguration;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.config.InvalidConfigurationStateException;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherServiceImpl;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
/**
|
||||
* This test class will test the methods that are exposed from {@link EventsPublisherService}
|
||||
*/
|
||||
public class EventPublisherServiceTest extends BaseAnalyticsDataPublisherTest {
|
||||
|
||||
private static final String STREAM_NAME = "org.wso2.test.stream";
|
||||
private static final String TENANT_DOMAIN = "test.com";
|
||||
|
||||
private EventsPublisherService eventsPublisherService;
|
||||
|
||||
@BeforeClass
|
||||
public void initTest() {
|
||||
this.eventsPublisherService = new EventsPublisherServiceImpl();
|
||||
}
|
||||
|
||||
@Test(description = "Publish the event before initializing",
|
||||
expectedExceptions = InvalidConfigurationStateException.class)
|
||||
public void publishBeforeInit() throws DataPublisherConfigurationException, NoSuchFieldException,
|
||||
IllegalAccessException, InstantiationException {
|
||||
Field configField = AnalyticsConfiguration.class.getDeclaredField("config");
|
||||
configField.setAccessible(true);
|
||||
configField.set(configField, null);
|
||||
this.eventsPublisherService.publishEvent(STREAM_NAME, "1.0.0", getEventProps(), getEventProps(),
|
||||
getEventProps());
|
||||
}
|
||||
|
||||
@Test(description = "Publish with analytics config disabled", dependsOnMethods = "publishBeforeInit")
|
||||
public void publishWhenAnalyticsConfigDisabled() throws DataPublisherConfigurationException {
|
||||
AnalyticsConfiguration.init();
|
||||
AnalyticsConfiguration.getInstance().setEnable(false);
|
||||
boolean published = this.eventsPublisherService.publishEvent(STREAM_NAME, "1.0.0", getEventProps(),
|
||||
getEventProps(), getEventProps());
|
||||
Assert.assertFalse(published);
|
||||
}
|
||||
|
||||
@Test(description = "Publish the event after initializing", dependsOnMethods = "publishWhenAnalyticsConfigDisabled")
|
||||
public void publishAfterInit() throws DataPublisherConfigurationException {
|
||||
AnalyticsConfiguration.getInstance().setEnable(true);
|
||||
boolean published = this.eventsPublisherService.publishEvent(STREAM_NAME, "1.0.0", getEventProps(),
|
||||
getEventProps(), getEventProps());
|
||||
Assert.assertTrue(published);
|
||||
}
|
||||
|
||||
@Test(description = "Publish as tenant", dependsOnMethods = "publishAfterInit")
|
||||
public void publishAsTenant() throws DataPublisherConfigurationException {
|
||||
publishAsTenant(getEventProps());
|
||||
}
|
||||
|
||||
@Test(description = "Publish the with no meta data as tenant", dependsOnMethods = "publishAsTenant",
|
||||
expectedExceptions = DataPublisherConfigurationException.class)
|
||||
public void publishAsTenantWithNoMetaData() throws DataPublisherConfigurationException {
|
||||
publishAsTenant(null);
|
||||
}
|
||||
|
||||
@Test(description = "Publish the with empty meta data as tenant", dependsOnMethods = "publishAsTenant",
|
||||
expectedExceptions = DataPublisherConfigurationException.class)
|
||||
public void publishAsTenantWithEmptyMetaData() throws DataPublisherConfigurationException {
|
||||
publishAsTenant(new Object[0]);
|
||||
}
|
||||
|
||||
@Test(description = "Publishing with invalid data publisher config",
|
||||
dependsOnMethods = {"publishAsTenantWithEmptyMetaData", "publishAsTenantWithNoMetaData"},
|
||||
expectedExceptions = DataPublisherConfigurationException.class)
|
||||
public void publishWithDataEndpointConfigException() throws DataPublisherConfigurationException,
|
||||
NoSuchFieldException, IllegalAccessException {
|
||||
AnalyticsConfiguration analyticsConfiguration = AnalyticsConfiguration.getInstance();
|
||||
analyticsConfiguration.setReceiverServerUrl("");
|
||||
Field dataPublisherField = DeviceDataPublisher.class.getDeclaredField("deviceDataPublisher");
|
||||
dataPublisherField.setAccessible(true);
|
||||
dataPublisherField.set(dataPublisherField, null);
|
||||
publishAsTenant(getEventProps());
|
||||
}
|
||||
|
||||
@Test(description = "Publishing with invalid data publisher config",
|
||||
dependsOnMethods = "publishWithDataEndpointConfigException",
|
||||
expectedExceptions = DataPublisherConfigurationException.class)
|
||||
public void publishWithDataAgentConfigException() throws DataPublisherConfigurationException,
|
||||
NoSuchFieldException, IllegalAccessException, DataEndpointAgentConfigurationException {
|
||||
AnalyticsConfiguration.init();
|
||||
Field defaultAgentName = AgentHolder.getInstance().getClass().getDeclaredField("defaultDataEndpointAgentName");
|
||||
defaultAgentName.setAccessible(true);
|
||||
defaultAgentName.set(AgentHolder.getInstance(), "dummyAgent");
|
||||
publishAsTenant(getEventProps());
|
||||
}
|
||||
|
||||
@Test(description = "Publishing with invalid data publisher config",
|
||||
dependsOnMethods = "publishWithDataAgentConfigException")
|
||||
public void publishWithDataEndpointException() throws DataPublisherConfigurationException,
|
||||
NoSuchFieldException, IllegalAccessException, DataEndpointAgentConfigurationException {
|
||||
AnalyticsConfiguration.init();
|
||||
|
||||
}
|
||||
|
||||
private void publishAsTenant(Object[] metaData) throws DataPublisherConfigurationException {
|
||||
PrivilegedCarbonContext.startTenantFlow();
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(TENANT_DOMAIN, true);
|
||||
try {
|
||||
boolean published = this.eventsPublisherService.publishEvent(STREAM_NAME, "1.0.0", metaData,
|
||||
getEventProps(), getEventProps());
|
||||
Assert.assertTrue(published);
|
||||
} finally {
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
}
|
||||
|
||||
private Object[] getEventProps() {
|
||||
return new Object[]{"123"};
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -1,81 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.analytics.data.publisher.util;
|
||||
|
||||
import org.osgi.framework.Bundle;
|
||||
import org.osgi.framework.BundleContext;
|
||||
import org.osgi.framework.ServiceReference;
|
||||
import org.osgi.service.component.ComponentContext;
|
||||
import org.osgi.service.component.ComponentInstance;
|
||||
|
||||
import java.util.Dictionary;
|
||||
|
||||
/**
|
||||
* Mock implementation for component context.
|
||||
*/
|
||||
public class TestComponentContext implements ComponentContext {
|
||||
@Override
|
||||
public Dictionary getProperties() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object locateService(String s) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object locateService(String s, ServiceReference serviceReference) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] locateServices(String s) {
|
||||
return new Object[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public BundleContext getBundleContext() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Bundle getUsingBundle() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ComponentInstance getComponentInstance() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enableComponent(String s) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disableComponent(String s) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServiceReference getServiceReference() {
|
||||
return null;
|
||||
}
|
||||
}
|
@ -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,69 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<!--
|
||||
~ 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.
|
||||
-->
|
||||
|
||||
<DataAgentsConfiguration>
|
||||
<Agent>
|
||||
<Name>Thrift</Name>
|
||||
<DataEndpointClass>org.wso2.carbon.databridge.agent.endpoint.thrift.ThriftDataEndpointNoClass</DataEndpointClass>
|
||||
<TrustSore>src/test/resources/client-truststore.jks</TrustSore>
|
||||
<TrustSorePassword>wso2carbon</TrustSorePassword>
|
||||
<QueueSize>32768</QueueSize>
|
||||
<BatchSize>200</BatchSize>
|
||||
<CorePoolSize>1</CorePoolSize>
|
||||
<SocketTimeoutMS>30000</SocketTimeoutMS>
|
||||
<MaxPoolSize>1</MaxPoolSize>
|
||||
<KeepAliveTimeInPool>20</KeepAliveTimeInPool>
|
||||
<ReconnectionInterval>30</ReconnectionInterval>
|
||||
<MaxTransportPoolSize>250</MaxTransportPoolSize>
|
||||
<MaxIdleConnections>250</MaxIdleConnections>
|
||||
<EvictionTimePeriod>5500</EvictionTimePeriod>
|
||||
<MinIdleTimeInPool>5000</MinIdleTimeInPool>
|
||||
<SecureMaxTransportPoolSize>250</SecureMaxTransportPoolSize>
|
||||
<SecureMaxIdleConnections>250</SecureMaxIdleConnections>
|
||||
<SecureEvictionTimePeriod>5500</SecureEvictionTimePeriod>
|
||||
<SecureMinIdleTimeInPool>5000</SecureMinIdleTimeInPool>
|
||||
<!--<sslEnabledProtocols>TLSv1,TLSv1.1,TLSv1.2</sslEnabledProtocols>-->
|
||||
<!--<ciphers>SSL_RSA_WITH_RC4_128_MD5,SSL_RSA_WITH_RC4_128_SHA,TLS_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_DSS_WITH_AES_128_CBC_SHA,SSL_RSA_WITH_3DES_EDE_CBC_SHA,SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA</ciphers>-->
|
||||
</Agent>
|
||||
|
||||
<Agent>
|
||||
<Name>Binary</Name>
|
||||
<DataEndpointClass>org.wso2.carbon.databridge.agent.endpoint.binary.BinaryDataEndpoint</DataEndpointClass>
|
||||
<TrustSore>src/test/resources/client-truststore.jks</TrustSore>
|
||||
<TrustSorePassword>wso2carbon</TrustSorePassword>
|
||||
<QueueSize>32768</QueueSize>
|
||||
<BatchSize>200</BatchSize>
|
||||
<CorePoolSize>1</CorePoolSize>
|
||||
<MaxPoolSize>1</MaxPoolSize>
|
||||
<SocketTimeoutMS>30000</SocketTimeoutMS>
|
||||
<KeepAliveTimeInPool>20</KeepAliveTimeInPool>
|
||||
<ReconnectionInterval>30</ReconnectionInterval>
|
||||
<MaxTransportPoolSize>250</MaxTransportPoolSize>
|
||||
<MaxIdleConnections>250</MaxIdleConnections>
|
||||
<EvictionTimePeriod>5500</EvictionTimePeriod>
|
||||
<MinIdleTimeInPool>5000</MinIdleTimeInPool>
|
||||
<SecureMaxTransportPoolSize>250</SecureMaxTransportPoolSize>
|
||||
<SecureMaxIdleConnections>250</SecureMaxIdleConnections>
|
||||
<SecureEvictionTimePeriod>5500</SecureEvictionTimePeriod>
|
||||
<SecureMinIdleTimeInPool>5000</SecureMinIdleTimeInPool>
|
||||
<!--<sslEnabledProtocols>TLSv1,TLSv1.1,TLSv1.2</sslEnabledProtocols>-->
|
||||
<!--<ciphers>SSL_RSA_WITH_RC4_128_MD5,SSL_RSA_WITH_RC4_128_SHA,TLS_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_DSS_WITH_AES_128_CBC_SHA,SSL_RSA_WITH_3DES_EDE_CBC_SHA,SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA</ciphers>-->
|
||||
</Agent>
|
||||
</DataAgentsConfiguration>
|
||||
|
@ -1,69 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<!--
|
||||
~ 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.
|
||||
-->
|
||||
|
||||
<DataAgentsConfiguration>
|
||||
<Agent>
|
||||
<Name>Thrift</Name>
|
||||
<DataEndpointClass>org.wso2.carbon.databridge.agent.endpoint.thrift.ThriftDataEndpoint</DataEndpointClass>
|
||||
<TrustSore>src/test/resources/client-truststore.jks</TrustSore>
|
||||
<TrustSorePassword>wso2carbon</TrustSorePassword>
|
||||
<QueueSize>32768</QueueSize>
|
||||
<BatchSize>200</BatchSize>
|
||||
<CorePoolSize>1</CorePoolSize>
|
||||
<SocketTimeoutMS>30000</SocketTimeoutMS>
|
||||
<MaxPoolSize>1</MaxPoolSize>
|
||||
<KeepAliveTimeInPool>20</KeepAliveTimeInPool>
|
||||
<ReconnectionInterval>30</ReconnectionInterval>
|
||||
<MaxTransportPoolSize>250</MaxTransportPoolSize>
|
||||
<MaxIdleConnections>250</MaxIdleConnections>
|
||||
<EvictionTimePeriod>5500</EvictionTimePeriod>
|
||||
<MinIdleTimeInPool>5000</MinIdleTimeInPool>
|
||||
<SecureMaxTransportPoolSize>250</SecureMaxTransportPoolSize>
|
||||
<SecureMaxIdleConnections>250</SecureMaxIdleConnections>
|
||||
<SecureEvictionTimePeriod>5500</SecureEvictionTimePeriod>
|
||||
<SecureMinIdleTimeInPool>5000</SecureMinIdleTimeInPool>
|
||||
<!--<sslEnabledProtocols>TLSv1,TLSv1.1,TLSv1.2</sslEnabledProtocols>-->
|
||||
<!--<ciphers>SSL_RSA_WITH_RC4_128_MD5,SSL_RSA_WITH_RC4_128_SHA,TLS_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_DSS_WITH_AES_128_CBC_SHA,SSL_RSA_WITH_3DES_EDE_CBC_SHA,SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA</ciphers>-->
|
||||
</Agent>
|
||||
|
||||
<Agent>
|
||||
<Name>Binary</Name>
|
||||
<DataEndpointClass>org.wso2.carbon.databridge.agent.endpoint.binary.BinaryDataEndpoint</DataEndpointClass>
|
||||
<TrustSore>src/test/resources/client-truststore.jks</TrustSore>
|
||||
<TrustSorePassword>wso2carbon</TrustSorePassword>
|
||||
<QueueSize>32768</QueueSize>
|
||||
<BatchSize>200</BatchSize>
|
||||
<CorePoolSize>1</CorePoolSize>
|
||||
<MaxPoolSize>1</MaxPoolSize>
|
||||
<SocketTimeoutMS>30000</SocketTimeoutMS>
|
||||
<KeepAliveTimeInPool>20</KeepAliveTimeInPool>
|
||||
<ReconnectionInterval>30</ReconnectionInterval>
|
||||
<MaxTransportPoolSize>250</MaxTransportPoolSize>
|
||||
<MaxIdleConnections>250</MaxIdleConnections>
|
||||
<EvictionTimePeriod>5500</EvictionTimePeriod>
|
||||
<MinIdleTimeInPool>5000</MinIdleTimeInPool>
|
||||
<SecureMaxTransportPoolSize>250</SecureMaxTransportPoolSize>
|
||||
<SecureMaxIdleConnections>250</SecureMaxIdleConnections>
|
||||
<SecureEvictionTimePeriod>5500</SecureEvictionTimePeriod>
|
||||
<SecureMinIdleTimeInPool>5000</SecureMinIdleTimeInPool>
|
||||
<!--<sslEnabledProtocols>TLSv1,TLSv1.1,TLSv1.2</sslEnabledProtocols>-->
|
||||
<!--<ciphers>SSL_RSA_WITH_RC4_128_MD5,SSL_RSA_WITH_RC4_128_SHA,TLS_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_DSS_WITH_AES_128_CBC_SHA,SSL_RSA_WITH_3DES_EDE_CBC_SHA,SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA</ciphers>-->
|
||||
</Agent>
|
||||
</DataAgentsConfiguration>
|
||||
|
@ -1,35 +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.
|
||||
-->
|
||||
|
||||
<AnalyticsConfig>
|
||||
<!--
|
||||
Server URL of the remote DAS/BAM/CEP server used to collect statistics. Must
|
||||
be specified in protocol://hostname:port/ format.
|
||||
|
||||
An event can also be published to multiple Receiver Groups each having 1 or more receivers. Receiver
|
||||
Groups are delimited by curly braces whereas receivers are delimited by commas.
|
||||
Ex - Multiple Receivers within a single group
|
||||
tcp://localhost:7612/,tcp://localhost:7613/,tcp://localhost:7614/
|
||||
Ex - Multiple Receiver Groups with two receivers each
|
||||
{tcp://localhost:7612/,tcp://localhost:7613},{tcp://localhost:7712/,tcp://localhost:7713/}
|
||||
-->
|
||||
<ReceiverServerUrl>tcp://localhost:7615</ReceiverServerUrl>
|
||||
<AdminUsername>testuser</AdminUsername>
|
||||
<AdminPassword>testuserpwd</AdminPassword
|
||||
</AnalyticsConfig>
|
@ -1,35 +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.
|
||||
-->
|
||||
|
||||
<AnalyticsConfig>
|
||||
<!--
|
||||
Server URL of the remote DAS/BAM/CEP server used to collect statistics. Must
|
||||
be specified in protocol://hostname:port/ format.
|
||||
|
||||
An event can also be published to multiple Receiver Groups each having 1 or more receivers. Receiver
|
||||
Groups are delimited by curly braces whereas receivers are delimited by commas.
|
||||
Ex - Multiple Receivers within a single group
|
||||
tcp://localhost:7612/,tcp://localhost:7613/,tcp://localhost:7614/
|
||||
Ex - Multiple Receiver Groups with two receivers each
|
||||
{tcp://localhost:7612/,tcp://localhost:7613},{tcp://localhost:7712/,tcp://localhost:7713/}
|
||||
-->
|
||||
<ReceiverServerUrl>tcp://localhost:7615</ReceiverServerUrl>
|
||||
<AdminUsername>testuser</AdminUsername>
|
||||
<AdminPassword>testuserpwd</AdminPassword>
|
||||
</AnalyticsConfig>
|
@ -1,36 +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.
|
||||
-->
|
||||
|
||||
<AnalyticsConfiguration>
|
||||
<!--
|
||||
Server URL of the remote DAS/BAM/CEP server used to collect statistics. Must
|
||||
be specified in protocol://hostname:port/ format.
|
||||
|
||||
An event can also be published to multiple Receiver Groups each having 1 or more receivers. Receiver
|
||||
Groups are delimited by curly braces whereas receivers are delimited by commas.
|
||||
Ex - Multiple Receivers within a single group
|
||||
tcp://localhost:7612/,tcp://localhost:7613/,tcp://localhost:7614/
|
||||
Ex - Multiple Receiver Groups with two receivers each
|
||||
{tcp://localhost:7612/,tcp://localhost:7613},{tcp://localhost:7712/,tcp://localhost:7713/}
|
||||
-->
|
||||
<Enabled>true</Enabled>
|
||||
<ReceiverServerUrl>tcp://localhost:7615</ReceiverServerUrl>
|
||||
<AdminUsername>testuser</AdminUsername>
|
||||
<AdminPassword>testuserpwd</AdminPassword>
|
||||
</AnalyticsConfiguration>
|
@ -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>
|
Binary file not shown.
@ -1,31 +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="Device Mgmt Analytics Data Publisher" preserve-order="true">
|
||||
<classes>
|
||||
<class name="org.wso2.carbon.device.mgt.analytics.data.publisher.DataPublisherConfigTest"/>
|
||||
<class name="org.wso2.carbon.device.mgt.analytics.data.publisher.EventPublisherServiceTest"/>
|
||||
<class name="org.wso2.carbon.device.mgt.analytics.data.publisher.DataPublisherServiceComponentTest"/>
|
||||
</classes>
|
||||
</test>
|
||||
</suite>
|
@ -1,80 +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>device-mgt</artifactId>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<version>5.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>org.wso2.carbon.device.mgt.analytics.wsproxy</artifactId>
|
||||
<packaging>war</packaging>
|
||||
<name>WSO2 - Webapp for Web Socket Proxy</name>
|
||||
<url>https://entgra.io</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
<artifactId>javax.ws.rs-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>secured-websocket-proxy</finalName>
|
||||
<plugins>
|
||||
<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,37 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.analytics.wsproxy.exception;
|
||||
|
||||
/**
|
||||
* Indicates an error with deployment tinkerer
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public class WSProxyException extends Exception {
|
||||
|
||||
/**
|
||||
* Constructs a new exception with the message provided and the cause.
|
||||
*
|
||||
* @param message the detailed message of the exception
|
||||
* @param cause the cause of the exception
|
||||
*/
|
||||
public WSProxyException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
@ -1,145 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.analytics.wsproxy.inbound;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.databridge.agent.exception.DataEndpointConfigurationException;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.DataPublisherUtil;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.config.AnalyticsConfiguration;
|
||||
import org.wso2.carbon.device.mgt.analytics.wsproxy.exception.WSProxyException;
|
||||
import org.wso2.carbon.device.mgt.analytics.wsproxy.outbound.AnalyticsClient;
|
||||
|
||||
import javax.websocket.CloseReason;
|
||||
import javax.websocket.Session;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Interface for subscription and un-subscription for web socket
|
||||
*/
|
||||
|
||||
public class SubscriptionEndpoint {
|
||||
|
||||
private static final Log log = LogFactory.getLog(SubscriptionEndpoint.class);
|
||||
private Map<String, List<AnalyticsClient>> analyticsClientsMap = new HashMap<>();
|
||||
|
||||
/**
|
||||
* Web socket onOpen - When client sends a message
|
||||
*
|
||||
* @param session - Users registered session.
|
||||
*/
|
||||
void onOpen(Session session) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("WebSocket opened, for Session id: " + session.getId());
|
||||
}
|
||||
|
||||
AnalyticsConfiguration analyticsConfig = AnalyticsConfiguration.getInstance();
|
||||
ArrayList<String> publisherGroups =
|
||||
DataPublisherUtil.getEndpointGroups(analyticsConfig.getAnalyticsPublisherUrl());
|
||||
List<AnalyticsClient> analyticsClients = new ArrayList<>();
|
||||
for (String publisherURLGroup : publisherGroups) {
|
||||
try {
|
||||
String[] endpoints = DataPublisherUtil.getEndpoints(publisherURLGroup);
|
||||
for (String endpoint : endpoints) {
|
||||
try {
|
||||
endpoint = endpoint.trim();
|
||||
if (!endpoint.endsWith("/")) {
|
||||
endpoint += "/";
|
||||
}
|
||||
endpoint += session.getRequestURI().getSchemeSpecificPart().replace("secured-websocket-proxy","");
|
||||
AnalyticsClient analyticsClient = new AnalyticsClient(session, new URI(endpoint));
|
||||
analyticsClients.add(analyticsClient);
|
||||
} catch (URISyntaxException e) {
|
||||
log.error("Unable to create URL from: " + endpoint, e);
|
||||
} catch (WSProxyException e) {
|
||||
log.error("Unable to create WS client for: " + endpoint, e);
|
||||
}
|
||||
}
|
||||
} catch (DataEndpointConfigurationException e) {
|
||||
log.error("Unable to obtain endpoints from receiverURLGroup: " + publisherURLGroup, e);
|
||||
}
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Configured " + analyticsClients.size() + " analytics clients for Session id: " +
|
||||
session.getId());
|
||||
}
|
||||
analyticsClientsMap.put(session.getId(), analyticsClients);
|
||||
}
|
||||
|
||||
/**
|
||||
* Web socket onClose - Remove the registered sessions
|
||||
*
|
||||
* @param session - Users registered session.
|
||||
* @param reason - Status code for web-socket close.
|
||||
* @param streamName - StreamName extracted from the ws url.
|
||||
* @param version - Version extracted from the ws url.
|
||||
* @param tenantDomain - Domain of the tenant.
|
||||
*/
|
||||
public void onClose(Session session, CloseReason reason, String streamName, String version, String tenantDomain) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Closing a WebSocket due to " + reason.getReasonPhrase() + ", for session ID:" +
|
||||
session.getId() + ", for request URI - " + session.getRequestURI());
|
||||
}
|
||||
for (AnalyticsClient analyticsClient : analyticsClientsMap.get(session.getId())) {
|
||||
if (analyticsClient != null) {
|
||||
try {
|
||||
analyticsClient.closeConnection(reason);
|
||||
} catch (WSProxyException e) {
|
||||
log.error("Error occurred while closing ws connection due to " + reason.getReasonPhrase() +
|
||||
", for session ID:" + session.getId() + ", for request URI - " + session.getRequestURI(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
analyticsClientsMap.remove(session.getId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Web socket onMessage - When client sens a message
|
||||
*
|
||||
* @param session - Users registered session.
|
||||
* @param message - Status code for web-socket close.
|
||||
*/
|
||||
void onMessage(Session session, String message) {
|
||||
for (AnalyticsClient analyticsClient : analyticsClientsMap.get(session.getId())) {
|
||||
if (analyticsClient != null) {
|
||||
analyticsClient.sendMessage(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Web socket onError
|
||||
*
|
||||
* @param session - Users registered session.
|
||||
* @param throwable - Status code for web-socket close.
|
||||
* @param streamName - StreamName extracted from the ws url.
|
||||
* @param version - Version extracted from the ws url.
|
||||
* @param tenantDomain - Domain of the tenant.
|
||||
*/
|
||||
public void onError(Session session, Throwable throwable, String streamName, String version, String tenantDomain) {
|
||||
log.error("Error occurred in session ID: " + session.getId() + ", for request URI - " +
|
||||
session.getRequestURI() + ", " + throwable.getMessage(), throwable);
|
||||
}
|
||||
|
||||
}
|
@ -1,104 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.analytics.wsproxy.inbound;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.base.MultitenantConstants;
|
||||
|
||||
import javax.websocket.CloseReason;
|
||||
import javax.websocket.EndpointConfig;
|
||||
import javax.websocket.OnClose;
|
||||
import javax.websocket.OnError;
|
||||
import javax.websocket.OnMessage;
|
||||
import javax.websocket.OnOpen;
|
||||
import javax.websocket.Session;
|
||||
import javax.websocket.server.PathParam;
|
||||
import javax.websocket.server.ServerEndpoint;
|
||||
|
||||
/**
|
||||
* Connect to web socket with Super tenant
|
||||
*/
|
||||
|
||||
@ServerEndpoint(value = "/{destination}/{streamname}/{version}")
|
||||
public class SuperTenantSubscriptionEndpoint extends SubscriptionEndpoint {
|
||||
|
||||
private static final Log log = LogFactory.getLog(SuperTenantSubscriptionEndpoint.class);
|
||||
|
||||
/**
|
||||
* Web socket onOpen - When client sends a message
|
||||
*
|
||||
* @param session - Users registered session.
|
||||
* @param streamName - StreamName extracted from the ws url.
|
||||
* @param version - Version extracted from the ws url.
|
||||
*/
|
||||
@OnOpen
|
||||
public void onOpen(Session session, EndpointConfig config, @PathParam("streamname") String streamName,
|
||||
@PathParam("version") String version) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("WebSocket opened, for Session id: " + session.getId() + ", for the Stream:" + streamName);
|
||||
}
|
||||
super.onOpen(session);
|
||||
}
|
||||
|
||||
/**
|
||||
* Web socket onMessage - When client sens a message
|
||||
*
|
||||
* @param session - Users registered session.
|
||||
* @param message - Status code for web-socket close.
|
||||
* @param streamName - StreamName extracted from the ws url.
|
||||
*/
|
||||
@OnMessage
|
||||
public void onMessage(Session session, String message, @PathParam("streamname") String streamName) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Received message from client. Message: " + message + ", " +
|
||||
"for Session id: " + session.getId() + ", for the Stream:" + streamName);
|
||||
}
|
||||
super.onMessage(session, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Web socket onClose - Remove the registered sessions
|
||||
*
|
||||
* @param session - Users registered session.
|
||||
* @param reason - Status code for web-socket close.
|
||||
* @param streamName - StreamName extracted from the ws url.
|
||||
* @param version - Version extracted from the ws url.
|
||||
*/
|
||||
@OnClose
|
||||
public void onClose(Session session, CloseReason reason, @PathParam("streamname") String streamName,
|
||||
@PathParam("version") String version) {
|
||||
super.onClose(session, reason, streamName, version, MultitenantConstants.SUPER_TENANT_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Web socket onError - Remove the registered sessions
|
||||
*
|
||||
* @param session - Users registered session.
|
||||
* @param throwable - Status code for web-socket close.
|
||||
* @param streamName - StreamName extracted from the ws url.
|
||||
* @param version - Version extracted from the ws url.
|
||||
*/
|
||||
@OnError
|
||||
public void onError(Session session, Throwable throwable, @PathParam("streamname") String streamName,
|
||||
@PathParam("version") String version) {
|
||||
super.onError(session, throwable, streamName, version, MultitenantConstants.SUPER_TENANT_NAME);
|
||||
}
|
||||
|
||||
}
|
@ -1,103 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.analytics.wsproxy.inbound;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import javax.websocket.CloseReason;
|
||||
import javax.websocket.EndpointConfig;
|
||||
import javax.websocket.OnClose;
|
||||
import javax.websocket.OnError;
|
||||
import javax.websocket.OnMessage;
|
||||
import javax.websocket.OnOpen;
|
||||
import javax.websocket.Session;
|
||||
import javax.websocket.server.PathParam;
|
||||
import javax.websocket.server.ServerEndpoint;
|
||||
|
||||
/**
|
||||
* Connect to web socket with a tenant
|
||||
*/
|
||||
|
||||
@ServerEndpoint(value = "/{destination}/t/{tdomain}/{streamname}/{version}")
|
||||
public class TenantSubscriptionEndpoint extends SubscriptionEndpoint {
|
||||
|
||||
private static final Log log = LogFactory.getLog(TenantSubscriptionEndpoint.class);
|
||||
|
||||
/**
|
||||
* Web socket onOpen - When client sends a message
|
||||
*
|
||||
* @param session - Users registered session.
|
||||
* @param streamName - StreamName extracted from the ws url.
|
||||
* @param version - Version extracted from the ws url.
|
||||
* @param tdomain - Tenant domain extracted from ws url.
|
||||
*/
|
||||
@OnOpen
|
||||
public void onOpen(Session session, EndpointConfig config, @PathParam("streamname") String streamName,
|
||||
@PathParam("version") String version, @PathParam("tdomain") String tdomain) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("WebSocket opened, for Session id: " + session.getId() + ", for the Stream:" + streamName);
|
||||
}
|
||||
super.onOpen(session);
|
||||
}
|
||||
|
||||
/**
|
||||
* Web socket onMessage - When client sens a message
|
||||
*
|
||||
* @param session - Users registered session.
|
||||
* @param message - Status code for web-socket close.
|
||||
* @param streamName - StreamName extracted from the ws url.
|
||||
*/
|
||||
@OnMessage
|
||||
public void onMessage(Session session, String message, @PathParam("streamname") String streamName, @PathParam("tdomain") String tdomain) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Received message from client. Message: " + message + ", for Session id: " +
|
||||
session.getId() + ", for tenant domain" + tdomain + ", for the Adaptor:" + streamName);
|
||||
}
|
||||
super.onMessage(session, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Web socket onClose - Remove the registered sessions
|
||||
*
|
||||
* @param session - Users registered session.
|
||||
* @param reason - Status code for web-socket close.
|
||||
* @param streamName - StreamName extracted from the ws url.
|
||||
* @param version - Version extracted from the ws url.
|
||||
*/
|
||||
@OnClose
|
||||
public void onClose(Session session, CloseReason reason, @PathParam("streamname") String streamName,
|
||||
@PathParam("version") String version, @PathParam("tdomain") String tdomain) {
|
||||
super.onClose(session, reason, streamName, version, tdomain);
|
||||
}
|
||||
|
||||
/**
|
||||
* Web socket onError - Remove the registered sessions
|
||||
*
|
||||
* @param session - Users registered session.
|
||||
* @param throwable - Status code for web-socket close.
|
||||
* @param streamName - StreamName extracted from the ws url.
|
||||
* @param version - Version extracted from the ws url.
|
||||
*/
|
||||
@OnError
|
||||
public void onError(Session session, Throwable throwable, @PathParam("streamname") String streamName,
|
||||
@PathParam("version") String version, @PathParam("tdomain") String tdomain) {
|
||||
super.onError(session, throwable, streamName, version, tdomain);
|
||||
}
|
||||
}
|
@ -1,133 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.analytics.wsproxy.outbound;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.device.mgt.analytics.wsproxy.exception.WSProxyException;
|
||||
|
||||
import javax.websocket.CloseReason;
|
||||
import javax.websocket.ContainerProvider;
|
||||
import javax.websocket.DeploymentException;
|
||||
import javax.websocket.OnClose;
|
||||
import javax.websocket.OnMessage;
|
||||
import javax.websocket.Session;
|
||||
import javax.websocket.WebSocketContainer;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
|
||||
/**
|
||||
* This class holds web socket client implementation
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
@javax.websocket.ClientEndpoint
|
||||
public class AnalyticsClient {
|
||||
|
||||
private static final Log log = LogFactory.getLog(AnalyticsClient.class);
|
||||
|
||||
private final Session analyticsSession;
|
||||
private final Session clientSession;
|
||||
|
||||
/**
|
||||
* Create {@link AnalyticsClient} instance.
|
||||
*/
|
||||
public AnalyticsClient(Session clientSession, URI endpointURI) throws WSProxyException {
|
||||
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
|
||||
this.clientSession = clientSession;
|
||||
|
||||
try {
|
||||
this.analyticsSession = container.connectToServer(this, endpointURI);
|
||||
} catch (DeploymentException | IOException e) {
|
||||
String msg = "Error occurred while connecting to remote endpoint " + endpointURI.toString();
|
||||
log.error(msg, e);
|
||||
throw new WSProxyException(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback hook for Connection close events.
|
||||
*
|
||||
* @param userSession the analyticsSession which is getting closed.
|
||||
* @param reason the reason for connection close
|
||||
*/
|
||||
@OnClose
|
||||
public void onClose(Session userSession, CloseReason reason) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Closing web socket session: '" + userSession.getId() + "'. Code: " +
|
||||
reason.getCloseCode().toString() + " Reason: " + reason.getReasonPhrase());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback hook for Message Events.
|
||||
*
|
||||
* <p>This method will be invoked when a client send a message.
|
||||
*
|
||||
* @param message The text message.
|
||||
*/
|
||||
@OnMessage
|
||||
public void onMessage(String message) {
|
||||
synchronized (this.clientSession) {
|
||||
try {
|
||||
this.clientSession.getBasicRemote().sendText(message);
|
||||
} catch (IOException e) {
|
||||
log.warn("Sending message to client failed due to " + e.getMessage());
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Full stack trace:", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message.
|
||||
*
|
||||
* @param message the message which is going to send.
|
||||
*/
|
||||
public void sendMessage(String message) {
|
||||
synchronized (this.analyticsSession) {
|
||||
try {
|
||||
this.analyticsSession.getBasicRemote().sendText(message);
|
||||
} catch (IOException e) {
|
||||
log.warn("Sending message to analytics failed due to " + e.getMessage());
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Full stack trace:", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close current connection.
|
||||
*/
|
||||
public void closeConnection(CloseReason closeReason) throws WSProxyException {
|
||||
if (this.analyticsSession.isOpen()) {
|
||||
try {
|
||||
this.analyticsSession.close(closeReason);
|
||||
} catch (IOException e) {
|
||||
String msg = "Error on closing WS connection.";
|
||||
log.error(msg, e);
|
||||
throw new WSProxyException(msg, e);
|
||||
}
|
||||
} else {
|
||||
log.warn("Analytics session '" + this.analyticsSession.getId() + "' is already closed");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,46 +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 web-app PUBLIC
|
||||
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
|
||||
"http://java.sun.com/dtd/web-app_2_3.dtd" >
|
||||
|
||||
<web-app>
|
||||
<display-name>Output WebSocket Proxy</display-name>
|
||||
|
||||
<filter>
|
||||
<filter-name>ContentTypeBasedCachePreventionFilter</filter-name>
|
||||
<filter-class>org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter</filter-class>
|
||||
<init-param>
|
||||
<param-name>patterns</param-name>
|
||||
<param-value>text/html" ,application/json" ,text/plain</param-value>
|
||||
</init-param>
|
||||
<init-param>
|
||||
<param-name>filterAction</param-name>
|
||||
<param-value>enforce</param-value>
|
||||
</init-param>
|
||||
<init-param>
|
||||
<param-name>httpHeaders</param-name>
|
||||
<param-value>Cache-Control: no-store, no-cache, must-revalidate, private</param-value>
|
||||
</init-param>
|
||||
</filter>
|
||||
|
||||
<filter-mapping>
|
||||
<filter-name>ContentTypeBasedCachePreventionFilter</filter-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
</filter-mapping>
|
||||
</web-app>
|
@ -1,154 +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>identity-extensions</artifactId>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<version>5.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - OAuth Back End Authenticator</name>
|
||||
<artifactId>org.wso2.carbon.identity.authenticator.backend.oauth</artifactId>
|
||||
|
||||
<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.utils</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.identity.framework</groupId>
|
||||
<artifactId>org.wso2.carbon.identity.base</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.identity.framework</groupId>
|
||||
<artifactId>org.wso2.carbon.identity.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.ops4j.pax.logging</groupId>
|
||||
<artifactId>pax-logging-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
<!-- <version>${pax.logging.api.version}</version>-->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.identity.framework</groupId>
|
||||
<artifactId>org.wso2.carbon.identity.application.authentication.framework</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.core.services</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.identity.inbound.auth.oauth2</groupId>
|
||||
<artifactId>org.wso2.carbon.identity.oauth</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.identity.framework</groupId>
|
||||
<artifactId>org.wso2.carbon.identity.application.common</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.identity.inbound.auth.oauth2</groupId>
|
||||
<artifactId>org.wso2.carbon.identity.oauth.stub</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec.wso2</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
<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>OAuth Authenticator Bundle</Bundle-Description>
|
||||
<Private-Package>
|
||||
org.wso2.carbon.identity.authenticator.backend.oauth.internal
|
||||
</Private-Package>
|
||||
<Export-Package>
|
||||
!org.wso2.carbon.identity.authenticator.backend.oauth.internal,
|
||||
org.wso2.carbon.identity.authenticator.backend.oauth.*
|
||||
</Export-Package>
|
||||
<Import-Package>
|
||||
org.wso2.carbon.identity.oauth2.*,
|
||||
javax.servlet.http,
|
||||
org.apache.axis2.client,
|
||||
org.apache.axis2.context,
|
||||
org.apache.axis2.transport.http,
|
||||
org.apache.commons.httpclient,
|
||||
org.apache.commons.logging,
|
||||
org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}",
|
||||
org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
|
||||
org.osgi.service.*;version="${imp.package.version.osgi.service}",
|
||||
org.wso2.carbon.core.security,
|
||||
org.wso2.carbon.core.services.authentication,
|
||||
org.wso2.carbon.utils.multitenancy,
|
||||
org.wso2.carbon.base,
|
||||
org.wso2.carbon.utils
|
||||
</Import-Package>
|
||||
</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>
|
||||
|
||||
</project>
|
@ -1,39 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.wso2.carbon.identity.authenticator.backend.oauth;
|
||||
|
||||
/**
|
||||
* Custom exception for backend OAuth authentication
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public class AuthenticatorException extends Exception {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public AuthenticatorException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public AuthenticatorException(Throwable e) {
|
||||
super(e);
|
||||
}
|
||||
|
||||
public AuthenticatorException(String message, Throwable e) {
|
||||
super(message, e);
|
||||
}
|
||||
}
|
@ -1,155 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.wso2.carbon.identity.authenticator.backend.oauth;
|
||||
|
||||
import org.apache.axis2.context.MessageContext;
|
||||
import org.apache.axis2.transport.http.HTTPConstants;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.base.MultitenantConstants;
|
||||
import org.wso2.carbon.core.security.AuthenticatorsConfiguration;
|
||||
import org.wso2.carbon.core.services.authentication.CarbonServerAuthenticator;
|
||||
import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationResponse;
|
||||
import org.wso2.carbon.utils.ServerConstants;
|
||||
import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator;
|
||||
import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidatorFactory;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import java.rmi.RemoteException;
|
||||
|
||||
/**
|
||||
* This is a custom back end authenticator for enable OAuth token authentication for admin services
|
||||
*/
|
||||
public class OauthAuthenticator implements CarbonServerAuthenticator {
|
||||
|
||||
private static final Log log = LogFactory.getLog(OauthAuthenticator.class);
|
||||
private static final int PRIORITY = 5;
|
||||
private static final int ACCESS_TOKEN_INDEX = 1;
|
||||
private OAuth2TokenValidator tokenValidator;
|
||||
|
||||
public OauthAuthenticator() {
|
||||
try {
|
||||
tokenValidator = OAuthValidatorFactory.getValidator();
|
||||
} catch (IllegalArgumentException e) {
|
||||
log.error("Failed to initialise Authenticator", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the authentication of the context can be handled using this authenticator.
|
||||
*
|
||||
* @param messageContext containing the request need to be authenticated.
|
||||
* @return boolean indicating whether the request can be authenticated by this Authenticator.
|
||||
*/
|
||||
public boolean isHandle(MessageContext messageContext) {
|
||||
HttpServletRequest httpServletRequest = getHttpRequest(messageContext);
|
||||
if (httpServletRequest != null) {
|
||||
String headerValue = httpServletRequest.getHeader(HTTPConstants.HEADER_AUTHORIZATION);
|
||||
if (headerValue != null && !headerValue.trim().isEmpty()) {
|
||||
String[] headerPart = headerValue.trim().split(OauthAuthenticatorConstants.SPLITING_CHARACTOR);
|
||||
if (OauthAuthenticatorConstants.AUTHORIZATION_HEADER_PREFIX_BEARER.equals(headerPart[0])) {
|
||||
return true;
|
||||
}
|
||||
} else if (httpServletRequest.getParameter(OauthAuthenticatorConstants.BEARER_TOKEN_IDENTIFIER) != null) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticates the user using the provided OAuth token and returns the status as a boolean.
|
||||
* Sets the tenant domain and tenant friendly username to the session as attributes.
|
||||
*
|
||||
* @param messageContext containing the request need to be authenticated.
|
||||
* @return boolean indicating the authentication status.
|
||||
*/
|
||||
public boolean isAuthenticated(MessageContext messageContext) {
|
||||
HttpServletRequest httpServletRequest = getHttpRequest(messageContext);
|
||||
String headerValue = httpServletRequest.getHeader(HTTPConstants.HEADER_AUTHORIZATION);
|
||||
String[] headerPart = headerValue.trim().split(OauthAuthenticatorConstants.SPLITING_CHARACTOR);
|
||||
String accessToken = headerPart[ACCESS_TOKEN_INDEX];
|
||||
OAuthValidationResponse response = null;
|
||||
try {
|
||||
response = tokenValidator.validateToken(accessToken);
|
||||
} catch (RemoteException e) {
|
||||
log.error("Failed to validate the OAuth token provided.", e);
|
||||
}
|
||||
if (response != null && response.isValid()) {
|
||||
HttpSession session;
|
||||
if ((session = httpServletRequest.getSession(false)) != null) {
|
||||
session.setAttribute(MultitenantConstants.TENANT_DOMAIN, response.getTenantDomain());
|
||||
session.setAttribute(ServerConstants.USER_LOGGED_IN, response.getUserName());
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Authentication successful for " + session.getAttribute(ServerConstants.USER_LOGGED_IN));
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Authentication failed.Illegal attempt from session " + httpServletRequest.getSession().getId());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* this method is currently not implemented.
|
||||
*
|
||||
* @param messageContext containing the request need to be authenticated.
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean authenticateWithRememberMe(MessageContext messageContext) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string Authenticator name.
|
||||
*/
|
||||
public String getAuthenticatorName() {
|
||||
return OauthAuthenticatorConstants.AUTHENTICATOR_NAME;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int priority of the authenticator.
|
||||
*/
|
||||
public int getPriority() {
|
||||
return PRIORITY;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return boolean true for enable or otherwise for disable status.
|
||||
*/
|
||||
public boolean isDisabled() {
|
||||
AuthenticatorsConfiguration authenticatorsConfiguration = AuthenticatorsConfiguration.getInstance();
|
||||
AuthenticatorsConfiguration.AuthenticatorConfig authenticatorConfig = authenticatorsConfiguration.
|
||||
getAuthenticatorConfig(OauthAuthenticatorConstants.AUTHENTICATOR_NAME);
|
||||
return authenticatorConfig.isDisabled();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve HTTP Servlet Request form thr Message Context.
|
||||
*
|
||||
* @param messageContext Containing the Servlet Request for backend authentication.
|
||||
* @return HTTPServletRequest.
|
||||
*/
|
||||
private HttpServletRequest getHttpRequest(MessageContext messageContext) {
|
||||
return (HttpServletRequest) messageContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
|
||||
}
|
||||
|
||||
}
|
@ -1,29 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.wso2.carbon.identity.authenticator.backend.oauth;
|
||||
|
||||
public class OauthAuthenticatorConstants {
|
||||
public static final String AUTHORIZATION_HEADER_PREFIX_BEARER = "Bearer";
|
||||
public static final String AUTHORIZATION_HEADER_PREFIX_BASIC = "Basic";
|
||||
public static final String BEARER_TOKEN_TYPE = "bearer";
|
||||
public static final String BEARER_TOKEN_IDENTIFIER = "token";
|
||||
public static final String AUTHENTICATOR_NAME = "OAuthAuthenticator";
|
||||
public static final String SPLITING_CHARACTOR = " ";
|
||||
public static final String OAUTH_ENDPOINT_POSTFIX =
|
||||
"/services/OAuth2TokenValidationService.OAuth2TokenValidationServiceHttpsSoap12Endpoint/";
|
||||
}
|
@ -1,49 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* you may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.identity.authenticator.backend.oauth.internal;
|
||||
|
||||
import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService;
|
||||
|
||||
/**
|
||||
* DataHolder of Backend OAuth Authenticator component.
|
||||
*/
|
||||
public class OAuthAuthenticatorDataHolder {
|
||||
|
||||
private OAuth2TokenValidationService oAuth2TokenValidationService;
|
||||
|
||||
private static OAuthAuthenticatorDataHolder thisInstance = new OAuthAuthenticatorDataHolder();
|
||||
|
||||
private OAuthAuthenticatorDataHolder() {}
|
||||
|
||||
public static OAuthAuthenticatorDataHolder getInstance() {
|
||||
return thisInstance;
|
||||
}
|
||||
|
||||
public OAuth2TokenValidationService getOAuth2TokenValidationService() {
|
||||
if (oAuth2TokenValidationService == null) {
|
||||
throw new IllegalStateException("OAuth2TokenValidation service is not initialized properly");
|
||||
}
|
||||
return oAuth2TokenValidationService;
|
||||
}
|
||||
|
||||
public void setOAuth2TokenValidationService(
|
||||
OAuth2TokenValidationService oAuth2TokenValidationService) {
|
||||
this.oAuth2TokenValidationService = oAuth2TokenValidationService;
|
||||
}
|
||||
}
|
@ -1,83 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.identity.authenticator.backend.oauth.internal;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.osgi.framework.BundleContext;
|
||||
import org.osgi.service.component.ComponentContext;
|
||||
import org.wso2.carbon.core.services.authentication.CarbonServerAuthenticator;
|
||||
import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticator;
|
||||
import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService;
|
||||
import org.osgi.service.component.annotations.*;
|
||||
|
||||
@Component(
|
||||
name = "org.wso2.carbon.identity.backend.oauth.authenticator",
|
||||
immediate = true)
|
||||
public class OAuthAuthenticatorServiceComponent {
|
||||
|
||||
private static final Log log = LogFactory.getLog(OAuthAuthenticatorServiceComponent.class);
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
@Activate
|
||||
protected void activate(ComponentContext componentContext) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Starting Backend OAuthAuthenticator Framework Bundle");
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
@Deactivate
|
||||
protected void deactivate(ComponentContext componentContext) {
|
||||
//do nothing
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets OAuth2TokenValidation Service.
|
||||
*
|
||||
* @param tokenValidationService An instance of OAuth2TokenValidationService.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
@Reference(
|
||||
name = "identity.oauth2.validation.service",
|
||||
service = org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService.class,
|
||||
cardinality = ReferenceCardinality.MANDATORY,
|
||||
policy = ReferencePolicy.DYNAMIC,
|
||||
bind = "setOAuth2ValidationService",
|
||||
unbind = "unsetOAuth2ValidationService")
|
||||
protected void setOAuth2ValidationService(OAuth2TokenValidationService tokenValidationService) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Setting OAuth2TokenValidationService Service");
|
||||
}
|
||||
OAuthAuthenticatorDataHolder.getInstance().setOAuth2TokenValidationService(tokenValidationService);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsets OAuth2TokenValidation Service.
|
||||
*
|
||||
* @param tokenValidationService An instance of OAuth2TokenValidationService
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
protected void unsetOAuth2ValidationService(OAuth2TokenValidationService tokenValidationService) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Unsetting OAuth2TokenValidationService Service");
|
||||
}
|
||||
OAuthAuthenticatorDataHolder.getInstance().setOAuth2TokenValidationService(null);
|
||||
}
|
||||
}
|
@ -1,35 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.wso2.carbon.identity.authenticator.backend.oauth.validator;
|
||||
|
||||
import java.rmi.RemoteException;
|
||||
|
||||
/**
|
||||
* Declares the contract for OAuth2TokenValidator implementations.
|
||||
*/
|
||||
public interface OAuth2TokenValidator {
|
||||
|
||||
/**
|
||||
* This method gets a string accessToken and validates it and generate the OAuth2ClientApplicationDTO
|
||||
* containing the validity and user details if valid.
|
||||
*
|
||||
* @param accessToken which need to be validated.
|
||||
* @return OAuthValidationResponse with the validated results.
|
||||
*/
|
||||
OAuthValidationResponse validateToken(String accessToken) throws RemoteException;
|
||||
}
|
@ -1,59 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.wso2.carbon.identity.authenticator.backend.oauth.validator;
|
||||
|
||||
/**
|
||||
* This class holds the authenticated user information after the OAuth2 token is validated.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public class OAuthValidationResponse {
|
||||
|
||||
private String userName;
|
||||
private String tenantDomain;
|
||||
private boolean isValid;
|
||||
|
||||
public OAuthValidationResponse(String userName, String tenantDomain, boolean isValid) {
|
||||
this.userName = userName;
|
||||
this.tenantDomain = tenantDomain;
|
||||
this.isValid = isValid;
|
||||
}
|
||||
|
||||
public String getUserName() {
|
||||
return userName;
|
||||
}
|
||||
|
||||
public void setUserName(String userName) {
|
||||
this.userName = userName;
|
||||
}
|
||||
|
||||
public String getTenantDomain() {
|
||||
return tenantDomain;
|
||||
}
|
||||
|
||||
public void setTenantDomain(String tenantDomain) {
|
||||
this.tenantDomain = tenantDomain;
|
||||
}
|
||||
|
||||
public boolean isValid() {
|
||||
return isValid;
|
||||
}
|
||||
|
||||
public void setIsValid(boolean isValid) {
|
||||
this.isValid = isValid;
|
||||
}
|
||||
}
|
@ -1,68 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.wso2.carbon.identity.authenticator.backend.oauth.validator;
|
||||
|
||||
import org.wso2.carbon.core.security.AuthenticatorsConfiguration;
|
||||
import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorConstants;
|
||||
import org.wso2.carbon.identity.authenticator.backend.oauth.validator.impl.ExternalOAuthValidator;
|
||||
import org.wso2.carbon.identity.authenticator.backend.oauth.validator.impl.LocalOAuthValidator;
|
||||
|
||||
/**
|
||||
* The class validate the configurations and provide the most suitable implementation according to the configuration.
|
||||
* Factory class for OAuthValidator.
|
||||
*/
|
||||
public class OAuthValidatorFactory {
|
||||
|
||||
private static final String AUTHENTICATOR_CONFIG_IS_REMOTE = "isRemote";
|
||||
private static final String AUTHENTICATOR_CONFIG_HOST_URL = "hostURL";
|
||||
private static final String AUTHENTICATOR_CONFIG_ADMIN_USERNAME = "adminUsername";
|
||||
private static final String AUTHENTICATOR_CONFIG_ADMIN_PASSWORD = "adminPassword";
|
||||
|
||||
/**
|
||||
* The method check the configuration and provide the appropriate implementation for OAuth2TokenValidator
|
||||
*
|
||||
* @return OAuth2TokenValidator
|
||||
*/
|
||||
public static OAuth2TokenValidator getValidator() throws IllegalArgumentException {
|
||||
AuthenticatorsConfiguration authenticatorsConfiguration = AuthenticatorsConfiguration.getInstance();
|
||||
AuthenticatorsConfiguration.AuthenticatorConfig authenticatorConfig = authenticatorsConfiguration.
|
||||
getAuthenticatorConfig(OauthAuthenticatorConstants.AUTHENTICATOR_NAME);
|
||||
boolean isRemote;
|
||||
String hostUrl;
|
||||
String adminUserName;
|
||||
String adminPassword;
|
||||
if (authenticatorConfig != null && authenticatorConfig.getParameters() != null) {
|
||||
isRemote = Boolean.parseBoolean(authenticatorConfig.getParameters().get(
|
||||
AUTHENTICATOR_CONFIG_IS_REMOTE));
|
||||
hostUrl = authenticatorConfig.getParameters().get(AUTHENTICATOR_CONFIG_HOST_URL);
|
||||
adminUserName = authenticatorConfig.getParameters().get(AUTHENTICATOR_CONFIG_ADMIN_USERNAME);
|
||||
adminPassword = authenticatorConfig.getParameters().get(AUTHENTICATOR_CONFIG_ADMIN_PASSWORD);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Configuration parameters need to be defined in Authenticators.xml");
|
||||
}
|
||||
if (isRemote) {
|
||||
if (!(hostUrl == null || hostUrl.trim().isEmpty())) {
|
||||
hostUrl = hostUrl + OauthAuthenticatorConstants.OAUTH_ENDPOINT_POSTFIX;
|
||||
return new ExternalOAuthValidator(hostUrl, adminUserName, adminPassword);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Remote server name and ip both can't be empty");
|
||||
}
|
||||
}
|
||||
return new LocalOAuthValidator();
|
||||
}
|
||||
}
|
@ -1,95 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.wso2.carbon.identity.authenticator.backend.oauth.validator.impl;
|
||||
|
||||
import org.apache.axis2.client.Options;
|
||||
import org.apache.axis2.client.ServiceClient;
|
||||
import org.apache.axis2.transport.http.HTTPConstants;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.httpclient.Header;
|
||||
import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorConstants;
|
||||
import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator;
|
||||
import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationResponse;
|
||||
import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub;
|
||||
import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO;
|
||||
import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_OAuth2AccessToken;
|
||||
import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO;
|
||||
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
|
||||
|
||||
import java.rmi.RemoteException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Handles the Authentication form external IDP servers. Currently supports WSO2 IS only.
|
||||
*/
|
||||
public class ExternalOAuthValidator implements OAuth2TokenValidator{
|
||||
|
||||
private String hostURL;
|
||||
private String adminUserName;
|
||||
private String adminPassword;
|
||||
|
||||
public ExternalOAuthValidator(String hostURL, String adminUserName, String adminPassword) {
|
||||
this.hostURL = hostURL;
|
||||
this.adminUserName = adminUserName;
|
||||
this.adminPassword = adminPassword;
|
||||
}
|
||||
/**
|
||||
* This method gets a string accessToken and validates it and generate the OAuth2ClientApplicationDTO
|
||||
* containing the validity and user details if valid.
|
||||
*
|
||||
* @param token which need to be validated.
|
||||
* @return OAuthValidationResponse with the validated results.
|
||||
*/
|
||||
public OAuthValidationResponse validateToken(String token) throws RemoteException {
|
||||
OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO();
|
||||
OAuth2TokenValidationRequestDTO_OAuth2AccessToken accessToken =
|
||||
new OAuth2TokenValidationRequestDTO_OAuth2AccessToken();
|
||||
accessToken.setTokenType(OauthAuthenticatorConstants.BEARER_TOKEN_TYPE);
|
||||
accessToken.setIdentifier(token);
|
||||
validationRequest.setAccessToken(accessToken);
|
||||
OAuth2TokenValidationServiceStub tokenValidationService =
|
||||
new OAuth2TokenValidationServiceStub(hostURL);
|
||||
ServiceClient client = tokenValidationService._getServiceClient();
|
||||
Options options = client.getOptions();
|
||||
List<Header> headerList = new ArrayList<>();
|
||||
Header header = new Header();
|
||||
header.setName(HTTPConstants.HEADER_AUTHORIZATION);
|
||||
header.setValue(OauthAuthenticatorConstants.AUTHORIZATION_HEADER_PREFIX_BASIC + " " + getBasicAuthCredentials());
|
||||
headerList.add(header);
|
||||
options.setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_HEADERS, headerList);
|
||||
client.setOptions(options);
|
||||
OAuth2TokenValidationResponseDTO tokenValidationResponse = tokenValidationService.
|
||||
findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse();
|
||||
boolean isValid = tokenValidationResponse.getValid();
|
||||
String userName = null;
|
||||
String tenantDomain = null;
|
||||
if (isValid) {
|
||||
userName = MultitenantUtils.getTenantAwareUsername(
|
||||
tokenValidationResponse.getAuthorizedUser());
|
||||
tenantDomain = MultitenantUtils.
|
||||
getTenantDomain(tokenValidationResponse.getAuthorizedUser());
|
||||
}
|
||||
return new OAuthValidationResponse(userName,tenantDomain,isValid);
|
||||
}
|
||||
|
||||
private String getBasicAuthCredentials() {
|
||||
byte[] bytesEncoded = Base64.encodeBase64((adminUserName + ":" + adminPassword).getBytes());
|
||||
return new String(bytesEncoded);
|
||||
}
|
||||
}
|
@ -1,60 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.wso2.carbon.identity.authenticator.backend.oauth.validator.impl;
|
||||
|
||||
import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorConstants;
|
||||
import org.wso2.carbon.identity.authenticator.backend.oauth.internal.OAuthAuthenticatorDataHolder;
|
||||
import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator;
|
||||
import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationResponse;
|
||||
import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService;
|
||||
import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO;
|
||||
import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO;
|
||||
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
|
||||
|
||||
/**
|
||||
* Handles the authentication using the inbuilt IS features.
|
||||
*/
|
||||
public class LocalOAuthValidator implements OAuth2TokenValidator {
|
||||
/**
|
||||
* This method gets a string accessToken and validates it and generate the OAuth2ClientApplicationDTO
|
||||
* containing the validity and user details if valid.
|
||||
*
|
||||
* @param token which need to be validated.
|
||||
* @return OAuthValidationResponse with the validated results.
|
||||
*/
|
||||
public OAuthValidationResponse validateToken(String token) {
|
||||
OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO();
|
||||
OAuth2TokenValidationRequestDTO.OAuth2AccessToken accessToken =
|
||||
validationRequest.new OAuth2AccessToken();
|
||||
accessToken.setTokenType(OauthAuthenticatorConstants.BEARER_TOKEN_TYPE);
|
||||
accessToken.setIdentifier(token);
|
||||
validationRequest.setAccessToken(accessToken);
|
||||
OAuth2TokenValidationResponseDTO tokenValidationResponse = OAuthAuthenticatorDataHolder.getInstance().
|
||||
getOAuth2TokenValidationService().findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse();
|
||||
boolean isValid = tokenValidationResponse.isValid();
|
||||
String userName = null;
|
||||
String tenantDomain = null;
|
||||
if (isValid) {
|
||||
userName = MultitenantUtils.getTenantAwareUsername(
|
||||
tokenValidationResponse.getAuthorizedUser());
|
||||
tenantDomain =
|
||||
MultitenantUtils.getTenantDomain(tokenValidationResponse.getAuthorizedUser());
|
||||
}
|
||||
return new OAuthValidationResponse(userName, tenantDomain, isValid);
|
||||
}
|
||||
}
|
@ -1,107 +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>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<artifactId>policy-mgt</artifactId>
|
||||
<version>5.0.0-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<artifactId>org.wso2.carbon.complex.policy.decision.point</artifactId>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - Policy Decision Point</name>
|
||||
<description>WSO2 Carbon - Policy Decision Point</description>
|
||||
<url>https://entgra.io</url>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
<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>Complex Policy Decision Point Bundle</Bundle-Description>
|
||||
<Private-Package>org.wso2.carbon.complex.policy.decision.point.internal</Private-Package>
|
||||
<Export-Package>
|
||||
org.wso2.carbon.complex.policy.decision.point.*
|
||||
</Export-Package>
|
||||
</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>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.equinox</groupId>
|
||||
<artifactId>org.eclipse.equinox.common</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.ops4j.pax.logging</groupId>
|
||||
<artifactId>pax-logging-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
<!-- <version>${pax.logging.api.version}</version>-->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.entgra.device.mgt.core</groupId>
|
||||
<artifactId>io.entgra.device.mgt.core.policy.mgt.common</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
|
@ -1,48 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
|
||||
package org.wso2.carbon.policy.evaluator;
|
||||
|
||||
import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy;
|
||||
import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface FeatureFilter {
|
||||
|
||||
List<ProfileFeature> evaluate(List<Policy> policyList, List<FeatureRules> featureRulesList);
|
||||
|
||||
List<ProfileFeature> extractFeatures(List<Policy> policyList);
|
||||
|
||||
List<ProfileFeature> evaluateFeatures(List<ProfileFeature> featureList, List<FeatureRules> featureRulesList);
|
||||
|
||||
void getDenyOverridesFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList);
|
||||
|
||||
void getPermitOverridesFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList);
|
||||
|
||||
void getFirstApplicableFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList);
|
||||
|
||||
void getLastApplicableFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList);
|
||||
|
||||
void getAllApplicableFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList);
|
||||
|
||||
void getHighestApplicableFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList);
|
||||
|
||||
void getLowestApplicableFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList);
|
||||
}
|
@ -1,250 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.policy.evaluator;
|
||||
|
||||
import org.wso2.carbon.policy.evaluator.utils.Constants;
|
||||
import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy;
|
||||
import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.ProfileFeature;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* This class is responsible for evaluating the policy (Configurations sets) and returning
|
||||
* the effective features set.
|
||||
*/
|
||||
|
||||
public class FeatureFilterImpl implements FeatureFilter {
|
||||
|
||||
/**
|
||||
* This method returns the effective feature list when policy list and feature aggregation rules are supplied.
|
||||
* @param policyList
|
||||
* @param featureRulesList
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public List<ProfileFeature> evaluate(List<Policy> policyList, List<FeatureRules> featureRulesList) {
|
||||
return evaluateFeatures(extractFeatures(policyList), featureRulesList);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method extract the features from the given policy list in the order they are provided in the list.
|
||||
* @param policyList
|
||||
* @return
|
||||
*/
|
||||
public List<ProfileFeature> extractFeatures(List<Policy> policyList) {
|
||||
List<ProfileFeature> featureList = new ArrayList<ProfileFeature>();
|
||||
for (Policy policy : policyList) {
|
||||
featureList.addAll(policy.getProfile().getProfileFeaturesList());
|
||||
}
|
||||
return featureList;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is responsible for supplying tasks to other methods to evaluate given features.
|
||||
* @param featureList
|
||||
* @param featureRulesList
|
||||
* @return
|
||||
*/
|
||||
public List<ProfileFeature> evaluateFeatures(List<ProfileFeature> featureList, List<FeatureRules> featureRulesList) {
|
||||
List<ProfileFeature> effectiveFeatureList = new ArrayList<ProfileFeature>();
|
||||
for (FeatureRules rule : featureRulesList) {
|
||||
String ruleName = rule.getEvaluationCriteria();
|
||||
String featureName = rule.getName();
|
||||
if (Constants.DENY_OVERRIDES.equalsIgnoreCase(ruleName)) {
|
||||
getDenyOverridesFeatures(featureName, featureList, effectiveFeatureList);
|
||||
}
|
||||
if (Constants.PERMIT_OVERRIDES.equalsIgnoreCase(ruleName)) {
|
||||
getPermitOverridesFeatures(featureName, featureList, effectiveFeatureList);
|
||||
}
|
||||
if (Constants.FIRST_APPLICABLE.equalsIgnoreCase(ruleName)) {
|
||||
getFirstApplicableFeatures(featureName, featureList, effectiveFeatureList);
|
||||
}
|
||||
if (Constants.LAST_APPLICABLE.equalsIgnoreCase(ruleName)) {
|
||||
getLastApplicableFeatures(featureName, featureList, effectiveFeatureList);
|
||||
}
|
||||
if (Constants.ALL_APPLICABLE.equalsIgnoreCase(ruleName)) {
|
||||
getAllApplicableFeatures(featureName, featureList, effectiveFeatureList);
|
||||
}
|
||||
if (Constants.HIGHEST_APPLICABLE.equalsIgnoreCase(ruleName)) {
|
||||
getHighestApplicableFeatures(featureName, featureList, effectiveFeatureList);
|
||||
}
|
||||
if (Constants.LOWEST_APPLICABLE.equalsIgnoreCase(ruleName)) {
|
||||
getLowestApplicableFeatures(featureName, featureList, effectiveFeatureList);
|
||||
}
|
||||
}
|
||||
return effectiveFeatureList;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method picks up denied features, if there is no denied features it will add to the list, the final permitted feature.
|
||||
* But if given policies do not have features of given type, it will not add anything.
|
||||
*
|
||||
* @param featureName
|
||||
* @param featureList
|
||||
* @param effectiveFeatureList
|
||||
*/
|
||||
public void getDenyOverridesFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList) {
|
||||
ProfileFeature evaluatedFeature = null;
|
||||
// for (ProfileFeature feature : featureList) {
|
||||
// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
|
||||
// if (feature.getFeature().getRuleValue().equalsIgnoreCase("Deny")) {
|
||||
// evaluatedFeature = feature;
|
||||
// effectiveFeatureList.add(evaluatedFeature);
|
||||
// return;
|
||||
// } else {
|
||||
// evaluatedFeature = feature;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
if (evaluatedFeature != null) {
|
||||
effectiveFeatureList.add(evaluatedFeature);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* This method picks up permitted features, if there is no permitted features it will add to the list, the final denied feature.
|
||||
* But if given policies do not have features of given type, it will not add anything.
|
||||
*
|
||||
* @param featureName
|
||||
* @param featureList
|
||||
* @param effectiveFeatureList
|
||||
*/
|
||||
public void getPermitOverridesFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList) {
|
||||
ProfileFeature evaluatedFeature = null;
|
||||
// for (ProfileFeature feature : featureList) {
|
||||
// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
|
||||
// if (feature.getFeature().getRuleValue().equalsIgnoreCase("Permit")) {
|
||||
// evaluatedFeature = feature;
|
||||
// effectiveFeatureList.add(evaluatedFeature);
|
||||
// return;
|
||||
// } else {
|
||||
// evaluatedFeature = feature;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
if (evaluatedFeature != null) {
|
||||
effectiveFeatureList.add(evaluatedFeature);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* This method picks the first features of the give type.
|
||||
* But if given policies do not have features of given type, it will not add anything.
|
||||
*
|
||||
* @param featureName
|
||||
* @param featureList
|
||||
* @param effectiveFeatureList
|
||||
*/
|
||||
public void getFirstApplicableFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList) {
|
||||
for (ProfileFeature feature : featureList) {
|
||||
// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
|
||||
// effectiveFeatureList.add(feature);
|
||||
// return;
|
||||
//
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method picks the last features of the give type.
|
||||
* But if given policies do not have features of given type, it will not add anything.
|
||||
*
|
||||
* @param featureName
|
||||
* @param featureList
|
||||
* @param effectiveFeatureList
|
||||
*/
|
||||
public void getLastApplicableFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList) {
|
||||
ProfileFeature evaluatedFeature = null;
|
||||
// for (ProfileFeature feature : featureList) {
|
||||
// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
|
||||
// evaluatedFeature = feature;
|
||||
// }
|
||||
// }
|
||||
if (evaluatedFeature != null) {
|
||||
effectiveFeatureList.add(evaluatedFeature);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method picks the all features of the give type.
|
||||
* But if given policies do not have features of given type, it will not add anything.
|
||||
*
|
||||
* @param featureName
|
||||
* @param featureList
|
||||
* @param effectiveFeatureList
|
||||
*/
|
||||
public void getAllApplicableFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList) {
|
||||
for (ProfileFeature feature : featureList) {
|
||||
// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
|
||||
// effectiveFeatureList.add(feature);
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method picks the feature with the highest value of given type.
|
||||
* But if given policies do not have features of given type, it will not add anything.
|
||||
*
|
||||
* @param featureName
|
||||
* @param featureList
|
||||
* @param effectiveFeatureList
|
||||
*/
|
||||
public void getHighestApplicableFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList) {
|
||||
ProfileFeature evaluatedFeature = null;
|
||||
int intValve = 0;
|
||||
// for (ProfileFeature feature : featureList) {
|
||||
// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
|
||||
// if (Integer.parseInt(feature.getFeature().getRuleValue()) > intValve) {
|
||||
// intValve = Integer.parseInt(feature.getFeature().getRuleValue());
|
||||
// evaluatedFeature = feature;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
if (evaluatedFeature != null) {
|
||||
effectiveFeatureList.add(evaluatedFeature);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method picks the feature with the lowest value of given type.
|
||||
* But if given policies do not have features of given type, it will not add anything.
|
||||
*
|
||||
* @param featureName
|
||||
* @param featureList
|
||||
* @param effectiveFeatureList
|
||||
*/
|
||||
public void getLowestApplicableFeatures(String featureName, List<ProfileFeature> featureList, List<ProfileFeature> effectiveFeatureList) {
|
||||
ProfileFeature evaluatedFeature = null;
|
||||
// int intValve = 0;
|
||||
// for (ProfileFeature feature : featureList) {
|
||||
// if (feature.getFeature().getName().equalsIgnoreCase(featureName)) {
|
||||
// if (Integer.parseInt(feature.getFeature().getRuleValue()) < intValve) {
|
||||
// intValve = Integer.parseInt(feature.getFeature().getRuleValue());
|
||||
// evaluatedFeature = feature;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
if (evaluatedFeature != null) {
|
||||
effectiveFeatureList.add(evaluatedFeature);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,41 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.policy.evaluator;
|
||||
|
||||
public class FeatureRules {
|
||||
|
||||
private String name;
|
||||
private String evaluationCriteria;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getEvaluationCriteria() {
|
||||
return evaluationCriteria;
|
||||
}
|
||||
|
||||
public void setEvaluationCriteria(String evaluationCriteria) {
|
||||
this.evaluationCriteria = evaluationCriteria;
|
||||
}
|
||||
}
|
@ -1,54 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* you may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.policy.evaluator;
|
||||
|
||||
public class PDPException extends Exception {
|
||||
|
||||
private String pdpErrorMessage;
|
||||
|
||||
public String getPdpErrorMessage() {
|
||||
return pdpErrorMessage;
|
||||
}
|
||||
|
||||
public void setPdpErrorMessage(String pdpErrorMessage) {
|
||||
this.pdpErrorMessage = pdpErrorMessage;
|
||||
}
|
||||
|
||||
public PDPException(String message) {
|
||||
setPdpErrorMessage(message);
|
||||
}
|
||||
|
||||
public PDPException(String message, Exception ex) {
|
||||
super(message, ex);
|
||||
setPdpErrorMessage(message);
|
||||
}
|
||||
|
||||
public PDPException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
setPdpErrorMessage(message);
|
||||
}
|
||||
|
||||
public PDPException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public PDPException(){
|
||||
super();
|
||||
}
|
||||
}
|
@ -1,37 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.policy.evaluator;
|
||||
|
||||
import org.wso2.carbon.policy.evaluator.spi.PDPService;
|
||||
import io.entgra.device.mgt.core.policy.mgt.common.Feature;
|
||||
import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class PDPServiceImpl implements PDPService {
|
||||
@Override
|
||||
public List<Policy> getEffectivePolicyList(List<Policy> policies, List<String> roles, String deviceType) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Feature> getEffectiveFeatureList(List<Policy> policies, List<FeatureRules> featureRulesList) {
|
||||
return null;
|
||||
}
|
||||
}
|
@ -1,43 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
|
||||
package org.wso2.carbon.policy.evaluator;
|
||||
|
||||
import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface PolicyFilter {
|
||||
|
||||
/**
|
||||
* This method will extract the policies related a given roles list from the policy list available.
|
||||
* @param policyList
|
||||
* @param roles
|
||||
* @return
|
||||
*/
|
||||
public List<Policy> extractPoliciesRelatedToRoles(List<Policy> policyList, List<String> roles);
|
||||
|
||||
/**
|
||||
* This mehtod extract the policies related to a given device type from policy list.
|
||||
* @param policyList
|
||||
* @param deviceType
|
||||
* @return
|
||||
*/
|
||||
public List<Policy> extractPoliciesRelatedToDeviceType(List<Policy> policyList, String deviceType);
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue