Automated api calls with http client

scep-fix3
Pasindu Rupasinghe 2 years ago
parent fa7ee67aed
commit ac834d0359

@ -0,0 +1,148 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2023, Entgra (Pvt) Ltd. (http://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>org.wso2.carbon.devicemgt</groupId>
<version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>io.entgra.devicemgt.apimgt.extension.publisher.api</artifactId>
<packaging>bundle</packaging>
<name>Entgra - Device API Management Extension Publisher API</name>
<description>Entgra - Device API Management Extension Publisher API</description>
<url>https://entgra.io</url>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents.wso2</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.orbit.org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>1.4.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
<Bundle-Description>Publisher API Management Bundle</Bundle-Description>
<Export-Package>
io.entgra.devicemgt.apimgt.extension.publisher.api.*
</Export-Package>
<Import-Package>
javax.net.ssl,
javax.xml.bind,
org.apache.commons.logging,
org.apache.http;version="${httpclient.version.range}",
org.apache.http.client;version="${httpclient.version.range}",
org.apache.http.client.methods;version="${httpclient.version.range}",
org.apache.http.conn.socket,
org.apache.http.conn.ssl,
org.apache.http.entity,
org.apache.http.impl.client,
org.apache.http.util;version="${httpclient.version.range}",
org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.*;version="${imp.package.version.osgi.service}",
com.sun.jndi.toolkit.ctx,
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>
<!-- <plugin>-->
<!-- <groupId>org.apache.maven.plugins</groupId>-->
<!-- <artifactId>maven-surefire-plugin</artifactId>-->
<!-- <configuration>-->
<!-- <systemPropertyVariables>-->
<!-- <log4j.configuration>file:src/test/resources/log4j.properties</log4j.configuration>-->
<!-- </systemPropertyVariables>-->
<!-- <suiteXmlFiles>-->
<!-- <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>-->
<!-- </suiteXmlFiles>-->
<!-- </configuration>-->
<!-- </plugin>-->
</plugins>
</build>
<properties>
<maven.test.skip>true</maven.test.skip>
</properties>
</project>

@ -0,0 +1,6 @@
package io.entgra.devicemgt.apimgt.extension.publisher.api;
public interface PublisherAPIService {
void registerApplication();
}

@ -0,0 +1,72 @@
package io.entgra.devicemgt.apimgt.extension.publisher.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import javax.xml.bind.DatatypeConverter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
public class PublisherAPIServiceImpl implements PublisherAPIService {
private static final Log log = LogFactory.getLog(PublisherAPIServiceImpl.class);
@Override
public void registerApplication() {
try {
HttpClient httpclient;
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
httpclient = org.apache.http.impl.client.HttpClients.custom().setSSLSocketFactory(sslsf).useSystemProperties().build();
URL url =new URL("https://localhost:9443/client-registration/v0.17/register");
HttpPost request = new HttpPost(url.toString());
String payload = "{\n" +
" \"callbackUrl\":\"www.google.lk\",\n" +
" \"clientName\":\"rest_api_publisher_code\",\n" +
" \"owner\":\"admin\",\n" +
" \"grantType\":\"client_credentials password refresh_token\",\n" +
" \"saasApp\":true\n" +
" }";
StringEntity entity = new StringEntity(payload);
request.setEntity(entity);
String encoding = DatatypeConverter.printBase64Binary("admin:admin".getBytes("UTF-8"));
request.setHeader("Authorization", "Basic " + encoding);
request.setHeader("Content-Type", "application/json");
HttpResponse httpResponse = httpclient.execute(request);
if (httpResponse != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String readLine;
String response = "";
while (((readLine = br.readLine()) != null)) {
response += readLine;
}
System.out.println(response);
}
System.out.println(httpResponse.getStatusLine().getStatusCode());
} catch (IOException | NoSuchAlgorithmException | KeyStoreException |
KeyManagementException e) {
log.error("failed to call http client.", e);
}
}
}

@ -0,0 +1,50 @@
package io.entgra.devicemgt.apimgt.extension.publisher.api.dto;
public class AccessTokenInfo {
private String tokenType;
private long expiresIn;
private String refreshToken;
private String accessToken;
private String scope;
public String getTokenType() {
return tokenType;
}
public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}
public long getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(long expiresIn) {
this.expiresIn = expiresIn;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
}

@ -0,0 +1,33 @@
package io.entgra.devicemgt.apimgt.extension.publisher.api.internal;
import com.sun.jndi.toolkit.ctx.ComponentContext;
import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherAPIService;
import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherAPIServiceImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import java.io.IOException;
/**
* @scr.component name="io.entgra.devicemgt.apimgt.extension.publisher.api.internal.PublisherAPIServiceComponent"
* immediate="true"
*/
public class PublisherAPIServiceComponent {
private static Log log = LogFactory.getLog(PublisherAPIServiceComponent.class);
protected void activate(ComponentContext componentContext) {
if (log.isDebugEnabled()) {
log.debug("Initializing publisher API extension bundle");
}
PublisherAPIService publisherAPIService = new PublisherAPIServiceImpl();
}
protected void deactivate(ComponentContext componentContext) {
//do nothing
}
}

@ -0,0 +1,72 @@
package io.entgra.devicemgt.apimgt.extension.publisher.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.wso2.carbon.utils.CarbonUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
public class PublisherAPIUtil {
private static final Log log = LogFactory.getLog(PublisherAPIUtil.class);
private static final String HTTPS_PROTOCOL = "https";
private static final String TENANT_JWT_CONFIG_LOCATION = File.separator + "jwt-config" + File.separator + "jwt.properties";
private static final String JWT_CONFIG_FILE_NAME = "jwt.properties";
private static final String SUPERTENANT_JWT_CONFIG_LOCATION =
CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + JWT_CONFIG_FILE_NAME;
/**
* Return a http client instance
*
* @param protocol- service endpoint protocol http/https
* @return
*/
public static HttpClient getHttpClient(String protocol)
throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
HttpClient httpclient;
if (HTTPS_PROTOCOL.equals(protocol)) {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).useSystemProperties().build();
} else {
httpclient = HttpClients.createDefault();
}
return httpclient;
}
public static String getResponseString(HttpResponse httpResponse) throws IOException {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String readLine;
String response = "";
while (((readLine = br.readLine()) != null)) {
response += readLine;
}
return response;
} finally {
EntityUtils.consumeQuietly(httpResponse.getEntity());
if (br != null) {
try {
br.close();
} catch (IOException e) {
log.warn("Error while closing the connection! " + e.getMessage());
}
}
}
}
}

@ -122,6 +122,10 @@
<artifactId>h2-database-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>io.entgra.devicemgt.apimgt.extension.publisher.api</artifactId>
</dependency>
</dependencies>
@ -165,6 +169,7 @@
org.scannotation;version="1.0",
org.scannotation.archiveiterator;version="1.0",
org.w3c.dom,
io.entgra.devicemgt.apimgt.extension.publisher.api,
org.wso2.carbon.apimgt.annotations.api,
org.wso2.carbon.apimgt.api,
org.wso2.carbon.apimgt.api.model,

@ -19,6 +19,7 @@
package org.wso2.carbon.apimgt.webapp.publisher;
import io.entgra.devicemgt.apimgt.extension.publisher.api.ScopeServices;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException;
@ -37,6 +38,7 @@ public class APIPublisherStartupHandler implements ServerStartupObserver {
private static Stack<APIConfig> currentAPIsStack;
private APIPublisherService publisher;
private ScopeServices scopeServices;
@Override
public void completingServerStartup() {
@ -55,6 +57,12 @@ public class APIPublisherStartupHandler implements ServerStartupObserver {
log.debug("Total number of unpublished APIs: "
+ APIPublisherDataHolder.getInstance().getUnpublishedApis().size());
}
try {
scopeServices.registerApplication();
} catch (Exception e) {
throw new RuntimeException(e);
}
publisher = APIPublisherDataHolder.getInstance().getApiPublisherService();
int retryCount = 0;
while (retryCount < MAX_RETRY_COUNT && (!failedAPIsStack.isEmpty() || !currentAPIsStack.isEmpty())) {

@ -25,6 +25,24 @@
<version>5.0.26-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents.wso2</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.orbit.org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
</dependencies>
<modelVersion>4.0.0</modelVersion>
<artifactId>apimgt-extensions</artifactId>
@ -40,6 +58,7 @@
<module>org.wso2.carbon.apimgt.keymgt.extension</module>
<module>org.wso2.carbon.apimgt.keymgt.extension.api</module>
<module>io.entgra.device.mgt.core.apimgt.analytics.extension</module>
<module>io.entgra.devicemgt.apimgt.extension.publisher.api</module>
</modules>
<build>

@ -238,6 +238,11 @@
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<version>${carbon.device.mgt.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>io.entgra.devicemgt.apimgt.extension.publisher.api</artifactId>
<version>${carbon.device.mgt.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.oauth.extensions</artifactId>

Loading…
Cancel
Save