revert-70aa11f8
Rasika Perera 8 years ago
commit 6a623f5657

@ -1,5 +1,7 @@
# carbon-device-mgt
<a href='https://wso2.org/jenkins/job/platform-builds/job/carbon-device-mgt/'><img src='https://wso2.org/jenkins/job/platform-builds/job/carbon-device-mgt/badge/icon'></a>
WSO2 CONNECTED DEVICE MANAGEMENT COMPONENTS
WSO2 Connected Device Manager (WSO2 CDM) is a comprehensive platform that helps solve mobile computing challenges enterprises face today when dealing with both corporate owned, personally enabled (COPE) devices and employee owned devices as part of a bring your own device (BYOD) program.

@ -22,13 +22,13 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>WSO2 Carbon - API Management Annotations</name>
<description>WSO2 Carbon - API Management Custom Annotation Module</description>

@ -21,12 +21,12 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<artifactId>org.wso2.carbon.apimgt.application.extension.api</artifactId>
<packaging>war</packaging>
<name>WSO2 Carbon - API Application Management API</name>

@ -51,12 +51,4 @@ public interface ApiApplicationRegistrationService {
@Path("register")
Response register(RegistrationProfile registrationProfile);
/**
* This method is used to unregister an API application.
* @param applicationName name of the application that needs to be unregistered.
* @return the response status of request.
*/
@DELETE
@Path("unregister")
Response unregister(@QueryParam("applicationName") String applicationName);
}

@ -18,6 +18,7 @@
package org.wso2.carbon.apimgt.application.extension.api;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONObject;
@ -60,11 +61,10 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi
}
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
.getRealmConfiguration().getAdminUserName();
username = username + "@" + APIUtil.getTenantDomainOftheUser();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username);
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
applicationName, APIUtil.getAllowedApisTags().toArray(new String[APIUtil.getAllowedApisTags().size()]),
applicationName, APIUtil.getDefaultTags(),
ApiApplicationConstants.DEFAULT_TOKEN_TYPE, username, false,
ApiApplicationConstants.DEFAULT_VALIDITY_PERIOD);
return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build();
@ -96,7 +96,9 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi
return Response.status(Response.Status.NOT_ACCEPTABLE).entity("APIs(Tags) are not allowed to this user."
).build();
}
String username = APIUtil.getAuthenticatedUser() + "@" + APIUtil.getTenantDomainOftheUser();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(PrivilegedCarbonContext.
getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration().getAdminUserName());
String username = APIUtil.getAuthenticatedUser();
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String validityPeriod;
if (registrationProfile.getValidityPeriod() == null) {
@ -104,51 +106,29 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi
} else {
validityPeriod = registrationProfile.getValidityPeriod();
}
if (registrationProfile.isMappingAnExistingOAuthApp()) {
JSONObject jsonStringObject = new JSONObject();
jsonStringObject.put(ApiApplicationConstants.JSONSTRING_USERNAME_TAG, username);
jsonStringObject.put(ApiApplicationConstants.JSONSTRING_KEY_TYPE_TAG,
ApiApplicationConstants.DEFAULT_TOKEN_TYPE);
jsonStringObject.put(ApiApplicationConstants.OAUTH_CLIENT_ID, registrationProfile.getConsumerKey());
jsonStringObject.put(ApiApplicationConstants.OAUTH_CLIENT_SECRET,
registrationProfile.getConsumerSecret());
jsonStringObject.put(ApiApplicationConstants.JSONSTRING_VALIDITY_PERIOD_TAG, validityPeriod);
apiManagementProviderService.registerExistingOAuthApplicationToAPIApplication(
jsonStringObject.toJSONString(), registrationProfile.getApplicationName(),
registrationProfile.getConsumerKey(), username, registrationProfile.isAllowedToAllDomains(),
ApiApplicationConstants.DEFAULT_TOKEN_TYPE, registrationProfile.getTags());
return Response.status(Response.Status.ACCEPTED).entity("true").build();
} else {
String applicationName = registrationProfile.getApplicationName();
synchronized (ApiApplicationRegistrationServiceImpl.class) {
ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
registrationProfile.getApplicationName(), registrationProfile.getTags(),
applicationName, registrationProfile.getTags(),
ApiApplicationConstants.DEFAULT_TOKEN_TYPE, username,
registrationProfile.isAllowedToAllDomains(), validityPeriod);
return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build();
}
} catch (APIManagerException e) {
String msg = "Error occurred while registering an application '"
+ registrationProfile.getApplicationName() + "'";
String msg = "Error occurred while registering an application with apis '"
+ StringUtils.join(registrationProfile.getTags(), ",") + "'";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("false").build();
} catch (DeviceManagementException e) {
String msg = "Failed to retrieve the device service";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Path("unregister")
@DELETE
public Response unregister(@QueryParam("applicationName") String applicationName) {
try {
String username = APIUtil.getAuthenticatedUser() + "@" + APIUtil.getTenantDomainOftheUser();
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
apiManagementProviderService.removeAPIApplication(applicationName, username);
return Response.status(Response.Status.ACCEPTED).build();
} catch (APIManagerException e) {
String msg = "Error occurred while removing the application '" + applicationName;
} catch (UserStoreException e) {
String msg = "Failed to access user space.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
}

@ -23,6 +23,7 @@ import org.wso2.carbon.apimgt.application.extension.api.util.APIUtil;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
@ -120,7 +121,8 @@ public class ApiPermissionFilter implements Filter {
try {
UserRealm userRealm = APIUtil.getRealmService().getTenantUserRealm(PrivilegedCarbonContext
.getThreadLocalCarbonContext().getTenantId());
return userRealm.getAuthorizationManager().isUserAuthorized(username, permission, action);
String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
return userRealm.getAuthorizationManager().isUserAuthorized(tenantAwareUsername, permission, action);
} catch (UserStoreException e) {
String errorMsg = String.format("Unable to authorize the user : %s", username);
log.error(errorMsg, e);

@ -31,6 +31,7 @@ import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
@ -95,8 +96,13 @@ public class APIUtil {
return deviceManagementProviderService;
}
public static String[] getDefaultTags() throws DeviceManagementException {
String[] allowedApisTags = new String[1];
allowedApisTags[0] = DEFAULT_CDMF_API_TAG;
return allowedApisTags;
}
public static List<String> getAllowedApisTags() throws DeviceManagementException {
//Todo get allowed cdmf service tags from config.
List<String> allowedApisTags = getDeviceManagementProviderService().getAvailableDeviceTypes();
allowedApisTags.add(DEFAULT_CDMF_API_TAG);
allowedApisTags.add(DEFAULT_CERT_API_TAG);

@ -30,17 +30,12 @@ import javax.xml.bind.annotation.XmlRootElement;
@JsonIgnoreProperties(ignoreUnknown = true)
public class RegistrationProfile {
@XmlElement(required = true)
private String applicationName;
@XmlElement(required = true)
private String tags[];
@XmlElement(required = true)
private boolean isAllowedToAllDomains;
@XmlElement(required = true)
private boolean isMappingAnExistingOAuthApp;
private String consumerKey;
private String consumerSecret;
@XmlElement(required = false)
private String validityPeriod;
@ -68,30 +63,6 @@ public class RegistrationProfile {
this.isAllowedToAllDomains = isAllowedToAllDomains;
}
public boolean isMappingAnExistingOAuthApp() {
return isMappingAnExistingOAuthApp;
}
public void setIsMappingAnExistingOAuthApp(boolean isMappingAnExistingOAuthApp) {
this.isMappingAnExistingOAuthApp = isMappingAnExistingOAuthApp;
}
public String getConsumerKey() {
return consumerKey;
}
public void setConsumerKey(String consumerKey) {
this.consumerKey = consumerKey;
}
public String getConsumerSecret() {
return consumerSecret;
}
public void setConsumerSecret(String consumerSecret) {
this.consumerSecret = consumerSecret;
}
public String getValidityPeriod() {
return validityPeriod;
}

@ -37,16 +37,9 @@
</Permission>
<Permission>
<name>Register application</name>
<path>/device-mgt/api/application</path>
<path>/device-mgt/device/api/subscribe</path>
<url>/register</url>
<method>POST</method>
<scope>application_user</scope>
</Permission>
<Permission>
<name>Delete application</name>
<path>/device-mgt/api/application</path>
<url>/unregister</url>
<method>DELETE</method>
<scope>application_user</scope>
</Permission>
</PermissionConfiguration>

@ -22,12 +22,12 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<packaging>bundle</packaging>
<name>WSO2 Carbon - API Application Management</name>
@ -52,12 +52,12 @@
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.impl</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.integration.client</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.api</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.integration.generated.client</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple.wso2</groupId>
@ -100,16 +100,17 @@
org.osgi.service.component,
org.apache.commons.logging.*,
org.wso2.carbon.user.core.*,
org.wso2.carbon.apimgt.api;version="${carbon.api.mgt.version.range}",
org.wso2.carbon.apimgt.api.model;version="${carbon.api.mgt.version.range}",
org.wso2.carbon.apimgt.impl;version="${carbon.api.mgt.version.range}",
org.wso2.carbon.user.api,
org.wso2.carbon.utils.multitenancy,
org.json.simple,
org.wso2.carbon.context,
org.wso2.carbon.base,
org.wso2.carbon.registry.core.*;resolution:=optional,
org.wso2.carbon.registry.indexing.*; version="${carbon.registry.imp.pkg.version.range}"
org.wso2.carbon.registry.indexing.*; version="${carbon.registry.imp.pkg.version.range}",
org.wso2.carbon.apimgt.integration.client.*,
org.wso2.carbon.apimgt.integration.generated.client.store.api,
org.wso2.carbon.apimgt.integration.generated.client.store.model,
feign
</Import-Package>
<Export-Package>
!org.wso2.carbon.apimgt.application.extension.internal,

@ -41,15 +41,7 @@ public interface APIManagementProviderService {
*/
ApiApplicationKey generateAndRetrieveApplicationKeys(String apiApplicationName, String tags[],
String keyType, String username, boolean isAllowedAllDomains,
String validityTime)
throws APIManagerException;
/**
* Register existing Oauth application as apim application.
*/
void registerExistingOAuthApplicationToAPIApplication(String jsonString, String applicationName, String clientId,
String username, boolean isAllowedAllDomains, String keyType,
String tags[]) throws APIManagerException;
String validityTime) throws APIManagerException;
/**
* Remove APIM Application.

@ -18,23 +18,23 @@
package org.wso2.carbon.apimgt.application.extension;
import feign.FeignException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONObject;
import org.wso2.carbon.apimgt.api.APIConsumer;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.model.*;
import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.apimgt.application.extension.internal.APIApplicationManagerExtensionDataHolder;
import org.wso2.carbon.apimgt.application.extension.util.APIManagerUtil;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.APIManagerFactory;
import org.wso2.carbon.apimgt.integration.client.store.*;
import org.wso2.carbon.apimgt.integration.generated.client.store.model.*;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This class represents an implementation of APIManagementProviderService.
@ -42,81 +42,23 @@ import java.util.Set;
public class APIManagementProviderServiceImpl implements APIManagementProviderService {
private static final Log log = LogFactory.getLog(APIManagementProviderServiceImpl.class);
/**
* {@inheritDoc}
*/
@Override
public void registerExistingOAuthApplicationToAPIApplication(String jsonString, String applicationName,
String clientId, String username,
boolean isAllowedAllDomains, String keyType,
String tags[]) throws APIManagerException {
try {
APIManagerUtil.loadTenantRegistry();
APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
if (apiConsumer != null) {
String groupId = getLoggedInUserGroupId(username, APIManagerUtil.getTenantDomain());
int applicationId = createApplication(apiConsumer, applicationName, username, groupId);
Subscriber subscriber = apiConsumer.getSubscriber(username);
if (subscriber == null) {
String tenantDomain = MultitenantUtils.getTenantDomain(username);
addSubscriber(username, "", groupId, APIManagerUtil.getTenantId(tenantDomain));
subscriber = apiConsumer.getSubscriber(username);
}
Application[] applications = apiConsumer.getApplications(subscriber, groupId);
Application application = null;
for (Application app : applications) {
if (app.getId() == applicationId) {
application = app;
}
}
if (application == null) {
throw new APIManagerException(
"Api application creation failed for " + applicationName + " to the user " + username);
}
OAuthApplicationInfo oAuthApp = application.getOAuthApp(keyType);
if (oAuthApp != null) {
if (oAuthApp.getClientId().equals(clientId)) {
if (tags != null && tags.length > 0) {
createApplicationAndSubscribeToAPIs(applicationName, tags, username);
}
return;
} else {
throw new APIManagerException("Api application already mapped to another OAuth App");
}
}
apiConsumer.mapExistingOAuthClient(jsonString, username, clientId, applicationName,
ApiApplicationConstants.DEFAULT_TOKEN_TYPE);
if (tags != null && tags.length > 0) {
createApplicationAndSubscribeToAPIs(applicationName, tags, username);
}
}
} catch (APIManagementException e) {
throw new APIManagerException(
"Failed registering the OAuth app [ clientId " + clientId + " ] with api manager application", e);
}
}
private static final String CONTENT_TYPE = "application/json";
private static final int MAX_API_PER_TAG = 200;
private static final String APP_TIER_TYPE = "application";
private static final Map<String, String> tiersMap = new HashMap<>();
private static final int MAX_ATTEMPTS = 10;
@Override
public void removeAPIApplication(String applicationName, String username) throws APIManagerException {
try {
APIManagerUtil.loadTenantRegistry();
APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
if (apiConsumer != null) {
String groupId = getLoggedInUserGroupId(username, APIManagerUtil.getTenantDomain());
Application[] applications = apiConsumer.getApplications(new Subscriber(username), groupId);
for (Application application : applications) {
if (application.getName().equals(applicationName)) {
apiConsumer.removeApplication(application);
break;
}
}
}
} catch (APIManagementException e) {
throw new APIManagerException(
"Failed to remove the application [ application name " + applicationName + " ]", e);
StoreClient storeClient = APIApplicationManagerExtensionDataHolder.getInstance().getIntegrationClientService()
.getStoreClient();
ApplicationList applicationList = storeClient.getApplications()
.applicationsGet("", applicationName, 1, 0, CONTENT_TYPE, null);
if (applicationList.getList() != null && applicationList.getList().size() > 0) {
ApplicationInfo applicationInfo = applicationList.getList().get(0);
storeClient.getIndividualApplication().applicationsApplicationIdDelete(applicationInfo.getApplicationId(),
null, null);
}
}
@ -124,203 +66,134 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
* {@inheritDoc}
*/
@Override
public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String apiApplicationName, String tags[],
public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String tags[],
String keyType, String username,
boolean isAllowedAllDomains, String validityTime)
throws APIManagerException {
StoreClient storeClient = APIApplicationManagerExtensionDataHolder.getInstance().getIntegrationClientService()
.getStoreClient();
//This is a fix to avoid race condition and trying to load tenant related tiers before invocation.
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext()
.getTenantDomain();
String tiersLoadedForTenant = tiersMap.get(tenantDomain);
if (tiersLoadedForTenant == null) {
int tierStatus = 0;
int attempts = 0;
do {
try {
APIManagerUtil.loadTenantRegistry();
APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
String groupId = getLoggedInUserGroupId(username, APIManagerUtil.getTenantDomain());
int applicationId = createApplicationAndSubscribeToAPIs(apiApplicationName, tags, username);
Application[] applications = apiConsumer.getApplications(apiConsumer.getSubscriber(username), groupId);
Application application = null;
for (Application app : applications) {
if (app.getId() == applicationId) {
application = app;
}
}
if (application == null) {
throw new APIManagerException(
"Api application creation failed for " + apiApplicationName + " to the user " + username);
}
OAuthApplicationInfo oAuthApp = application.getOAuthApp(keyType);
if (oAuthApp != null) {
ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
apiApplicationKey.setConsumerKey(oAuthApp.getClientId());
apiApplicationKey.setConsumerSecret(oAuthApp.getClientSecret());
return apiApplicationKey;
}
String[] allowedDomains = new String[1];
if (isAllowedAllDomains) {
allowedDomains[0] = ApiApplicationConstants.ALLOWED_DOMAINS;
} else {
allowedDomains[0] = APIManagerUtil.getTenantDomain();
}
String ownerJsonString = "{\"username\":\"" + username + "\"}";
Map<String, Object> keyDetails = apiConsumer.requestApprovalForApplicationRegistration(username,
apiApplicationName,
keyType, "",
allowedDomains,
validityTime,
"null",
groupId,
ownerJsonString);
ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
apiApplicationKey.setConsumerKey((String) keyDetails.get(APIConstants.FrontEndParameterNames
.CONSUMER_KEY));
apiApplicationKey.setConsumerSecret((String) keyDetails.get(
APIConstants.FrontEndParameterNames.CONSUMER_SECRET));
return apiApplicationKey;
} catch (APIManagementException e) {
throw new APIManagerException("Failed to register a api application : " + apiApplicationName, e);
}
}
private int createApplication(APIConsumer apiConsumer, String applicationName, String username, String groupId)
throws APIManagerException {
storeClient.getIndividualTier()
.tiersTierLevelTierNameGet(ApiApplicationConstants.DEFAULT_TIER, APP_TIER_TYPE,
tenantDomain, CONTENT_TYPE, null, null);
tiersMap.put(tenantDomain, "exist");
tierStatus = 200;
} catch (FeignException e) {
tierStatus = e.status();
attempts++;
try {
if (apiConsumer != null) {
if (apiConsumer.getSubscriber(username) == null) {
String tenantDomain = MultitenantUtils.getTenantDomain(username);
addSubscriber(username, "", groupId, APIManagerUtil.getTenantId(tenantDomain));
}
Application application = apiConsumer.getApplicationsByName(username, applicationName, groupId);
if (application == null) {
Subscriber subscriber = apiConsumer.getSubscriber(username);
application = new Application(applicationName, subscriber);
application.setTier(ApiApplicationConstants.DEFAULT_TIER);
application.setGroupId(groupId);
return apiConsumer.addApplication(application, username);
Thread.sleep(500);
} catch (InterruptedException ex) {
log.warn("Interrupted the waiting for tier availability.");
}
}
} while (tierStatus == 500 && attempts < MAX_ATTEMPTS);
}
ApplicationList applicationList = storeClient.getApplications()
.applicationsGet("", applicationName, 1, 0, CONTENT_TYPE, null);
Application application;
if (applicationList == null || applicationList.getList() == null || applicationList.getList().size() == 0) {
//create application;
application = new Application();
application.setName(applicationName);
application.setSubscriber(username);
application.setDescription("");
application.setThrottlingTier(ApiApplicationConstants.DEFAULT_TIER);
application.setGroupId("");
application = storeClient.getIndividualApplication().applicationsPost(application, CONTENT_TYPE);
} else {
if (log.isDebugEnabled()) {
log.debug("Application [" + applicationName + "] already exists for Subscriber [" + username +
"]");
}
return application.getId();
}
} else {
throw new APIManagerException("Failed to retrieve the api consumer for username" + username);
}
} catch (APIManagementException e) {
throw new APIManagerException("Failed to create application [name:" + applicationName + " , username:"
+ username + ", " + "groupId:" + groupId, e);
ApplicationInfo applicationInfo = applicationList.getList().get(0);
application = storeClient.getIndividualApplication()
.applicationsApplicationIdGet(applicationInfo.getApplicationId(), CONTENT_TYPE, null, null);
}
if (application == null) {
throw new APIManagerException (
"Api application creation failed for " + applicationName + " to the user " + username);
}
private void addSubscription(APIConsumer apiConsumer, APIIdentifier apiId, int applicationId, String username)
throws APIManagerException {
try {
if (apiConsumer != null) {
APIIdentifier apiIdentifier = new APIIdentifier(apiId.getProviderName(), apiId.getApiName(),
apiId.getVersion());
apiIdentifier.setTier(ApiApplicationConstants.DEFAULT_TIER);
apiConsumer.addSubscription(apiIdentifier, username, applicationId);
if (log.isDebugEnabled()) {
log.debug("Successfully created subscription for API : " + apiId + " from application : " +
applicationId);
}
} else {
throw new APIManagerException("API provider configured for the given API configuration is null. " +
"Thus, the API is not published");
SubscriptionList subscriptionList = storeClient.getSubscriptions().subscriptionsGet
(null, application.getApplicationId(), "", 0, 100, CONTENT_TYPE, null);
List<Subscription> needToSubscribe = new ArrayList<>();
// subscribe to apis.
if (tags != null && tags.length > 0) {
for (String tag: tags) {
APIList apiList = storeClient.getApis().apisGet(MAX_API_PER_TAG, 0, tenantDomain, "tag:" + tag
, CONTENT_TYPE, null);
if (apiList.getList() == null || apiList.getList().size() == 0) {
apiList = storeClient.getApis().apisGet(MAX_API_PER_TAG, 0
, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, "tag:" + tag, CONTENT_TYPE, null);
}
if (apiList.getList() != null && apiList.getList().size() > 0) {
for (APIInfo apiInfo : apiList.getList()) {
String id = apiInfo.getProvider().replace("@", "-AT-")
+ "-" + apiInfo.getName()+ "-" + apiInfo.getVersion();
boolean subscriptionExist = false;
if (subscriptionList.getList() != null && subscriptionList.getList().size() > 0) {
for (Subscription subs : subscriptionList.getList()) {
if (subs.getApiIdentifier().equals(id)) {
subscriptionExist = true;
break;
}
} catch (APIManagementException e) {
throw new APIManagerException("Failed to create subscription for api name : " + apiId.getApiName(), e);
}
}
if (!subscriptionExist) {
Subscription subscription = new Subscription();
//fix for APIMANAGER-5566 admin-AT-tenant1.com-Tenant1API1-1.0.0
private void addSubscriber(String subscriberName, String subscriberEmail, String groupId, int tenantId)
throws APIManagerException {
if (log.isDebugEnabled()) {
log.debug("Creating subscriber with name " + subscriberName);
subscription.setApiIdentifier(id);
subscription.setApplicationId(application.getApplicationId());
subscription.tier(ApiApplicationConstants.DEFAULT_TIER);
needToSubscribe.add(subscription);
}
try {
APIConsumer consumer = APIManagerFactory.getInstance().getAPIConsumer(subscriberName);
if (consumer != null) {
synchronized (consumer) {
if (consumer.getSubscriber(subscriberName) == null) {
consumer.addSubscriber(subscriberName, groupId);
if (log.isDebugEnabled()) {
log.debug("Successfully created subscriber with name : " + subscriberName +
" with groupID : " + groupId);
}
}
}
} else {
throw new APIManagerException("API provider configured for the given API configuration is null. " +
"Thus, the API is not published");
}
} catch (APIManagementException e) {
throw new APIManagerException("API provider configured for the given API configuration is null. " +
"Thus, the API is not published", e);
}
if (!needToSubscribe.isEmpty()) {
storeClient.getSubscriptionMultitpleApi().subscriptionsMultiplePost(needToSubscribe, CONTENT_TYPE);
}
//end of subscription
/**
* This method registers an api application and then subscribe the application to the api.
*
* @param apiApplicationName name of the application.
* @param tags are used subscribe the apis with the tag.
* @param username subscription is created for the user.
* @throws APIManagerException
*/
private int createApplicationAndSubscribeToAPIs(String apiApplicationName, String tags[], String username)
throws APIManagerException {
try {
APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
String groupId = getLoggedInUserGroupId(username, APIManagerUtil.getTenantDomain());
int applicationId = createApplication(apiConsumer, apiApplicationName, username, groupId);
Subscriber subscriber = apiConsumer.getSubscriber(username);
Set<API> userVisibleAPIs = null;
for (String tag : tags) {
Set<API> tagAPIs = apiConsumer.getAPIsWithTag(tag, APIManagerUtil.getTenantDomain());
if (userVisibleAPIs == null) {
userVisibleAPIs = tagAPIs;
} else {
userVisibleAPIs.addAll(tagAPIs);
}
}
if (userVisibleAPIs != null) {
Set<SubscribedAPI> subscribedAPIs = apiConsumer.getSubscribedAPIs(subscriber, apiApplicationName,
groupId);
for (API userVisibleAPI : userVisibleAPIs) {
APIIdentifier apiIdentifier = userVisibleAPI.getId();
boolean isSubscribed = false;
if (subscribedAPIs != null) {
for (SubscribedAPI subscribedAPI : subscribedAPIs) {
if (subscribedAPI.getApiId().equals(apiIdentifier)) {
isSubscribed = true;
}
}
}
if (!isSubscribed) {
addSubscription(apiConsumer, apiIdentifier, applicationId, username);
}
}
List<ApplicationKey> applicationKeys = application.getKeys();
if (applicationKeys != null) {
for (ApplicationKey applicationKey : applicationKeys) {
if (keyType.equals(applicationKey.getKeyType().toString())) {
ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey());
apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret());
return apiApplicationKey;
}
return applicationId;
} catch (APIManagementException e) {
throw new APIManagerException("Failed to fetch device apis information for the user " + username, e);
}
}
private String getLoggedInUserGroupId(String username, String tenantDomain) throws APIManagerException {
JSONObject loginInfoJsonObj = new JSONObject();
try {
APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
loginInfoJsonObj.put("user", username);
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
loginInfoJsonObj.put("isSuperTenant", true);
ApplicationKeyGenerateRequest applicationKeyGenerateRequest = new ApplicationKeyGenerateRequest();
List<String> allowedDomains = new ArrayList<>();
if (isAllowedAllDomains) {
allowedDomains.add(ApiApplicationConstants.ALLOWED_DOMAINS);
} else {
loginInfoJsonObj.put("isSuperTenant", false);
}
String loginInfoString = loginInfoJsonObj.toString();
return apiConsumer.getGroupIds(loginInfoString);
} catch (APIManagementException e) {
throw new APIManagerException("Unable to get groupIds of user " + username, e);
allowedDomains.add(APIManagerUtil.getTenantDomain());
}
applicationKeyGenerateRequest.setAccessAllowDomains(allowedDomains);
applicationKeyGenerateRequest.setCallbackUrl("");
applicationKeyGenerateRequest.setKeyType(ApplicationKeyGenerateRequest.KeyTypeEnum.PRODUCTION);
applicationKeyGenerateRequest.setValidityTime(validityTime);
ApplicationKey applicationKey = storeClient.getIndividualApplication().applicationsGenerateKeysPost(
application.getApplicationId(), applicationKeyGenerateRequest, CONTENT_TYPE, null, null);
ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey());
apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret());
return apiApplicationKey;
}
}

@ -18,6 +18,7 @@
package org.wso2.carbon.apimgt.application.extension.internal;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService;
import org.wso2.carbon.registry.core.service.TenantRegistryLoader;
import org.wso2.carbon.registry.indexing.service.TenantIndexingLoader;
import org.wso2.carbon.user.core.service.RealmService;
@ -30,6 +31,7 @@ public class APIApplicationManagerExtensionDataHolder {
private TenantManager tenantManager;
private TenantRegistryLoader tenantRegistryLoader;
private TenantIndexingLoader indexLoader;
private IntegrationClientService integrationClientService;
private APIApplicationManagerExtensionDataHolder() {
}
@ -86,4 +88,13 @@ public class APIApplicationManagerExtensionDataHolder {
public TenantIndexingLoader getIndexLoaderService(){
return indexLoader;
}
public IntegrationClientService getIntegrationClientService() {
return integrationClientService;
}
public void setIntegrationClientService(
IntegrationClientService integrationClientService) {
this.integrationClientService = integrationClientService;
}
}

@ -23,6 +23,7 @@ import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderServiceImpl;
import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService;
import org.wso2.carbon.registry.core.service.TenantRegistryLoader;
import org.wso2.carbon.registry.indexing.service.TenantIndexingLoader;
import org.wso2.carbon.user.core.service.RealmService;
@ -48,6 +49,12 @@ import org.wso2.carbon.user.core.service.RealmService;
* policy="dynamic"
* bind="setRealmService"
* unbind="unsetRealmService"
* @scr.reference name="integration.client.service"
* interface="org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService"
* cardinality="1..1"
* policy="dynamic"
* bind="setIntegrationClientService"
* unbind="unsetIntegrationClientService"
*/
public class APIApplicationManagerExtensionServiceComponent {
@ -86,6 +93,17 @@ public class APIApplicationManagerExtensionServiceComponent {
APIApplicationManagerExtensionDataHolder.getInstance().setIndexLoaderService(null);
}
protected void setIntegrationClientService(IntegrationClientService integrationClientService) {
if (integrationClientService != null && log.isDebugEnabled()) {
log.debug("integrationClientService initialized");
}
APIApplicationManagerExtensionDataHolder.getInstance().setIntegrationClientService(integrationClientService);
}
protected void unsetIntegrationClientService(IntegrationClientService integrationClientService) {
APIApplicationManagerExtensionDataHolder.getInstance().setIntegrationClientService(null);
}
/**
* Sets Realm Service.
*

@ -21,13 +21,13 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.handlers</artifactId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>WSO2 Carbon - API Security Handler Component</name>
<description>WSO2 Carbon - API Management Security Handler Module</description>

@ -0,0 +1,147 @@
<!-- ~ 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. -->
<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>2.0.37-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.integration.client</artifactId>
<version>2.0.37-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>WSO2 Carbon - API Management Integration Client</name>
<description>WSO2 Carbon - API Management Integration Client</description>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>1.4.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${project.version}</Bundle-Version>
<Bundle-Description>APIM Integration</Bundle-Description>
<Private-Package>org.wso2.carbon.apimgt.integration.client.internal</Private-Package>
<Export-Package>
org.wso2.carbon.apimgt.integration.client.*,
!org.wso2.carbon.apimgt.integration.client.internal
</Export-Package>
<Import-Package>
org.osgi.framework,
org.osgi.service.component,
feign,
feign.codec,
feign.auth,
feign.gson,
feign.slf4j,
org.wso2.carbon.apimgt.integration.generated.client.publisher.api,
org.wso2.carbon.apimgt.integration.generated.client.store.api,
javax.xml.bind,
javax.xml.bind.annotation,
javax.xml.parsers;resolution:=optional,
org.apache.commons.logging,
org.w3c.dom,
org.wso2.carbon.context,
org.wso2.carbon.identity.jwt.client.*,
org.wso2.carbon.user.api,
org.wso2.carbon.utils,
com.fasterxml.jackson.annotation,
io.swagger.annotations,
org.wso2.carbon.core.util,
javax.xml,
org.wso2.carbon.base,
javax.net.ssl,
</Import-Package>
<Embed-Dependency>
jsr311-api,
feign-jaxrs
</Embed-Dependency>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-jackson</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-gson</artifactId>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.integration.generated.client</artifactId>
</dependency>
</dependencies>
</project>

@ -0,0 +1,45 @@
/*
* 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 feign.RequestInterceptor;
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 StoreClient storeClient;
private static PublisherClient publisherClient;
public IntegrationClientServiceImpl() {
RequestInterceptor oAuthRequestInterceptor = new OAuthRequestInterceptor();
storeClient = new StoreClient(oAuthRequestInterceptor);
publisherClient = new PublisherClient(oAuthRequestInterceptor);
}
@Override
public StoreClient getStoreClient() {
return storeClient;
}
@Override
public PublisherClient getPublisherClient() {
return publisherClient;
}
}

@ -0,0 +1,118 @@
/*
* 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.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 org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import java.util.HashMap;
import java.util.Map;
/**
* 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 static OAuthApplication oAuthApplication;
private static Map<String, AccessTokenInfo> tenantUserTokenMap = new HashMap<>();
private static final Log log = LogFactory.getLog(OAuthRequestInterceptor.class);
/**
* Creates an interceptor that authenticates all requests.
*/
public OAuthRequestInterceptor() {
String username = APIMConfigReader.getInstance().getConfig().getUsername();
String password = APIMConfigReader.getInstance().getConfig().getPassword();
dcrClient = Feign.builder().client(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(APIMConfigReader.getInstance().getConfig().getUsername());
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().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);
}
}
}

@ -0,0 +1,90 @@
/*
* 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;
}
}

@ -0,0 +1,94 @@
/*
* 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(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;
}
}

@ -0,0 +1,58 @@
/*
* 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;
}
}

@ -0,0 +1,58 @@
/*
* 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;
}
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;
}
}

@ -0,0 +1,78 @@
/*
* 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);
}
}

@ -0,0 +1,45 @@
/*
* 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 org.wso2.carbon.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;
}
}

@ -0,0 +1,77 @@
/*
* 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.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
/**
* @scr.component name="org.wso2.carbon.api.integration.client" immediate="true"
* @scr.reference name="api.integration.client.service"
* interface="org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService"
* cardinality="1..1"
* policy="dynamic"
* bind="setJWTClientManagerService"
* unbind="unsetJWTClientManagerService"
*/
public class APIIntegrationClientServiceComponent {
private static Log log = LogFactory.getLog(APIIntegrationClientServiceComponent.class);
protected void activate(ComponentContext componentContext) {
try {
if (log.isDebugEnabled()) {
log.debug("Initializing apimgt client bundle");
}
/* Initializing webapp publisher configuration */
APIMConfigReader.init();
BundleContext bundleContext = componentContext.getBundleContext();
bundleContext.registerService(IntegrationClientService.class.getName(), new IntegrationClientServiceImpl(), null);
if (log.isDebugEnabled()) {
log.debug("apimgt client bundle has been successfully initialized");
}
} catch (Throwable e) {
log.error("Error occurred while initializing apimgt client bundle", e);
}
}
protected void deactivate(ComponentContext componentContext) {
//do nothing
}
protected void setJWTClientManagerService(JWTClientManagerService jwtClientManagerService) {
if (jwtClientManagerService != null) {
log.debug("jwtClientManagerService service is initialized");
}
APIIntegrationClientDataHolder.getInstance().setJwtClientManagerService(jwtClientManagerService);
}
protected void unsetJWTClientManagerService(JWTClientManagerService jwtClientManagerService) {
APIIntegrationClientDataHolder.getInstance().setJwtClientManagerService(null);
}
}

@ -0,0 +1,96 @@
/*
* 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();
}
}

@ -16,17 +16,21 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.oauth.extensions.handlers.grant;
package org.wso2.carbon.apimgt.integration.client.model;
import org.wso2.carbon.device.mgt.oauth.extensions.OAuthExtUtils;
import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
@SuppressWarnings("unused")
public class ExtendedPasswordGrantHandler extends org.wso2.carbon.apimgt.keymgt.handlers.ExtendedPasswordGrantHandler {
/**
* DCR Rest resource.
*/
@Path("/")
public interface DCRClient {
@Override
public boolean validateScope(OAuthTokenReqMessageContext tokReqMsgCtx) {
return OAuthExtUtils.setScopes(tokReqMsgCtx);
}
// DCR APIs
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
OAuthApplication register(ClientProfile registrationProfile);
}

@ -0,0 +1,103 @@
/*
* 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();
}
}

@ -0,0 +1,88 @@
/*
* 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.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 APIsApi api = null;
private APIDocumentApi document = null;
private ApplicationsApi application = null;
private EnvironmentsApi environments = null;
private SubscriptionsApi subscriptions = null;
private TiersApi tiers = null;
/**
* PublisherClient constructor - Initialize a PublisherClient instance
*
*/
public PublisherClient(RequestInterceptor requestInterceptor) {
Feign.Builder builder = Feign.builder().client(
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(APIsApi.class, basePath);
document = builder.target(APIDocumentApi.class, basePath);
application = builder.target(ApplicationsApi.class, basePath);
environments = builder.target(EnvironmentsApi.class, basePath);
subscriptions = builder.target(SubscriptionsApi.class, basePath);
tiers = builder.target(TiersApi.class, basePath);
}
public APIsApi getApi() {
return api;
}
public APIDocumentApi getDocument() {
return document;
}
public ApplicationsApi getApplication() {
return application;
}
public EnvironmentsApi getEnvironments() {
return environments;
}
public SubscriptionsApi getSubscriptions() {
return subscriptions;
}
public TiersApi getTiers() {
return tiers;
}
}

@ -0,0 +1,41 @@
/*
* 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 {
/**
*
* @return API Store Client.
*/
StoreClient getStoreClient();
/**
*
* @return API Publisher Client.
*/
PublisherClient getPublisherClient();
}

@ -0,0 +1,109 @@
/*
* 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.RequestInterceptor;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
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;
/**
* 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(
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);
tiers = builder.target(ThrottlingTierCollectionApi.class, basePath);
individualTier = builder.target(ThrottlingTierIndividualApi.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;
}
}

@ -0,0 +1,89 @@
/*
* 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 feign.Client;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import feign.Logger;
import feign.Request;
import feign.Response;
import org.apache.commons.logging.Log;
public class Utils {
//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 Client getSSLClient() {
return new Client.Default(getTrustedSSLSocketFactory(), new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
}
private static SSLSocketFactory getTrustedSSLSocketFactory() {
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;
}
}
}

@ -0,0 +1,206 @@
<!-- ~ 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. -->
<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>2.0.37-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.integration.generated.client</artifactId>
<version>2.0.37-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>WSO2 Carbon - API Management Integration Generated Client</name>
<description>WSO2 Carbon - API Management Integration Client</description>
<url>http://wso2.org</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>
<version>1.5.2</version>
<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>

@ -22,13 +22,13 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>WSO2 Carbon - API Management Webapp Publisher</name>
<description>WSO2 Carbon - API Management Webapp Publisher</description>
@ -47,14 +47,6 @@
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.api</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.impl</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.tomcat</groupId>
<artifactId>tomcat</artifactId>
@ -111,6 +103,10 @@
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.integration.client</artifactId>
</dependency>
</dependencies>
@ -147,16 +143,26 @@
com.google.gson.*,
org.apache.catalina,
org.apache.catalina.core,
org.wso2.carbon.apimgt.api,
org.wso2.carbon.apimgt.api.model,
org.wso2.carbon.apimgt.impl,
org.apache.axis2.*;version="${axis2.osgi.version.range}",
org.wso2.carbon.core,
org.apache.commons.lang,
org.wso2.carbon.utils,
org.wso2.carbon.apimgt.annotations.*,
org.wso2.carbon.governance.lcm.util.*,
org.wso2.carbon.registry.core.*
org.wso2.carbon.registry.core.*,
io.swagger.annotations,
javax.net.ssl,
org.scannotation,
org.scannotation.archiveiterator,
org.w3c.dom,
org.wso2.carbon.apimgt.integration.client.*,
org.wso2.carbon.context,
org.wso2.carbon.core.util,
org.wso2.carbon.user.api,
org.wso2.carbon.user.core.*,
org.wso2.carbon.utils.multitenancy,
org.wso2.carbon.apimgt.integration.generated.client.publisher.api,
org.wso2.carbon.apimgt.integration.generated.client.publisher.model
</Import-Package>
<Embed-Dependency>
javax.ws.rs-api,

@ -18,17 +18,11 @@
*/
package org.wso2.carbon.apimgt.webapp.publisher;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIProvider;
import org.wso2.carbon.apimgt.api.model.URITemplate;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.APIManagerFactory;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import org.wso2.carbon.apimgt.webapp.publisher.dto.ApiScope;
import org.wso2.carbon.apimgt.webapp.publisher.dto.ApiUriTemplate;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import java.util.List;
import java.util.Set;
/**
@ -53,26 +47,16 @@ public class APIConfig {
private String name;
private String owner;
private String context;
private String contextTemplate;
private String endpoint;
private String version;
private String policy;
private String transports;
private APIProvider provider;
private boolean isSecured;
private Set<URITemplate> uriTemplates;
private List<String> tenants;
private Set<ApiUriTemplate> uriTemplates;
private boolean isSharedWithAllTenants;
private String tenantDomain;
private String[] tags;
public void init() throws APIManagementException {
try {
this.provider = APIManagerFactory.getInstance().getAPIProvider(owner);
} catch (APIManagementException e) {
throw new APIManagementException("Error occurred while initializing API provider", e);
}
}
private Set<ApiScope> scopes;
@XmlElement(name = "Policy", required = true)
public String getPolicy() {
@ -84,20 +68,6 @@ public class APIConfig {
this.policy = policy;
}
@XmlElement(name = "ContextTemplate", required = true)
public String getContextTemplate() {
return contextTemplate;
}
public void setContextTemplate(String contextTemplate) {
this.contextTemplate = contextTemplate;
}
@XmlTransient
public APIProvider getProvider() {
return provider;
}
@XmlElement(name = "Name", required = true)
public String getName() {
return name;
@ -168,12 +138,12 @@ public class APIConfig {
}
@XmlElement(name = "UriTemplates", required = false)
public Set<URITemplate> getUriTemplates() {
public Set<ApiUriTemplate> getUriTemplates() {
return uriTemplates;
}
@SuppressWarnings("unused")
public void setUriTemplates(Set<URITemplate> uriTemplates) {
public void setUriTemplates(Set<ApiUriTemplate> uriTemplates) {
this.uriTemplates = uriTemplates;
}
@ -206,4 +176,12 @@ public class APIConfig {
public void setTags(String[] tags) {
this.tags = tags;
}
public Set<ApiScope> getScopes() {
return scopes;
}
public void setScopes(Set<ApiScope> scopes) {
this.scopes = scopes;
}
}

@ -18,18 +18,12 @@
*/
package org.wso2.carbon.apimgt.webapp.publisher;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.FaultGatewaysException;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import java.util.List;
import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException;
/**
* This interface represents all methods related to API manipulation that's done as part of API-Management tasks.
*
* Note: Ideally, this has to come from the API-Management components. However, due to lack of clean APIs
* (as OSGi declarative services, etc) provided for API publishing and related tasks, this was introduced at the device
* management core implementation layer.
*/
public interface APIPublisherService {
@ -37,23 +31,8 @@ public interface APIPublisherService {
* This method registers an API within the underlying API-Management infrastructure.
*
* @param api An instance of the bean that passes metadata related to the API being published
* @throws APIManagementException Is thrown if some unexpected event occurs while publishing the API
*/
void publishAPI(API api) throws APIManagementException, FaultGatewaysException;
/**
* This method removes an API that's already published within the underlying API-Management infrastructure.
*
* @param id An instance of the bean that carries API identification related metadata
* @throws APIManagementException Is thrown if some unexpected event occurs while removing the API
* @throws APIManagerPublisherException Is thrown if some unexpected event occurs while publishing the API
*/
void removeAPI(APIIdentifier id) throws APIManagementException;
void publishAPI(APIConfig api) throws APIManagerPublisherException;
/**
* This method registers a collection of APIs within the underlying API-Management infrastructure.
*
* @param apis A list of the beans that passes metadata related to the APIs being published
* @throws APIManagementException Is thrown if some unexpected event occurs while publishing the APIs
*/
void publishAPIs(List<API> apis) throws APIManagementException, FaultGatewaysException;
}

@ -18,28 +18,14 @@
*/
package org.wso2.carbon.apimgt.webapp.publisher;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIProvider;
import org.wso2.carbon.apimgt.api.FaultGatewaysException;
import org.wso2.carbon.apimgt.api.model.*;
import org.wso2.carbon.apimgt.impl.APIManagerFactory;
import feign.FeignException;
import org.wso2.carbon.apimgt.integration.generated.client.publisher.model.*;
import org.wso2.carbon.apimgt.integration.client.publisher.PublisherClient;
import org.wso2.carbon.apimgt.webapp.publisher.config.WebappPublisherConfig;
import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException;
import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.governance.lcm.util.CommonUtil;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.xml.stream.XMLStreamException;
import java.io.FileNotFoundException;
import java.util.*;
/**
@ -47,176 +33,122 @@ import java.util.*;
* API publishing related operations.
*/
public class APIPublisherServiceImpl implements APIPublisherService {
private static final Log log = LogFactory.getLog(APIPublisherServiceImpl.class);
private static final String UNLIMITED_TIER = "Unlimited";
private static final String API_PUBLISH_ENVIRONMENT = "Production and Sandbox";
private static final String CONTENT_TYPE = "application/json";
private static final String PUBLISHED_STATUS = "PUBLISHED";
private static final String CREATED_STATUS = "CREATED";
private static final String PUBLISH_ACTION = "Publish";
@Override
public void publishAPI(final API api) throws APIManagementException, FaultGatewaysException {
String tenantDomain = MultitenantUtils.getTenantDomain(api.getApiOwner());
public void publishAPI(APIConfig apiConfig) throws APIManagerPublisherException {
String tenantDomain = MultitenantUtils.getTenantDomain(apiConfig.getOwner());
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(apiConfig.getOwner());
try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
// Below code snippet is added to load API Lifecycle in tenant mode.
RegistryService registryService = APIPublisherDataHolder.getInstance().getRegistryService();
CommonUtil.addDefaultLifecyclesIfNotAvailable(registryService.getConfigSystemRegistry(tenantId),
CommonUtil.getRootSystemRegistry(tenantId));
APIProvider provider = APIManagerFactory.getInstance().getAPIProvider(api.getApiOwner());
MultitenantUtils.getTenantDomain(api.getApiOwner());
processHttpVerbs(api);
if (provider != null) {
if (provider.isDuplicateContextTemplate(api.getContext())) {
throw new APIManagementException(
"Error occurred while adding the API. A duplicate API" +
" context already exists for " + api.getContext());
}
if (!provider.isAPIAvailable(api.getId())) {
provider.addAPI(api);
provider.changeLifeCycleStatus(api.getId(), PUBLISH_ACTION);
if (log.isDebugEnabled()) {
log.debug("Successfully published API '" + api.getId().getApiName() +
"' with context '" + api.getContext() + "' and version '"
+ api.getId().getVersion() + "'");
PublisherClient publisherClient = APIPublisherDataHolder.getInstance().getIntegrationClientService()
.getPublisherClient();
API api = getAPI(apiConfig);
APIList apiList = publisherClient.getApi().apisGet(100, 0, "name:" + api.getName(), CONTENT_TYPE, null);
if (!isExist(api, apiList)) {
api = publisherClient.getApi().apisPost(api, CONTENT_TYPE);
if (CREATED_STATUS.equals(api.getStatus())) {
publisherClient.getApi().apisChangeLifecyclePost(PUBLISH_ACTION, api.getId(), null, null, null);
}
} else {
if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) {
if (provider.getAPI(api.getId()).getStatus() == APIStatus.CREATED) {
provider.changeLifeCycleStatus(api.getId(), PUBLISH_ACTION);
for (APIInfo apiInfo : apiList.getList()) {
if (api.getName().equals(apiInfo.getName()) && api.getVersion().equals(apiInfo.getVersion())) {
api = publisherClient.getApi().apisApiIdPut(apiInfo.getId(), api, CONTENT_TYPE, null, null);
if (CREATED_STATUS.equals(api.getStatus())) {
publisherClient.getApi().apisChangeLifecyclePost(PUBLISH_ACTION, api.getId(), null, null,
null);
}
api.setStatus(APIStatus.PUBLISHED);
provider.updateAPI(api);
if (log.isDebugEnabled()) {
log.debug("An API already exists with the name '" + api.getId().getApiName() +
"', context '" + api.getContext() + "' and version '"
+ api.getId().getVersion() + "'. Thus, the API config is updated");
}
}
}
provider.saveSwagger20Definition(api.getId(), createSwaggerDefinition(api));
} else {
throw new APIManagementException("API provider configured for the given API configuration " +
"is null. Thus, the API is not published");
}
} catch (FileNotFoundException e) {
throw new APIManagementException("Failed to retrieve life cycle file ", e);
} catch (RegistryException e) {
throw new APIManagementException("Failed to access the registry ", e);
} catch (XMLStreamException e) {
throw new APIManagementException("Failed parsing the lifecycle xml.", e);
} catch (FeignException e) {
throw new APIManagerPublisherException(e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
private String createSwaggerDefinition(API api) {
Map<String, JsonObject> httpVerbsMap = new HashMap<>();
List<Scope> scopes = new ArrayList<>();
for (URITemplate uriTemplate : api.getUriTemplates()) {
JsonObject response = new JsonObject();
response.addProperty("200", "");
JsonObject responses = new JsonObject();
responses.add("responses", response);
JsonObject httpVerbs = httpVerbsMap.get(uriTemplate.getUriTemplate());
if (httpVerbs == null) {
httpVerbs = new JsonObject();
}
JsonObject httpVerb = new JsonObject();
httpVerb.add("responses", response);
httpVerb.addProperty("x-auth-type", "Application%20%26%20Application%20User");
httpVerb.addProperty("x-throttling-tier", "Unlimited");
if (uriTemplate.getScope() != null) {
httpVerb.addProperty("x-scope", uriTemplate.getScope().getName());
scopes.add(uriTemplate.getScope());
}
httpVerbs.add(uriTemplate.getHTTPVerb().toLowerCase(), httpVerb);
httpVerbsMap.put(uriTemplate.getUriTemplate(), httpVerbs);
}
Iterator it = httpVerbsMap.entrySet().iterator();
JsonObject paths = new JsonObject();
while (it.hasNext()) {
Map.Entry<String, JsonObject> pair = (Map.Entry) it.next();
paths.add(pair.getKey(), pair.getValue());
it.remove();
}
JsonObject info = new JsonObject();
info.addProperty("title", api.getId().getApiName());
info.addProperty("version", api.getId().getVersion());
JsonObject swaggerDefinition = new JsonObject();
swaggerDefinition.add("paths", paths);
swaggerDefinition.addProperty("swagger", "2.0");
swaggerDefinition.add("info", info);
// adding scopes to swagger definition
if (!api.getScopes().isEmpty()) {
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(api.getScopes(), new TypeToken<Set<Scope>>() {
}.getType());
if (element != null) {
JsonArray apiScopes = element.getAsJsonArray();
JsonObject apim = new JsonObject();
apim.add("x-wso2-scopes", apiScopes);
JsonObject wso2Security = new JsonObject();
wso2Security.add("apim", apim);
swaggerDefinition.add("x-wso2-security", wso2Security);
private boolean isExist(API api, APIList apiList) {
if (apiList == null || apiList.getList() == null || apiList.getList().size() == 0) {
return false;
}
for (APIInfo existingApi : apiList.getList()) {
if (existingApi.getName().equals(api.getName()) && existingApi.getVersion().equals(api.getVersion())) {
return true;
}
if (log.isDebugEnabled()) {
log.debug("API swagger definition: " + swaggerDefinition.toString());
}
return swaggerDefinition.toString();
return false;
}
/**
* Sometimes the httpVerb string attribute is not existing in
* the list of httpVerbs attribute of uriTemplate. In such cases when creating the api in the
* synapse configuration, it doesn't have http methods correctly assigned for the resources.
* Therefore this method takes care of such inconsistency issue.
*
* @param api The actual API model object
*/
private void processHttpVerbs(API api) {
for (URITemplate uriTemplate : api.getUriTemplates()) {
String httpVerbString = uriTemplate.getHTTPVerb();
if (httpVerbString != null && !httpVerbString.isEmpty()) {
uriTemplate.setHttpVerbs(httpVerbString);
}
}
}
private API getAPI(APIConfig config) {
@Override
public void removeAPI(APIIdentifier id) throws APIManagementException {
if (log.isDebugEnabled()) {
log.debug("Removing API '" + id.getApiName() + "'");
}
APIProvider provider = APIManagerFactory.getInstance().getAPIProvider(id.getProviderName());
provider.deleteAPI(id);
if (log.isDebugEnabled()) {
log.debug("API '" + id.getApiName() + "' has been successfully removed");
}
}
API api = new API();
api.setName(config.getName());
api.setDescription("");
@Override
public void publishAPIs(List<API> apis) throws APIManagementException, FaultGatewaysException {
if (log.isDebugEnabled()) {
log.debug("Publishing a batch of APIs");
}
for (API api : apis) {
try {
this.publishAPI(api);
} catch (APIManagementException e) {
log.error("Error occurred while publishing API '" + api.getId().getApiName() + "'", e);
}
}
if (log.isDebugEnabled()) {
log.debug("End of publishing the batch of APIs");
}
String context = config.getContext();
context = context.startsWith("/") ? context : ("/" + context);
api.setContext(context);
api.setVersion(config.getVersion());
api.setProvider(config.getOwner());
api.setApiDefinition(APIPublisherUtil.getSwaggerDefinition(config));
api.setWsdlUri(null);
api.setStatus(PUBLISHED_STATUS);
api.setResponseCaching("DISABLED");
api.setDestinationStatsEnabled("false");
api.isDefaultVersion(true);
List<String> transport = new ArrayList<>();
transport.add("https");
transport.add("http");
api.transport(transport);
api.setTags(Arrays.asList(config.getTags()));
api.addTiersItem(UNLIMITED_TIER);
api.setGatewayEnvironments(API_PUBLISH_ENVIRONMENT);
if (config.isSharedWithAllTenants()) {
api.setSubscriptionAvailability(API.SubscriptionAvailabilityEnum.all_tenants);
api.setVisibility(API.VisibilityEnum.PUBLIC);
} else {
api.setSubscriptionAvailability(API.SubscriptionAvailabilityEnum.current_tenant);
api.setVisibility(API.VisibilityEnum.PRIVATE);
}
String endpointConfig = "{\"production_endpoints\":{\"url\":\"" + config.getEndpoint() +
"\",\"config\":null},\"implementation_status\":\"managed\",\"endpoint_type\":\"http\"}";
api.setEndpointConfig(endpointConfig);
APICorsConfiguration apiCorsConfiguration = new APICorsConfiguration();
List<String> accessControlAllowOrigins = new ArrayList<>();
accessControlAllowOrigins.add("*");
apiCorsConfiguration.setAccessControlAllowOrigins(accessControlAllowOrigins);
List<String> accessControlAllowHeaders = new ArrayList<>();
accessControlAllowHeaders.add("authorization");
accessControlAllowHeaders.add("Access-Control-Allow-Origin");
accessControlAllowHeaders.add("Content-Type");
accessControlAllowHeaders.add("SOAPAction");
apiCorsConfiguration.setAccessControlAllowHeaders(accessControlAllowHeaders);
List<String> accessControlAllowMethods = new ArrayList<>();
accessControlAllowMethods.add("GET");
accessControlAllowMethods.add("PUT");
accessControlAllowMethods.add("DELETE");
accessControlAllowMethods.add("POST");
accessControlAllowMethods.add("PATCH");
accessControlAllowMethods.add("OPTIONS");
apiCorsConfiguration.setAccessControlAllowMethods(accessControlAllowMethods);
apiCorsConfiguration.setAccessControlAllowCredentials(false);
apiCorsConfiguration.corsConfigurationEnabled(false);
api.setCorsConfiguration(apiCorsConfiguration);
return api;
}
}

@ -21,7 +21,7 @@ package org.wso2.carbon.apimgt.webapp.publisher;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException;
import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import org.wso2.carbon.core.ServerStartupObserver;
@ -33,8 +33,8 @@ public class APIPublisherStartupHandler implements ServerStartupObserver {
private static int retryTime = 2000;
private static final int CONNECTION_RETRY_FACTOR = 2;
private static final int MAX_RETRY_COUNT = 5;
private static Stack<API> failedAPIsStack = new Stack<>();
private static Stack<API> currentAPIsStack;
private static Stack<APIConfig> failedAPIsStack = new Stack<>();
private static Stack<APIConfig> currentAPIsStack;
private APIPublisherService publisher;
@ -64,7 +64,7 @@ public class APIPublisherStartupHandler implements ServerStartupObserver {
} catch (InterruptedException te) {
//do nothing.
}
Stack<API> failedApis;
Stack<APIConfig> failedApis;
if (!APIPublisherDataHolder.getInstance().getUnpublishedApis().isEmpty()) {
publishAPIs(currentAPIsStack, failedAPIsStack);
failedApis = failedAPIsStack;
@ -77,8 +77,8 @@ public class APIPublisherStartupHandler implements ServerStartupObserver {
StringBuilder error = new StringBuilder();
error.append("Error occurred while publishing API ['");
while (!failedApis.isEmpty()) {
API api = failedApis.pop();
error.append(api.getId().getApiName() + ",");
APIConfig api = failedApis.pop();
error.append(api.getName() + ",");
}
error.append("']");
log.error(error.toString());
@ -90,12 +90,13 @@ public class APIPublisherStartupHandler implements ServerStartupObserver {
t.start();
}
private void publishAPIs(Stack<API> apis, Stack<API> failedStack) {
private void publishAPIs(Stack<APIConfig> apis, Stack<APIConfig> failedStack) {
while (!apis.isEmpty()) {
API api = apis.pop();
APIConfig api = apis.pop();
try {
publisher.publishAPI(api);
} catch (Exception e) {
} catch (APIManagerPublisherException e) {
log.error("failed to publish api.", e);
failedStack.push(api);
}
}

@ -18,22 +18,24 @@
package org.wso2.carbon.apimgt.webapp.publisher;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIProvider;
import org.wso2.carbon.apimgt.api.model.*;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResource;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResourceConfiguration;
import org.wso2.carbon.apimgt.webapp.publisher.config.WebappPublisherConfig;
import org.wso2.carbon.apimgt.webapp.publisher.dto.ApiScope;
import org.wso2.carbon.apimgt.webapp.publisher.dto.ApiUriTemplate;
import org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util.AnnotationProcessor;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.util.Utils;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.servlet.ServletContext;
import java.util.*;
@ -41,7 +43,6 @@ import java.util.*;
public class APIPublisherUtil {
public static final String API_VERSION_PARAM = "{version}";
public static final String API_PUBLISH_ENVIRONMENT = "Production and Sandbox";
private static final Log log = LogFactory.getLog(APIPublisherUtil.class);
private static final String DEFAULT_API_VERSION = "1.0.0";
private static final String API_CONFIG_DEFAULT_VERSION = "1.0.0";
@ -55,101 +56,6 @@ public class APIPublisherUtil {
private static final String NON_SECURED_RESOURCES = "nonSecuredEndPoints";
private static final String AUTH_TYPE_NON_SECURED = "None";
public static API getAPI(APIConfig config) throws APIManagementException {
APIProvider provider = config.getProvider();
String apiVersion = config.getVersion();
APIIdentifier id = new APIIdentifier(replaceEmailDomain(config.getOwner()), config.getName(), apiVersion);
API api = new API(id);
api.setApiOwner(config.getOwner());
String context = config.getContext();
context = context.startsWith("/") ? context : ("/" + context);
String providerDomain = config.getTenantDomain();
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(providerDomain)) {
//Create tenant aware context for API
context = "/t/" + providerDomain + context;
}
// This is to support the new Pluggable version strategy
// if the context does not contain any {version} segment, we use the default version strategy.
context = checkAndSetVersionParam(context);
api.setContextTemplate(context);
context = updateContextWithVersion(config.getVersion(), context);
api.setContext(context);
api.setUrl(config.getEndpoint());
api.addAvailableTiers(provider.getTiers());
api.setEndpointSecured(false);
api.setStatus(APIStatus.CREATED);
api.setTransports(config.getTransports());
api.setApiLevelPolicy(config.getPolicy());
api.setContextTemplate(config.getContextTemplate());
Set<String> environments = new HashSet<>();
environments.add(API_PUBLISH_ENVIRONMENT);
api.setEnvironments(environments);
Set<Tier> tiers = new HashSet<>();
tiers.add(new Tier(APIConstants.UNLIMITED_TIER));
api.addAvailableTiers(tiers);
if (config.isSharedWithAllTenants()) {
api.setSubscriptionAvailability(APIConstants.SUBSCRIPTION_TO_ALL_TENANTS);
api.setVisibility(APIConstants.API_GLOBAL_VISIBILITY);
} else {
api.setSubscriptionAvailability(APIConstants.SUBSCRIPTION_TO_CURRENT_TENANT);
api.setVisibility(APIConstants.API_PRIVATE_VISIBILITY);
}
api.setResponseCache(APIConstants.DISABLED);
String endpointConfig = "{\"production_endpoints\":{\"url\":\"" + config.getEndpoint() +
"\",\"config\":null},\"implementation_status\":\"managed\",\"endpoint_type\":\"http\"}";
api.setEndpointConfig(endpointConfig);
if ("".equals(id.getVersion()) || (DEFAULT_API_VERSION.equals(id.getVersion()))) {
api.setAsDefaultVersion(Boolean.TRUE);
api.setAsPublishedDefaultVersion(Boolean.TRUE);
}
if (config.getTags() != null && config.getTags().length > 0) {
Set<String> tags = new HashSet<>(Arrays.asList(config.getTags()));
api.addTags(tags);
}
// adding scopes to the api
Set<URITemplate> uriTemplates = config.getUriTemplates();
Map<String, Scope> apiScopes = new HashMap<>();
if (uriTemplates != null) {
// this creates distinct scopes list
for (URITemplate template : uriTemplates) {
Scope scope = template.getScope();
if (scope != null) {
if (apiScopes.get(scope.getKey()) == null) {
apiScopes.put(scope.getKey(), scope);
}
}
}
Set<Scope> scopes = new HashSet<>(apiScopes.values());
// set current scopes to API
api.setScopes(scopes);
// this has to be done because of the use of pass by reference
// where same object reference of scope should be available for both
// api scope and uri template scope
for (Scope scope : scopes) {
for (URITemplate template : uriTemplates) {
if (template.getScope() != null && scope.getKey().equals(template.getScope().getKey())) {
template.setScope(scope);
}
}
}
api.setUriTemplates(uriTemplates);
}
api.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
return api;
}
public static String getServerBaseUrl() {
WebappPublisherConfig webappPublisherConfig = WebappPublisherConfig.getInstance();
return Utils.replaceSystemProperty(webappPublisherConfig.getHost());
@ -159,39 +65,6 @@ public class APIPublisherUtil {
return getServerBaseUrl() + context;
}
/**
* When an input is having '@',replace it with '-AT-'
* [This is required to persist API data in registry,as registry paths don't allow '@' sign.]
*
* @param input inputString
* @return String modifiedString
*/
private static String replaceEmailDomain(String input) {
if (input != null && input.contains(APIConstants.EMAIL_DOMAIN_SEPARATOR)) {
input = input.replace(APIConstants.EMAIL_DOMAIN_SEPARATOR, APIConstants.EMAIL_DOMAIN_SEPARATOR_REPLACEMENT);
}
return input;
}
private static String updateContextWithVersion(String version, String context) {
// This condition should not be true for any occasion but we keep it so that there are no loopholes in
// the flow.
context = context.replace(API_VERSION_PARAM, version);
return context;
}
private static String checkAndSetVersionParam(String context) {
// This is to support the new Pluggable version strategy
// if the context does not contain any {version} segment, we use the default version strategy.
if (!context.contains(API_VERSION_PARAM)) {
if (!context.endsWith("/")) {
context = context + "/";
}
context = context + API_VERSION_PARAM;
}
return context;
}
/**
* Build the API Configuration to be passed to APIM, from a given list of URL templates
*
@ -245,11 +118,6 @@ public class APIPublisherUtil {
tenantDomain = (tenantDomain != null && !tenantDomain.isEmpty()) ? tenantDomain :
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
apiConfig.setTenantDomain(tenantDomain);
String contextTemplate = context + "/" + APIConstants.VERSION_PLACEHOLDER;
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
contextTemplate = context + "/t/" + tenantDomain + "/" + APIConstants.VERSION_PLACEHOLDER;
}
apiConfig.setContextTemplate(contextTemplate);
String endpoint = servletContext.getInitParameter(PARAM_MANAGED_API_ENDPOINT);
if (endpoint == null || endpoint.isEmpty()) {
@ -292,17 +160,33 @@ public class APIPublisherUtil {
}
apiConfig.setSharedWithAllTenants(isSharedWithAllTenants);
Set<URITemplate> uriTemplates = new LinkedHashSet<>();
Set<ApiUriTemplate> uriTemplates = new LinkedHashSet<>();
for (APIResource apiResource : apiDef.getResources()) {
URITemplate template = new URITemplate();
ApiUriTemplate template = new ApiUriTemplate();
template.setAuthType(apiResource.getAuthType());
template.setHTTPVerb(apiResource.getHttpVerb());
template.setHttpVerb(apiResource.getHttpVerb());
template.setResourceURI(apiResource.getUri());
template.setUriTemplate(apiResource.getUriTemplate());
template.setScope(apiResource.getScope());
uriTemplates.add(template);
}
apiConfig.setUriTemplates(uriTemplates);
// adding scopes to the api
Map<String, ApiScope> apiScopes = new HashMap<>();
if (uriTemplates != null) {
// this creates distinct scopes list
for (ApiUriTemplate template : uriTemplates) {
ApiScope scope = template.getScope();
if (scope != null) {
if (apiScopes.get(scope.getKey()) == null) {
apiScopes.put(scope.getKey(), scope);
}
}
}
Set<ApiScope> scopes = new HashSet<>(apiScopes.values());
// set current scopes to API
apiConfig.setScopes(scopes);
}
String policy = servletContext.getInitParameter(PARAM_MANAGED_API_POLICY);
if (policy == null || policy.isEmpty()) {
@ -317,6 +201,70 @@ public class APIPublisherUtil {
return apiConfig;
}
public static String getSwaggerDefinition(APIConfig apiConfig) {
Map<String, JsonObject> httpVerbsMap = new HashMap<>();
List<ApiScope> scopes = new ArrayList<>();
for (ApiUriTemplate uriTemplate : apiConfig.getUriTemplates()) {
JsonObject response = new JsonObject();
response.addProperty("200", "");
JsonObject responses = new JsonObject();
responses.add("responses", response);
JsonObject httpVerbs = httpVerbsMap.get(uriTemplate.getUriTemplate());
if (httpVerbs == null) {
httpVerbs = new JsonObject();
}
JsonObject httpVerb = new JsonObject();
httpVerb.add("responses", response);
httpVerb.addProperty("x-auth-type", uriTemplate.getAuthType());
httpVerb.addProperty("x-throttling-tier", "Unlimited");
if (uriTemplate.getScope() != null) {
httpVerb.addProperty("x-scope", uriTemplate.getScope().getKey());
scopes.add(uriTemplate.getScope());
}
httpVerbs.add(uriTemplate.getHttpVerb().toLowerCase(), httpVerb);
httpVerbsMap.put(uriTemplate.getUriTemplate(), httpVerbs);
}
Iterator it = httpVerbsMap.entrySet().iterator();
JsonObject paths = new JsonObject();
while (it.hasNext()) {
Map.Entry<String, JsonObject> pair = (Map.Entry) it.next();
paths.add(pair.getKey(), pair.getValue());
it.remove();
}
JsonObject info = new JsonObject();
info.addProperty("title", apiConfig.getName());
info.addProperty("version", apiConfig.getVersion());
JsonObject swaggerDefinition = new JsonObject();
swaggerDefinition.add("paths", paths);
swaggerDefinition.addProperty("swagger", "2.0");
swaggerDefinition.add("info", info);
// adding scopes to swagger definition
if (!apiConfig.getScopes().isEmpty()) {
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(apiConfig.getScopes(), new TypeToken<Set<Scope>>() {
}.getType());
if (element != null) {
JsonArray apiScopes = element.getAsJsonArray();
JsonObject apim = new JsonObject();
apim.add("x-wso2-scopes", apiScopes);
JsonObject wso2Security = new JsonObject();
wso2Security.add("apim", apim);
swaggerDefinition.add("x-wso2-security", wso2Security);
}
}
if (log.isDebugEnabled()) {
log.debug("API swagger definition: " + swaggerDefinition.toString());
}
return swaggerDefinition.toString();
}
public static void setResourceAuthTypes(ServletContext servletContext, APIConfig apiConfig) {
List<String> resourcesList = null;
@ -324,9 +272,9 @@ public class APIPublisherUtil {
if(null != nonSecuredResources){
resourcesList = Arrays.asList(nonSecuredResources.split(","));
}
Set<URITemplate> templates = apiConfig.getUriTemplates();
Set<ApiUriTemplate> templates = apiConfig.getUriTemplates();
if(null != resourcesList) {
for (URITemplate template : templates) {
for (ApiUriTemplate template : templates) {
String fullPaath = "";
if( template.getUriTemplate() != AnnotationProcessor.WILD_CARD ) {
fullPaath = apiConfig.getContext() + template.getUriTemplate();
@ -341,5 +289,6 @@ public class APIPublisherUtil {
}
}
}
apiConfig.setUriTemplates(templates);
}
}

@ -18,7 +18,7 @@
package org.wso2.carbon.apimgt.webapp.publisher.config;
import org.wso2.carbon.apimgt.api.model.Scope;
import org.wso2.carbon.apimgt.webapp.publisher.dto.ApiScope;
public class APIResource {
@ -28,7 +28,7 @@ public class APIResource {
private String UriTemplate;
private String consumes;
private String produces;
private Scope scope;
private ApiScope scope;
public String getAuthType() {
return AuthType;
@ -78,11 +78,11 @@ public class APIResource {
this.produces = produces;
}
public Scope getScope() {
public ApiScope getScope() {
return scope;
}
public void setScope(Scope scope) {
public void setScope(ApiScope scope) {
this.scope = scope;
}
}

@ -0,0 +1,64 @@
/*
* 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.webapp.publisher.dto;
public class ApiScope {
String key;
String name;
String roles;
String description;
int id;
public ApiScope() {
}
public String getKey() {
return this.key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getRoles() {
return this.roles;
}
public void setRoles(String roles) {
this.roles = roles;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
}

@ -0,0 +1,73 @@
/*
* 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.webapp.publisher.dto;
/**
* This hold the api uri template information.
*/
public class ApiUriTemplate {
private String authType;
private String httpVerb;
private String resourceURI;
private String uriTemplate;
private ApiScope scope;
public ApiUriTemplate() {}
public String getAuthType() {
return authType;
}
public void setAuthType(String authType) {
this.authType = authType;
}
public String getHttpVerb() {
return httpVerb;
}
public void setHttpVerb(String httpVerb) {
this.httpVerb = httpVerb;
}
public String getResourceURI() {
return resourceURI;
}
public void setResourceURI(String resourceURI) {
this.resourceURI = resourceURI;
}
public String getUriTemplate() {
return uriTemplate;
}
public void setUriTemplate(String uriTemplate) {
this.uriTemplate = uriTemplate;
}
public ApiScope getScope() {
return scope;
}
public void setScope(ApiScope scope) {
this.scope = scope;
}
}

@ -0,0 +1,48 @@
/*
* 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.webapp.publisher.exception;
/**
* Handles the exceptions related to API management.
*/
public class APIManagerPublisherException extends Exception {
private static final long serialVersionUID = -8933142342423122660L;
public APIManagerPublisherException(String msg, Exception nestedEx) {
super(msg, nestedEx);
}
public APIManagerPublisherException(String message, Throwable cause) {
super(message, cause);
}
public APIManagerPublisherException(String msg) {
super(msg);
}
public APIManagerPublisherException() {
super();
}
public APIManagerPublisherException(Throwable cause) {
super(cause);
}
}

@ -18,8 +18,8 @@
*/
package org.wso2.carbon.apimgt.webapp.publisher.internal;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService;
import org.wso2.carbon.apimgt.webapp.publisher.APIConfig;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService;
@ -36,7 +36,8 @@ public class APIPublisherDataHolder {
private TenantManager tenantManager;
private RegistryService registryService;
private boolean isServerStarted;
private Stack<API> unpublishedApis = new Stack<>();
private Stack<APIConfig> unpublishedApis = new Stack<>();
private IntegrationClientService integrationClientService;
private static APIPublisherDataHolder thisInstance = new APIPublisherDataHolder();
@ -108,11 +109,20 @@ public class APIPublisherDataHolder {
isServerStarted = serverStarted;
}
public Stack<API> getUnpublishedApis() {
public Stack<APIConfig> getUnpublishedApis() {
return unpublishedApis;
}
public void setUnpublishedApis(Stack<API> unpublishedApis) {
public void setUnpublishedApis(Stack<APIConfig> unpublishedApis) {
this.unpublishedApis = unpublishedApis;
}
public IntegrationClientService getIntegrationClientService() {
return integrationClientService;
}
public void setIntegrationClientService(
IntegrationClientService integrationClientService) {
this.integrationClientService = integrationClientService;
}
}

@ -22,7 +22,7 @@ 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.impl.APIManagerConfigurationService;
import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherServiceImpl;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherStartupHandler;
@ -30,16 +30,9 @@ import org.wso2.carbon.apimgt.webapp.publisher.config.WebappPublisherConfig;
import org.wso2.carbon.core.ServerStartupObserver;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.ConfigurationContextService;
/**
* @scr.component name="org.wso2.carbon.apimgt.webapp.publisher" immediate="true"
* @scr.reference name="config.context.service"
* interface="org.wso2.carbon.utils.ConfigurationContextService"
* cardinality="0..1"
* policy="dynamic"
* bind="setConfigurationContextService"
* unbind="unsetConfigurationContextService"
* @scr.reference name="user.realmservice.default"
* interface="org.wso2.carbon.user.core.service.RealmService"
* cardinality="1..1"
@ -52,6 +45,11 @@ import org.wso2.carbon.utils.ConfigurationContextService;
* policy="dynamic"
* bind="setRegistryService"
* unbind="unsetRegistryService"
* interface="org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService"
* cardinality="1..1"
* policy="dynamic"
* bind="setIntegrationClientService"
* unbind="unsetIntegrationClientService"
*/
public class APIPublisherServiceComponent {
@ -97,28 +95,6 @@ public class APIPublisherServiceComponent {
bundleContext.registerService(ServerStartupObserver.class, new APIPublisherStartupHandler(), null);
}
protected void setAPIManagerConfigurationService(APIManagerConfigurationService service) {
//do nothing
}
protected void unsetAPIManagerConfigurationService(APIManagerConfigurationService service) {
//do nothing
}
protected void setConfigurationContextService(ConfigurationContextService configurationContextService) {
if (log.isDebugEnabled()) {
log.debug("Setting ConfigurationContextService");
}
APIPublisherDataHolder.getInstance().setConfigurationContextService(configurationContextService);
}
protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) {
if (log.isDebugEnabled()) {
log.debug("Un-setting ConfigurationContextService");
}
APIPublisherDataHolder.getInstance().setConfigurationContextService(null);
}
protected void setRealmService(RealmService realmService) {
if (log.isDebugEnabled()) {
log.debug("Setting Realm Service");
@ -143,4 +119,15 @@ public class APIPublisherServiceComponent {
protected void unsetRegistryService(RegistryService registryService) {
APIPublisherDataHolder.getInstance().setRegistryService(null);
}
protected void setIntegrationClientService(IntegrationClientService integrationClientService) {
if (integrationClientService != null && log.isDebugEnabled()) {
log.debug("integrationClientService initialized");
}
APIPublisherDataHolder.getInstance().setIntegrationClientService(integrationClientService);
}
protected void unsetIntegrationClientService(IntegrationClientService integrationClientService) {
APIPublisherDataHolder.getInstance().setIntegrationClientService(null);
}
}

@ -24,7 +24,6 @@ import org.apache.catalina.LifecycleListener;
import org.apache.catalina.core.StandardContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.webapp.publisher.APIConfig;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil;
@ -77,8 +76,6 @@ public class APIPublisherLifecycleListener implements LifecycleListener {
boolean isTenantActive = APIPublisherDataHolder.getInstance().
getTenantManager().isTenantActive(tenantId);
if (isTenantActive) {
apiConfig.init();
API api = APIPublisherUtil.getAPI(apiConfig);
boolean isServerStarted = APIPublisherDataHolder.getInstance().isServerStarted();
if (isServerStarted) {
APIPublisherService apiPublisherService =
@ -87,13 +84,13 @@ public class APIPublisherLifecycleListener implements LifecycleListener {
throw new IllegalStateException(
"API Publisher service is not initialized properly");
}
apiPublisherService.publishAPI(api);
apiPublisherService.publishAPI(apiConfig);
} else {
if (log.isDebugEnabled()) {
log.debug("Server has not started yet. Hence adding API '" +
api.getId().getApiName() + "' to the queue");
apiConfig.getName() + "' to the queue");
}
APIPublisherDataHolder.getInstance().getUnpublishedApis().push(api);
APIPublisherDataHolder.getInstance().getUnpublishedApis().push(apiConfig);
}
} else {
log.error("No tenant [" + apiConfig.getTenantDomain() + "] " +
@ -112,14 +109,11 @@ public class APIPublisherLifecycleListener implements LifecycleListener {
} catch (UserStoreException e) {
log.error("Error while retrieving tenant admin user for the tenant domain"
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(), e);
} catch (Throwable e) {
// This is done to stop tomcat failure if a webapp failed to publish apis.
log.error("Failed to Publish api from " + servletContext.getContextPath(), e);
}
}
}
}
//TODO : Need to implemented, to merge API Definitions in cases where implementation of an API Lies in two classes
private List<APIResourceConfiguration> mergeAPIDefinitions(List<APIResourceConfiguration> inputList) {
return null;
}
}

@ -21,10 +21,10 @@ import io.swagger.annotations.SwaggerDefinition;
import org.apache.catalina.core.StandardContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.model.Scope;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResource;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResourceConfiguration;
import org.wso2.carbon.apimgt.webapp.publisher.dto.ApiScope;
import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
@ -53,7 +53,7 @@ public class AnnotationProcessor {
private static final Log log = LogFactory.getLog(AnnotationProcessor.class);
private static final String AUTH_TYPE = "Any";
private static final String AUTH_TYPE = "Application & Application User";
private static final String STRING_ARR = "string_arr";
private static final String STRING = "string";
private static final String PACKAGE_ORG_APACHE = "org.apache";
@ -96,7 +96,7 @@ public class AnnotationProcessor {
private Class<io.swagger.annotations.ApiOperation> apiOperation;
private Class<org.wso2.carbon.apimgt.annotations.api.Scope> scopeClass;
private Class<org.wso2.carbon.apimgt.annotations.api.Scopes> scopesClass;
private Map<String, Scope> apiScopes;
private Map<String, ApiScope> apiScopes;
public AnnotationProcessor(final StandardContext context) {
servletContext = context.getServletContext();
@ -206,20 +206,20 @@ public class AnnotationProcessor {
return apiResourceConfigs;
}
private Map<String,Scope> processAPIScopes(Annotation annotation) throws Throwable {
Map<String, Scope> scopes = new HashMap<>();
private Map<String,ApiScope> processAPIScopes(Annotation annotation) throws Throwable {
Map<String, ApiScope> scopes = new HashMap<>();
InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation);
Annotation[] annotatedScopes = (Annotation[]) methodHandler.invoke(annotation, scopesClass
.getMethod(ANNOTATIONS_SCOPES, null), null);
Scope scope;
ApiScope scope;
String permissions[];
StringBuilder aggregatedPermissions;
for(int i=0; i<annotatedScopes.length; i++){
aggregatedPermissions = new StringBuilder();
methodHandler = Proxy.getInvocationHandler(annotatedScopes[i]);
scope = new Scope();
scope = new ApiScope();
scope.setName(invokeMethod(scopeClass
.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_NAME), annotatedScopes[i], STRING));
scope.setDescription(invokeMethod(scopeClass
@ -277,13 +277,13 @@ public class AnnotationProcessor {
resource.setProduces(invokeMethod(producesClassMethods[0], producesAnno, STRING_ARR));
}
if (annotations[i].annotationType().getName().equals(ApiOperation.class.getName())) {
Scope scope = this.getScope(annotations[i]);
ApiScope scope = this.getScope(annotations[i]);
if (scope != null) {
resource.setScope(scope);
} else {
log.warn("Scope is not defined for '" + makeContextURLReady(resourceRootContext) +
makeContextURLReady(subCtx) + "' endpoint, hence assigning the default scope");
scope = new Scope();
scope = new ApiScope();
scope.setName(DEFAULT_SCOPE_NAME);
scope.setDescription(DEFAULT_SCOPE_NAME);
scope.setKey(DEFAULT_SCOPE_KEY);
@ -456,7 +456,7 @@ public class AnnotationProcessor {
}
}
private Scope getScope(Annotation currentMethod) throws Throwable {
private ApiScope getScope(Annotation currentMethod) throws Throwable {
InvocationHandler methodHandler = Proxy.getInvocationHandler(currentMethod);
Annotation[] extensions = (Annotation[]) methodHandler.invoke(currentMethod,
apiOperation.getMethod(SWAGGER_ANNOTATIONS_EXTENSIONS, null), null);

@ -22,18 +22,20 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>apimgt-extensions</artifactId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<packaging>pom</packaging>
<name>WSO2 Carbon - API Management Extensions Component</name>
<url>http://wso2.org</url>
<modules>
<module>org.wso2.carbon.apimgt.integration.generated.client</module>
<module>org.wso2.carbon.apimgt.integration.client</module>
<module>org.wso2.carbon.apimgt.webapp.publisher</module>
<module>org.wso2.carbon.apimgt.application.extension</module>
<module>org.wso2.carbon.apimgt.application.extension.api</module>

@ -22,7 +22,7 @@
<parent>
<artifactId>certificate-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -47,5 +47,9 @@
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
<context-param>
<param-name>isSharedWithAllTenants</param-name>
<param-value>true</param-value>
</context-param>
</web-app>

@ -22,7 +22,7 @@
<parent>
<artifactId>certificate-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -52,6 +52,10 @@
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
<context-param>
<param-name>isSharedWithAllTenants</param-name>
<param-value>true</param-value>
</context-param>
<security-constraint>
<web-resource-collection>

@ -21,13 +21,13 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>certificate-mgt</artifactId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>WSO2 Carbon - Certificate Management Core</name>
<description>WSO2 Carbon - Certificate Management Core</description>
@ -61,7 +61,7 @@
javax.security.auth.x500,
javax.xml.*,
javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional,
org.apache.commons.codec.binary,
org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}",
org.bouncycastle.asn1,
org.bouncycastle.asn1.x500,
org.bouncycastle.asn1.x509,

@ -22,14 +22,14 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>certificate-mgt</artifactId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<packaging>pom</packaging>
<name>WSO2 Carbon - Certificate Management Component</name>
<url>http://wso2.org</url>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -0,0 +1,104 @@
/*
* 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.extensions.device.type.deployer.config;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* <p>Java class for DeviceDetails complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="DeviceDetails">
* &lt;simpleContent>
* &lt;extension base="&lt;http://www.w3.org/2001/XMLSchema>string">
* &lt;attribute name="table-id" type="{http://www.w3.org/2001/XMLSchema}string" />
* &lt;/extension>
* &lt;/simpleContent>
* &lt;/complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Claimable", propOrder = {
"value"
})
public class Claimable {
@XmlValue
protected String value;
@XmlAttribute(name = "enabled")
protected boolean enabled;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the enabled property.
*
* @return
* possible object is
* {@link String }
*
*/
public boolean isEnabled() {
return enabled;
}
/**
* Sets the value of the enabled property.
*
* @param enabled
* allowed object is
* {@link String }
*
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}

@ -18,11 +18,8 @@
*/
package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.*;
import java.util.List;
/**
@ -56,6 +53,8 @@ public class DeviceTypeConfiguration {
@XmlElement(name = "DeviceDetails", required = true)
protected DeviceDetails deviceDetails;
@XmlElement(name = "Claimable", required = true)
protected Claimable claimable;
@XmlElement(name = "Features", required = true)
protected Features features;
@XmlElement(name = "ProvisioningConfig", required = true)
@ -74,6 +73,21 @@ public class DeviceTypeConfiguration {
protected String name;
@XmlElement(name = "PolicyMonitoring", required = true)
protected PolicyMonitoring policyMonitoring;
@XmlElementWrapper(name = "InitialOperationConfig")
@XmlElement(name = "Operation", required = true)
protected List<String> operations;
public List<String> getOperations() {
return operations;
}
public void setOperations(List<String> operations) {
this.operations = operations;
}
/**
* Gets the value of the taskConfiguration property.
@ -119,6 +133,27 @@ public class DeviceTypeConfiguration {
this.deviceDetails = value;
}
/**
* Gets the value of the Claimable property.
*
* @return possible object is
* {@link DeviceDetails }
*/
public Claimable getClaimable() {
return claimable;
}
/**
* Sets the value of the deviceDetails property.
*
* @param value allowed object is
* {@link DeviceDetails }
*/
public void setClaimable(Claimable value) {
this.claimable = value;
}
/**
* Gets the value of the policyMonitoring property.
*

@ -0,0 +1,39 @@
package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config;
import javax.xml.bind.annotation.*;
import java.util.List;
/**
* <p>Java class for InitialOperationConfig complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="InitialOperationConfig">
* &lt;complexContent>
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* &lt;sequence>
* &lt;element name="Operations" type="{http://www.w3.org/2001/XMLSchema}list"/>
* &lt;/sequence>
* &lt;/restriction>
* &lt;/complexContent>
* &lt;/complexType>
* </pre>
*
*
*/
@XmlRootElement(name = "InitialOperationConfig")
public class InitialOperationConfig {
private List<String> operations;
@XmlElementWrapper(name = "Operations", required = true)
@XmlElement(name = "Operation", required = true)
public List<String> getOperations() {
return operations;
}
public void setOperationsll(List<String> operations) {
this.operations = operations;
}
}

@ -65,6 +65,7 @@ public class DeviceTypeManager implements DeviceManager {
private LicenseManager licenseManager;
private boolean propertiesExist;
private boolean requiredDeviceTypeAuthorization;
private boolean claimable;
private FeatureManager featureManager;
@ -101,8 +102,13 @@ public class DeviceTypeManager implements DeviceManager {
String msg = "Error occurred while adding default license for " + deviceType + " devices";
throw new DeviceTypeDeployerFileException(msg, e);
}
claimable = false;
if (deviceTypeConfiguration.getClaimable() != null ) {
claimable = deviceTypeConfiguration.getClaimable().isEnabled();
}
DeviceDetails deviceDetails = deviceTypeConfiguration.getDeviceDetails();
if (deviceDetails != null) {
//Check whether device dao definition exist.
@ -341,7 +347,7 @@ public class DeviceTypeManager implements DeviceManager {
@Override
public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
return false;
return claimable;
}
@Override

@ -20,11 +20,7 @@ package org.wso2.carbon.device.mgt.extensions.device.type.deployer.template;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.MonitoringOperation;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
@ -57,6 +53,8 @@ public class DeviceTypeManagerService implements DeviceManagementService {
private OperationMonitoringTaskConfig operationMonitoringConfigs;
private List<MonitoringOperation> monitoringOperations;
private PolicyMonitoringManager policyMonitoringManager;
private InitialOperationConfig initialOperationConfig;
private List<String> operations;
public DeviceTypeManagerService(DeviceTypeConfigIdentifier deviceTypeConfigIdentifier,
DeviceTypeConfiguration deviceTypeConfiguration) {
@ -66,6 +64,7 @@ public class DeviceTypeManagerService implements DeviceManagementService {
this.populatePushNotificationConfig(deviceTypeConfiguration.getPushNotificationProvider());
this.operationMonitoringConfigs = new OperationMonitoringTaskConfig();
this.setOperationMonitoringConfig(deviceTypeConfiguration);
this.setInitialOperationConfig(deviceTypeConfiguration);
if (deviceTypeConfiguration.getPolicyMonitoring() != null && deviceTypeConfiguration.getPolicyMonitoring()
.isEnabled()) {
this.policyMonitoringManager = new DefaultPolicyMonitoringManager();
@ -157,6 +156,11 @@ public class DeviceTypeManagerService implements DeviceManagementService {
return policyMonitoringManager;
}
@Override
public InitialOperationConfig getInitialOperationConfig() {
return initialOperationConfig;
}
private void setProvisioningConfig(String tenantDomain, DeviceTypeConfiguration deviceTypeConfiguration) {
if (deviceTypeConfiguration.getProvisioningConfig() != null) {
boolean sharedWithAllTenants = deviceTypeConfiguration.getProvisioningConfig().isSharedWithAllTenants();
@ -166,6 +170,15 @@ public class DeviceTypeManagerService implements DeviceManagementService {
}
}
protected void setInitialOperationConfig(DeviceTypeConfiguration deviceTypeConfiguration) {
if (deviceTypeConfiguration.getOperations() != null) {
List<String> ops = deviceTypeConfiguration.getOperations();
if (ops != null && !ops.isEmpty()) {
initialOperationConfig.setOperations(ops);
}
}
}
private void setType(String type) {
this.type = type;
}

@ -36,10 +36,12 @@
</Feature>
</Features>
<!-- <Sensors table-id="SAMPLE_DEVICE_2">
<Claimable enabled="true"/>
<Sensors table-id="SAMPLE_DEVICE_2">
<Sensor code="CPU_Temperature">
<Name>temperature sensor fitted</Name>
<StreamDefinition>org.wso2.temperature.stream<StreamDefinition>
<StreamDefinition>org.wso2.temperature.stream</StreamDefinition>
<Description>this is a sensor</Description>
<SensorStaticProperties>
<Property name="unit">celcius</Property>
@ -48,7 +50,7 @@
</Sensor>
<Sensor code="DHT11_Temperature">
<Name>temperature sensor fitted</Name>
<StreamDefinition>org.wso2.temperature.stream<StreamDefinition>
<StreamDefinition>org.wso2.temperature.stream</StreamDefinition>
<Description>this is a sensor</Description>
<SensorStaticProperties>
<Property name="unit">celcius</Property>
@ -57,7 +59,7 @@
<Property name="model_number"/>
</SensorDynamicProperties>
</Sensor>
</Sensors> -->
</Sensors>
<ProvisioningConfig>
<SharedWithAllTenants>false</SharedWithAllTenants>

@ -22,15 +22,15 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm</artifactId>
<artifactId>org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm</artifactId>
<packaging>bundle</packaging>
<name>WSO2 Carbon - GCM Based Push Notification Provider Implementation</name>
<description>WSO2 Carbon - GCM Based Push Notification Provider Implementation</description>
<name>WSO2 Carbon - FCM Based Push Notification Provider Implementation</name>
<description>WSO2 Carbon - FCM Based Push Notification Provider Implementation</description>
<url>http://wso2.org</url>
<dependencies>
@ -128,10 +128,10 @@
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
<Bundle-Description>GCM Based Push Notification Provider Bundle</Bundle-Description>
<Bundle-Description>FCM Based Push Notification Provider Bundle</Bundle-Description>
<Export-Package>
!org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm.internal,
org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm.*
!org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.internal,
org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.*
</Export-Package>
<Import-Package>
com.google.gson,

@ -16,24 +16,24 @@
* under the License.
*
*/
package org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm;
package org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm;
import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationProvider;
public class GCMBasedPushNotificationProvider implements PushNotificationProvider {
public class FCMBasedPushNotificationProvider implements PushNotificationProvider {
private static final String PS_PROVIDER_GCM = "GCM";
private static final String PS_PROVIDER_FCM = "FCM";
@Override
public String getType() {
return PS_PROVIDER_GCM;
return PS_PROVIDER_FCM;
}
@Override
public NotificationStrategy getNotificationStrategy(PushNotificationConfig config) {
return new GCMNotificationStrategy(config);
return new FCMNotificationStrategy(config);
}
}

@ -16,7 +16,7 @@
* under the License.
*
*/
package org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm;
package org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
@ -27,7 +27,7 @@ import org.wso2.carbon.device.mgt.common.push.notification.NotificationContext;
import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationExecutionFailedException;
import org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm.internal.GCMDataHolder;
import org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.internal.FCMDataHolder;
import java.io.IOException;
import java.io.OutputStream;
@ -35,16 +35,16 @@ import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
public class GCMNotificationStrategy implements NotificationStrategy {
public class FCMNotificationStrategy implements NotificationStrategy {
private static final String GCM_TOKEN = "GCM_TOKEN";
private final static String GCM_ENDPOINT = "https://fcm.googleapis.com/fcm/send";
private static final String GCM_API_KEY = "gcmAPIKey";
private static final String FCM_TOKEN = "FCM_TOKEN";
private static final String FCM_ENDPOINT = "https://fcm.googleapis.com/fcm/send";
private static final String FCM_API_KEY = "fcmAPIKey";
private static final int TIME_TO_LIVE = 60;
private static final int HTTP_STATUS_CODE_OK = 200;
private PushNotificationConfig config;
public GCMNotificationStrategy(PushNotificationConfig config) {
public FCMNotificationStrategy(PushNotificationConfig config) {
this.config = config;
}
@ -57,7 +57,7 @@ public class GCMNotificationStrategy implements NotificationStrategy {
public void execute(NotificationContext ctx) throws PushNotificationExecutionFailedException {
try {
Device device =
GCMDataHolder.getInstance().getDeviceManagementProviderService().getDevice(ctx.getDeviceId());
FCMDataHolder.getInstance().getDeviceManagementProviderService().getDevice(ctx.getDeviceId());
this.sendWakeUpCall(ctx.getOperation().getCode(), device);
} catch (DeviceManagementException e) {
throw new PushNotificationExecutionFailedException("Error occurred while retrieving device information", e);
@ -79,13 +79,13 @@ public class GCMNotificationStrategy implements NotificationStrategy {
private void sendWakeUpCall(String message,
Device device) throws IOException, PushNotificationExecutionFailedException {
OutputStream os = null;
byte[] bytes = getGCMRequest(message, getGCMToken(device.getProperties())).getBytes();
byte[] bytes = getFCMRequest(message, getFCMToken(device.getProperties())).getBytes();
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(GCM_ENDPOINT).openConnection();
conn = (HttpURLConnection) new URL(FCM_ENDPOINT).openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key=" + config.getProperty(GCM_API_KEY));
conn.setRequestProperty("Authorization", "key=" + config.getProperty(FCM_API_KEY));
conn.setRequestMethod("POST");
conn.setDoOutput(true);
os = conn.getOutputStream();
@ -102,35 +102,35 @@ public class GCMNotificationStrategy implements NotificationStrategy {
}
}
private static String getGCMRequest(String message, String registrationId) {
JsonObject gcmRequest = new JsonObject();
gcmRequest.addProperty("delay_while_idle", false);
gcmRequest.addProperty("time_to_live", TIME_TO_LIVE);
private static String getFCMRequest(String message, String registrationId) {
JsonObject fcmRequest = new JsonObject();
fcmRequest.addProperty("delay_while_idle", false);
fcmRequest.addProperty("time_to_live", TIME_TO_LIVE);
//Add message to GCM request
//Add message to FCM request
JsonObject data = new JsonObject();
if (message != null && !message.isEmpty()) {
data.addProperty("data", message);
gcmRequest.add("data", data);
fcmRequest.add("data", data);
}
//Set device reg-id
JsonArray regIds = new JsonArray();
regIds.add(new JsonPrimitive(registrationId));
gcmRequest.add("registration_ids", regIds);
return gcmRequest.toString();
fcmRequest.add("registration_ids", regIds);
return fcmRequest.toString();
}
private static String getGCMToken(List<Device.Property> properties) {
String gcmToken = null;
private static String getFCMToken(List<Device.Property> properties) {
String fcmToken = null;
for (Device.Property property : properties) {
if (GCM_TOKEN.equals(property.getName())) {
gcmToken = property.getValue();
if (FCM_TOKEN.equals(property.getName())) {
fcmToken = property.getValue();
break;
}
}
return gcmToken;
return fcmToken;
}
}

@ -16,16 +16,16 @@
* under the License.
*
*/
package org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm.internal;
package org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.internal;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
public class GCMDataHolder {
public class FCMDataHolder {
private DeviceManagementProviderService deviceManagementProviderService;
private static GCMDataHolder thisInstance = new GCMDataHolder();
private static FCMDataHolder thisInstance = new FCMDataHolder();
public static GCMDataHolder getInstance() {
public static FCMDataHolder getInstance() {
return thisInstance;
}

@ -16,7 +16,7 @@
* under the License.
*
*/
package org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm.internal;
package org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -24,7 +24,7 @@ import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
/**
* @scr.component name="org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm.internal.GCMPushNotificationServiceComponent" immediate="true"
* @scr.component name="org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.internal.FCMPushNotificationServiceComponent" immediate="true"
* @scr.reference name="carbon.device.mgt.provider"
* interface="org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService"
* cardinality="1..1"
@ -32,23 +32,20 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
* bind="setDeviceManagementProviderService"
* unbind="unsetDeviceManagementProviderService"
*/
public class GCMPushNotificationServiceComponent {
public class FCMPushNotificationServiceComponent {
private static final Log log = LogFactory.getLog(GCMPushNotificationServiceComponent.class);
private static final Log log = LogFactory.getLog(FCMPushNotificationServiceComponent.class);
@SuppressWarnings("unused")
protected void activate(ComponentContext componentContext) {
try {
if (log.isDebugEnabled()) {
log.debug("Initializing GCM based push notification provider implementation bundle");
}
//Do nothing
if (log.isDebugEnabled()) {
log.debug("GCM based push notification provider implementation bundle has been successfully " +
log.debug("FCM based push notification provider implementation bundle has been successfully " +
"initialized");
}
} catch (Throwable e) {
log.error("Error occurred while initializing GCM based push notification provider " +
log.error("Error occurred while initializing FCM based push notification provider " +
"implementation bundle", e);
}
}
@ -59,12 +56,12 @@ public class GCMPushNotificationServiceComponent {
protected void setDeviceManagementProviderService(
DeviceManagementProviderService deviceManagementProviderService) {
GCMDataHolder.getInstance().setDeviceManagementProviderService(deviceManagementProviderService);
FCMDataHolder.getInstance().setDeviceManagementProviderService(deviceManagementProviderService);
}
protected void unsetDeviceManagementProviderService(
DeviceManagementProviderService deviceManagementProviderService) {
GCMDataHolder.getInstance().setDeviceManagementProviderService(deviceManagementProviderService);
FCMDataHolder.getInstance().setDeviceManagementProviderService(deviceManagementProviderService);
}
}

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -25,7 +25,7 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
/**
* @scr.component name="org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm.internal.XMPPPushNotificationServiceComponent" immediate="true"
* @scr.component name="org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.internal.XMPPPushNotificationServiceComponent" immediate="true"
* @scr.reference name="carbon.device.mgt.provider"
* interface="org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService"
* cardinality="1..1"

@ -22,7 +22,7 @@
<parent>
<artifactId>carbon-devicemgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
@ -34,7 +34,7 @@
<url>http://wso2.org</url>
<modules>
<module>org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm</module>
<module>org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm</module>
<module>org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt</module>
<module>org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp</module>
<module>org.wso2.carbon.device.mgt.extensions.device.type.deployer</module>

@ -3,7 +3,7 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>device-mgt</artifactId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>device-mgt</artifactId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
@ -281,6 +281,23 @@
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.commons</groupId>
<artifactId>org.wso2.carbon.application.mgt.stub</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity.framework</groupId>
<artifactId>org.wso2.carbon.identity.user.store.count</artifactId>
<version>${carbon.identity.framework.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

@ -30,13 +30,13 @@ public class BasePaginatedResult {
value = "Number of total resources.",
example = "1")
@JsonProperty("count")
private int count;
private long count;
public int getCount() {
public long getCount() {
return count;
}
public void setCount(int count) {
public void setCount(long count) {
this.count = count;
}
}

@ -423,6 +423,83 @@ public interface DeviceManagementService {
@HeaderParam("If-Modified-Since")
String ifModifiedSince);
@GET
@Path("/{type}/{id}/location")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Location Details of a Device",
notes = "Get the location details of a device by specifying the device type and device identifier.",
tags = "Device Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the location details of the device.",
response = Device.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. Empty body because the client already has the latest version" +
" of the requested resource.\n"),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Location data for the specified device was not found.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while retrieving the device details.",
response = ErrorResponse.class)
})
Response getDeviceLocation(
@ApiParam(
name = "type",
value = "The device type name, such as ios, android, windows or fire-alarm.",
required = true)
@PathParam("type")
@Size(max = 45)
String type,
@ApiParam(
name = "id",
value = "The device identifier of the device you want ot get details.",
required = true)
@PathParam("id")
@Size(max = 45)
String id,
@ApiParam(
name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time. \n" +
"Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z. \n" +
"Example: Mon, 05 Jan 2014 15:10:00 +0200",
required = false)
@HeaderParam("If-Modified-Since")
String ifModifiedSince);
//device rename request would looks like follows
//POST devices/type/virtual_firealarm/id/us06ww93auzp/rename
@POST
@ -575,7 +652,7 @@ public interface DeviceManagementService {
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Feature Details of a Device",
notes = "WSO2 EMM features enable you to carry out many operations based on the device platform. " +
notes = "WSO2 IoTS features enable you to carry out many operations based on the device platform. " +
"Using this REST API you can get the features that can be carried out on a preferred device type," +
" such as iOS, Android or Windows.",
tags = "Device Management",
@ -644,7 +721,7 @@ public interface DeviceManagementService {
@ApiParam(
name = "id",
value = "The device identifier of the device.\n" +
"INFO: Make sure to add the ID of a device that is already registered with WSO2 EMM.",
"INFO: Make sure to add the ID of a device that is already registered with WSO2 IoTS.",
required = true)
@PathParam("id")
@Size(max = 45)
@ -911,7 +988,7 @@ public interface DeviceManagementService {
@ApiParam(
name = "id",
value = "The device identifier of the device you wish to get details.\n" +
"INFO: Make sure to add the ID of a device that is already registered with WSO2 EMM.",
"INFO: Make sure to add the ID of a device that is already registered with WSO2 IoTS.",
required = true)
@PathParam("id")
@Size(max = 45)
@ -952,8 +1029,8 @@ public interface DeviceManagementService {
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get the details of the policy that is enforced on a device.",
notes = "A policy is enforced on all the devices that register with WSO2 EMM." +
"WSO2 EMM filters the policies based on the device platform (device type)," +
notes = "A policy is enforced on all the devices that register with WSO2 IoTS." +
"WSO2 IoTS filters the policies based on the device platform (device type)," +
"the device ownership type, the user role or name and finally, the policy that matches these filters will be enforced on the device.",
tags = "Device Management",
extensions = {
@ -1041,7 +1118,7 @@ public interface DeviceManagementService {
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Policy Compliance Details of a Device",
notes = "A policy is enforced on the devices that register with WSO2 EMM. " +
notes = "A policy is enforced on the devices that register with WSO2 IoTS. " +
"The server checks if the settings in the device comply with the policy that is enforced on the device using this REST API.",
tags = "Device Management",
extensions = {

@ -18,17 +18,7 @@
*/
package org.wso2.carbon.device.mgt.jaxrs.service.api;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Info;
import io.swagger.annotations.ExtensionProperty;
import io.swagger.annotations.Extension;
import io.swagger.annotations.Tag;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.ResponseHeader;
import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
@ -120,7 +110,7 @@ public interface RoleManagementService {
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting the List of Roles",
notes = "WSO2 EMM supports role-based access control (RBAC) and role management. Using this API you can the list of roles that are in WSO2 EMM.\n" +
notes = "WSO2 IoTS supports role-based access control (RBAC) and role management. Using this API you can the list of roles that are in WSO2 IoTS.\n" +
"Note: Internal roles, roles created for service-providers, and application related roles will not be given in the output.",
tags = "Role Management",
extensions = {
@ -133,7 +123,7 @@ public interface RoleManagementService {
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the list of roles in WSO2 EMM.",
message = "OK. \n Successfully fetched the list of roles in WSO2 IoTS.",
response = RoleList.class,
responseHeaders = {
@ResponseHeader(
@ -190,6 +180,88 @@ public interface RoleManagementService {
defaultValue = "5")
@QueryParam("limit") int limit);
@GET
@Path("/filter/{prefix}")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting the List of Roles filtered by the given prefix",
notes = "WSO2 IoTS supports role-based access control (RBAC) and role management. Using this API you can the list of roles that are in WSO2 IoTS.\n" +
"Note: Internal roles, roles created for service-providers, and application related roles will not be given in the output.",
tags = "Role Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:roles:view")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the list of roles in WSO2 IoTS.",
response = RoleList.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client already has the latest version of the requested resource."),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported"),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while fetching list of roles.",
response = ErrorResponse.class)
})
Response getFilteredRoles(
@ApiParam(
name = "prefix",
value = "Filtering prefix of the role.",
required = true,
defaultValue = "")
@PathParam("prefix") String prefix,
@ApiParam(
name = "filter",
value = "Provide a character or a few characters in the role name.",
required = false)
@QueryParam("filter") String filter,
@ApiParam(
name = "user-store",
value = "The name of the UserStore you wish to get the list of roles.",
required = false)
@QueryParam("user-store") String userStoreName,
@ApiParam(
name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time." +
"Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" +
"Example: Mon, 05 Jan 2014 15:10:00 +0200",
required = false)
@HeaderParam("If-Modified-Since") String ifModifiedSince,
@ApiParam(
name = "offset",
value = "The starting pagination index for the complete list of qualified items.",
required = false,
defaultValue = "0")
@QueryParam("offset") int offset,
@ApiParam(
name = "limit",
value = "Provide how many role details you require from the starting pagination index/offset.",
required = false,
defaultValue = "5")
@QueryParam("limit") int limit);
@GET
@Path("/{roleName}/permissions")
@ApiOperation(
@ -197,7 +269,7 @@ public interface RoleManagementService {
httpMethod = "GET",
value = "Getting Permission Details of a Role",
notes = "An individual is associated a with set of responsibilities based on their " +
"role. In WSO2 EMM you are able to configure permissions based on the responsibilities carried " +
"role. In WSO2 IoTS you are able to configure permissions based on the responsibilities carried " +
"out by various roles. Therefore, if you wish to retrieve the permission details of a role, you can do " +
"so using this REST API.",
response = UIPermissionNode.class,
@ -350,7 +422,7 @@ public interface RoleManagementService {
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Adding a Role",
notes = "WSO2 EMM supports role-based access control (RBAC) and role management. Add a new role to WSO2 EMM using this REST API.",
notes = "WSO2 IoTS supports role-based access control (RBAC) and role management. Add a new role to WSO2 IoTS using this REST API.",
tags = "Role Management",
extensions = {
@Extension(properties = {
@ -410,7 +482,7 @@ public interface RoleManagementService {
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Adding a combined Role",
notes = "WSO2 EMM supports role-based access control (RBAC) and role management. Add a new combined role to WSO2 EMM using this REST API.",
notes = "WSO2 IoTS supports role-based access control (RBAC) and role management. Add a new combined role to WSO2 IoTS using this REST API.",
tags = "Role Management",
extensions = {
@Extension(properties = {
@ -653,4 +725,4 @@ public interface RoleManagementService {
defaultValue = "[admin]"
) List<String> users);
}
}

@ -0,0 +1,148 @@
/*
* 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.jaxrs.service.api.admin;
import io.swagger.annotations.*;
import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
@SwaggerDefinition(
info = @Info(
version = "1.0.0",
title = "",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = "name", value = "DeviceTypePublisherAdminService"),
@ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/admin/devicetype"),
})
}
),
tags = {
@Tag(name = "device_management", description = "")
}
)
@Path("/admin/devicetype")
@Api(value = "Devicetype deployment Administrative Service", description = "This an API intended to be used to " +
"deploy device type components" +
"Further, this is strictly restricted to admin users only ")
@Scopes(
scopes = {
@Scope(
name = "Devicetype deployment",
description = "Deploy devicetype",
key = "perm:devicetype:deployment",
permissions = {"/device-mgt/devicetype/deploy"}
)
}
)
public interface DeviceTypePublisherAdminService {
@POST
@Path("/deploy/{type}")
@ApiOperation(
httpMethod = "POST",
value = "Deploy device type\n",
notes = "This is an API that can be used to deploy existing device type artifact for tenant",
response = Response.class,
tags = "Devicetype Deployment Service",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devicetype:deployment")
})
})
@ApiResponses(value = {
@ApiResponse(
code = 201,
message = "OK. \n Successfully deployed the artifacts.",
response = Response.class),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n The specified resource does not exist."),
@ApiResponse(
code = 415,
message = "Unsupported media type. \n The entity of the request was in a not supported format."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while checking the authorization" +
" for a specified set of devices.",
response = ErrorResponse.class)
})
Response doPublish(
@ApiParam(name = "type",
value = "The type of deployment." +
"INFO: Deploy artifact with given type.",
required = true)
@PathParam("type") String type);
@GET
@Path("/deploy/{type}/status")
@ApiOperation(
httpMethod = "GET",
value = "Check the status of device type artifact\n",
notes = "This is an API that can be used to check the status of the artifact",
response = Response.class,
tags = "Devicetype Status Service",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devicetype:deployment")
})
})
@ApiResponses(value = {
@ApiResponse(
code = 201,
message = "OK. \n Successfully deployed the artifacts.",
response = Response.class),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n The specified resource does not exist."),
@ApiResponse(
code = 415,
message = "Unsupported media type. \n The entity of the request was in a not supported format."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while checking the authorization" +
" for a specified set of devices.",
response = ErrorResponse.class)
})
Response getStatus(@PathParam("type") String deviceType);
}

@ -18,6 +18,7 @@
*/
package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -34,6 +35,7 @@ import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
@ -41,6 +43,8 @@ import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.NonComplianceData;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException;
import org.wso2.carbon.device.mgt.common.search.SearchContext;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService;
import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
@ -133,7 +137,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
RequestValidationUtil.validateStatus(status);
request.setStatus(status);
}
if (groupId != 0 ) {
if (groupId != 0) {
request.setGroupId(groupId);
}
if (role != null && !role.isEmpty()) {
@ -359,6 +363,32 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.OK).entity(device).build();
}
@GET
@Path("/{type}/{id}/location")
@Override
public Response getDeviceLocation(
@PathParam("type") @Size(max = 45) String type,
@PathParam("id") @Size(max = 45) String id,
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
DeviceInformationManager informationManager;
DeviceLocation deviceLocation;
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(id);
deviceIdentifier.setType(type);
informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService();
deviceLocation = informationManager.getDeviceLocation(deviceIdentifier);
} catch (DeviceDetailsMgtException e) {
String msg = "Error occurred while getting the device location.";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
return Response.status(Response.Status.OK).entity(deviceLocation).build();
}
@GET
@Path("/{type}/{id}/features")
@Override

@ -30,37 +30,20 @@ import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.FilteringUtil;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer;
import org.wso2.carbon.user.api.AuthorizationManager;
import org.wso2.carbon.user.api.Permission;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.api.*;
import org.wso2.carbon.user.core.common.AbstractUserStoreManager;
import org.wso2.carbon.user.mgt.UserRealmProxy;
import org.wso2.carbon.user.mgt.common.UIPermissionNode;
import org.wso2.carbon.user.mgt.common.UserAdminException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.*;
import static org.wso2.carbon.device.mgt.jaxrs.util.Constants.PRIMARY_USER_STORE;
@ -105,6 +88,48 @@ public class RoleManagementServiceImpl implements RoleManagementService {
}
}
@GET
@Path("/filter/{prefix}")
@Override
public Response getFilteredRoles(
@PathParam("prefix") String prefix,
@QueryParam("filter") String filter,
@QueryParam("user-store") String userStore,
@HeaderParam("If-Modified-Since") String ifModifiedSince,
@QueryParam("offset") int offset, @QueryParam("limit") int limit) {
RequestValidationUtil.validatePaginationParameters(offset, limit);
List<String> finalRoleList;
RoleList targetRoles = new RoleList();
//if user store is null set it to primary
if (userStore == null || "".equals(userStore)) {
userStore = PRIMARY_USER_STORE;
}
try {
//Get the total role count that matches the given filter
List<String> filteredRoles = getRolesFromUserStore(filter, userStore);
finalRoleList = new ArrayList<String>();
filteredRoles = FilteringUtil.getFilteredList(getRolesFromUserStore(filter, userStore), offset, limit);
for (String rolename : filteredRoles){
if (rolename.startsWith(prefix)){
finalRoleList.add(rolename);
}
}
targetRoles.setCount(finalRoleList.size());
targetRoles.setList(finalRoleList);
return Response.ok().entity(targetRoles).build();
} catch (UserStoreException e) {
String msg = "Error occurred while retrieving roles from the underlying user stores";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
@GET
@Path("/{roleName}/permissions")
@Override
@ -404,7 +429,7 @@ public class RoleManagementServiceImpl implements RoleManagementService {
// Get all role permissions
final UIPermissionNode rolePermissions = this.getAllRolePermissions(roleName, userRealm);
List<String> permissions = new ArrayList<String>();
final UIPermissionNode emmRolePermissions = (UIPermissionNode)this.getRolePermissions(roleName);
final UIPermissionNode emmRolePermissions = (UIPermissionNode) this.getRolePermissions(roleName);
List<String> emmConsolePermissions = new ArrayList<String>();
this.getAuthorizedPermissions(emmRolePermissions, emmConsolePermissions);
emmConsolePermissions.removeAll(new ArrayList<String>(Arrays.asList(roleInfo.getPermissions())));
@ -413,7 +438,7 @@ public class RoleManagementServiceImpl implements RoleManagementService {
permissions.add(permission);
}
permissions.removeAll(emmConsolePermissions);
String [] allApplicablePerms = new String[permissions.size()];
String[] allApplicablePerms = new String[permissions.size()];
allApplicablePerms = permissions.toArray(allApplicablePerms);
roleInfo.setPermissions(allApplicablePerms);

@ -38,6 +38,8 @@ import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
import org.wso2.carbon.device.mgt.jaxrs.util.CredentialManagementResponseBuilder;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.identity.user.store.count.UserStoreCountRetriever;
import org.wso2.carbon.identity.user.store.count.exception.UserStoreCounterException;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.utils.CarbonUtils;
@ -395,6 +397,30 @@ public class UserManagementServiceImpl implements UserManagementService {
@Path("/count")
@Override
public Response getUserCount() {
try {
UserStoreCountRetriever userStoreCountRetrieverService = DeviceMgtAPIUtils.getUserStoreCountRetrieverService();
if (userStoreCountRetrieverService != null) {
long count = userStoreCountRetrieverService.countUsers("");
if (count != -1) {
BasicUserInfoList result = new BasicUserInfoList();
result.setCount(count);
return Response.status(Response.Status.OK).entity(result).build();
}
}
} catch (UserStoreCounterException e) {
String msg =
"Error occurred while retrieving the count of users that exist within the current tenant";
log.error(msg, e);
}
return getUserCountViaUserStoreManager();
}
/**
* This method returns the count of users using UserStoreManager.
*
* @return user count
*/
private Response getUserCountViaUserStoreManager() {
if (log.isDebugEnabled()) {
log.debug("Getting the user count");
}

@ -0,0 +1,311 @@
/*
* 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.jaxrs.service.impl.admin;
import org.apache.axis2.client.Options;
import org.apache.axis2.java.security.SSLProtocolSocketFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.application.mgt.stub.upload.CarbonAppUploaderStub;
import org.wso2.carbon.application.mgt.stub.upload.types.carbon.UploadedFileItem;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.util.Utils;
import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceTypePublisherAdminService;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.ResourceImpl;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.utils.CarbonUtils;
import javax.activation.DataHandler;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import java.io.*;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
@Path("/admin/devicetype")
public class DeviceTypePublisherAdminServiceImpl implements DeviceTypePublisherAdminService {
/**
* required soap header for authorization
*/
private static final String AUTHORIZATION_HEADER = "Authorization";
/**
* required soap header value for mutualSSL
*/
private static final String AUTHORIZATION_HEADER_VALUE = "Bearer";
private static final String KEY_STORE_TYPE = "JKS";
/**
* Default truststore type of the client
*/
private static final String TRUST_STORE_TYPE = "JKS";
/**
* Default keymanager type of the client
*/
private static final String KEY_MANAGER_TYPE = "SunX509"; //Default Key Manager Type
/**
* Default trustmanager type of the client
*/
private static final String TRUST_MANAGER_TYPE = "SunX509"; //Default Trust Manager Type
private static final String SSLV3 = "SSLv3";
private KeyStore keyStore;
private KeyStore trustStore;
private char[] keyStorePassword;
private SSLContext sslContext;
private static final Log log = LogFactory.getLog(DeviceTypePublisherAdminServiceImpl.class);
private static final String DEFAULT_RESOURCE_LOCATION = "/resources/devicetypes";
private static final String CAR_FILE_LOCATION = CarbonUtils.getCarbonHome() + File.separator + "repository" +
File.separator + "resources" + File.separator + "devicetypes";
private static final String DAS_PORT = "${iot.analytics.https.port}";
private static final String DAS_HOST_NAME = "${iot.analytics.host}";
private static final String DEFAULT_HTTP_PROTOCOL = "https";
private static final String IOT_MGT_PORT = "${iot.manager.https.port}";
private static final String IOT_MGT_HOST_NAME = "${iot.manager.host}";
private static final String DAS_URL = DEFAULT_HTTP_PROTOCOL + "://" + DAS_HOST_NAME
+ ":" + DAS_PORT + "/services/CarbonAppUploader" + "/";
private static final String IOT_MGT_URL = DEFAULT_HTTP_PROTOCOL + "://" + IOT_MGT_HOST_NAME
+ ":" + IOT_MGT_PORT + "/services/CarbonAppUploader" + "/";
private static final String MEDIA_TYPE_XML = "application/xml";
private static final String DEVICE_MANAGEMENT_TYPE = "device_management";
@Override
@POST
@Path("/deploy/{type}")
public Response doPublish(@PathParam("type") String type) {
try {
//Getting the tenant Domain
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
String tenantAdminUser = username + "@" + tenantDomain;
String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password");
String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty(
"Security.TrustStore.Password");
String keyStoreLocation = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Location");
String trustStoreLocation = ServerConfiguration.getInstance().getFirstProperty(
"Security.TrustStore.Location");
//Call to load the keystore.
loadKeyStore(keyStoreLocation, keyStorePassword);
//Call to load the TrustStore.
loadTrustStore(trustStoreLocation, trustStorePassword);
//Create the SSL context with the loaded TrustStore/keystore.
initSSLConnection();
JWTClient jwtClient = DeviceMgtAPIUtils.getJWTClientManagerService().getJWTClient();
String authValue = AUTHORIZATION_HEADER_VALUE + " " + new String(Base64.encodeBase64(
jwtClient.getJwtToken(tenantAdminUser).getBytes()));
List<Header> list = new ArrayList<Header>();
Header httpHeader = new Header();
httpHeader.setName(AUTHORIZATION_HEADER);
httpHeader.setValue(authValue);
list.add(httpHeader);//"https"
File directory = new File(CAR_FILE_LOCATION + File.separator + type);
if (directory.isDirectory() && directory.exists()) {
UploadedFileItem[] uploadedFileItems = loadCappFromFileSystem(type);
if (uploadedFileItems.length > 0) {
CarbonAppUploaderStub carbonAppUploaderStub = new CarbonAppUploaderStub(Utils.replaceSystemProperty(
IOT_MGT_URL));
Options appUploaderOptions = carbonAppUploaderStub._getServiceClient().getOptions();
if (appUploaderOptions == null) {
appUploaderOptions = new Options();
}
appUploaderOptions.setProperty(HTTPConstants.HTTP_HEADERS, list);
appUploaderOptions.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER
, new Protocol(DEFAULT_HTTP_PROTOCOL, (ProtocolSocketFactory) new SSLProtocolSocketFactory
(sslContext), Integer.parseInt(Utils.replaceSystemProperty(IOT_MGT_PORT))));
carbonAppUploaderStub._getServiceClient().setOptions(appUploaderOptions);
carbonAppUploaderStub.uploadApp(uploadedFileItems);
if (!DEVICE_MANAGEMENT_TYPE.equals(type.toLowerCase())) {
carbonAppUploaderStub = new CarbonAppUploaderStub(Utils.replaceSystemProperty(DAS_URL));
appUploaderOptions = carbonAppUploaderStub._getServiceClient().getOptions();
if (appUploaderOptions == null) {
appUploaderOptions = new Options();
}
appUploaderOptions.setProperty(HTTPConstants.HTTP_HEADERS, list);
appUploaderOptions.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER
, new Protocol(DEFAULT_HTTP_PROTOCOL
, (ProtocolSocketFactory) new SSLProtocolSocketFactory(sslContext)
, Integer.parseInt(Utils.replaceSystemProperty(DAS_PORT))));
carbonAppUploaderStub._getServiceClient().setOptions(appUploaderOptions);
carbonAppUploaderStub.uploadApp(uploadedFileItems);
}
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Registry registry = DeviceMgtAPIUtils.getRegistryService().getConfigSystemRegistry(tenantId);
if (!registry.resourceExists(DEFAULT_RESOURCE_LOCATION + type + ".exist")) {
Resource resource = new ResourceImpl();
resource.setContent("</exist>");
resource.setMediaType(MEDIA_TYPE_XML);
registry.put(DEFAULT_RESOURCE_LOCATION + type + ".exist", resource);
}
}
} else {
return Response.status(Response.Status.BAD_REQUEST)
.entity("\"Error, Artifact does not exist.\"").build();
}
} catch (Exception e) {
log.error("Capp deployment failed due to " + e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
"\"Error, Artifact deployment has failed\"").build();
}
return Response.status(Response.Status.CREATED).entity("\"OK. \\n Successfully uploaded the artifacts.\"")
.build();
}
@GET
@Path("/deploy/{type}/status")
@Override
public Response getStatus(@PathParam("type") String deviceType) {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Registry registry = null;
try {
registry = DeviceMgtAPIUtils.getRegistryService().getConfigSystemRegistry(tenantId);
if (registry.resourceExists(DEFAULT_RESOURCE_LOCATION + deviceType + ".exist")) {
return Response.status(Response.Status.OK).entity("Exist").build();
} else {
return Response.status(Response.Status.NO_CONTENT).entity("Does not Exist").build();
}
} catch (RegistryException e) {
log.error("Registry failed to load." + e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
"\"Error, Artifact status check has failed\"").build();
}
}
private UploadedFileItem[] loadCappFromFileSystem(String deviceType) throws IOException {
File directory = new File(CAR_FILE_LOCATION + File.separator + deviceType);
File[] carFiles = directory.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".car");
}
});
List<UploadedFileItem> uploadedFileItemLis = new ArrayList<>();
if (carFiles != null) {
for (File carFile : carFiles) {
UploadedFileItem uploadedFileItem = new UploadedFileItem();
DataHandler param = new DataHandler(carFile.toURI().toURL());
uploadedFileItem.setDataHandler(param);
uploadedFileItem.setFileName(carFile.getName());
uploadedFileItem.setFileType("jar");
uploadedFileItemLis.add(uploadedFileItem);
}
}
UploadedFileItem[] fileItems = new UploadedFileItem[uploadedFileItemLis.size()];
fileItems = uploadedFileItemLis.toArray(fileItems);
return fileItems;
}
/**
* Loads the keystore.
*
* @param keyStorePath - the path of the keystore
* @param ksPassword - the keystore password
*/
private void loadKeyStore(String keyStorePath, String ksPassword)
throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
InputStream fis = null;
try {
keyStorePassword = ksPassword.toCharArray();
keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
fis = new FileInputStream(keyStorePath);
keyStore.load(fis, keyStorePassword);
} finally {
if (fis != null) {
fis.close();
}
}
}
/**
* Loads the trustore
*
* @param trustStorePath - the trustore path in the filesystem.
* @param tsPassword - the truststore password
*/
private void loadTrustStore(String trustStorePath, String tsPassword)
throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
InputStream fis = null;
try {
trustStore = KeyStore.getInstance(TRUST_STORE_TYPE);
fis = new FileInputStream(trustStorePath);
trustStore.load(fis, tsPassword.toCharArray());
} finally {
if (fis != null) {
fis.close();
}
}
}
/**
* Initializes the SSL Context
*/
private void initSSLConnection() throws NoSuchAlgorithmException, UnrecoverableKeyException,
KeyStoreException, KeyManagementException {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
keyManagerFactory.init(keyStore, keyStorePassword);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
trustManagerFactory.init(trustStore);
// Create and initialize SSLContext for HTTPS communication
sslContext = SSLContext.getInstance(SSLV3);
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
SSLContext.setDefault(sslContext);
}
}

@ -29,7 +29,6 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementService;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService;
@ -37,13 +36,22 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
import org.wso2.carbon.identity.user.store.count.AbstractCountRetrieverFactory;
import org.wso2.carbon.identity.user.store.count.UserStoreCountRetriever;
import org.wso2.carbon.identity.user.store.count.exception.UserStoreCounterException;
import org.wso2.carbon.identity.user.store.count.jdbc.JDBCCountRetrieverFactory;
import org.wso2.carbon.identity.user.store.count.jdbc.internal.InternalCountRetrieverFactory;
import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.api.AuthorizationManager;
import org.wso2.carbon.user.api.RealmConfiguration;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager;
import org.wso2.carbon.user.core.service.RealmService;
import javax.ws.rs.core.MediaType;
@ -105,6 +113,32 @@ public class DeviceMgtAPIUtils {
return deviceManagementProviderService;
}
public static UserStoreCountRetriever getUserStoreCountRetrieverService()
throws UserStoreCounterException {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
List<Object> countRetrieverFactories = ctx.getOSGiServices(AbstractCountRetrieverFactory.class, null);
RealmService realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
RealmConfiguration realmConfiguration = realmService.getBootstrapRealmConfiguration();
String userStoreType;
//Ignoring Sonar warning as getUserStoreClass() returning string name of the class. So cannot use 'instanceof'.
if (JDBCUserStoreManager.class.getName().equals(realmConfiguration.getUserStoreClass())) {
userStoreType = JDBCCountRetrieverFactory.JDBC;
} else {
userStoreType = InternalCountRetrieverFactory.INTERNAL;
}
AbstractCountRetrieverFactory countRetrieverFactory = null;
for (Object countRetrieverFactoryObj : countRetrieverFactories) {
countRetrieverFactory = (AbstractCountRetrieverFactory) countRetrieverFactoryObj;
if (userStoreType.equals(countRetrieverFactory.getCounterType())) {
break;
}
}
if (countRetrieverFactory == null) {
return null;
}
return countRetrieverFactory.buildCountRetriever(realmConfiguration);
}
public static DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceAccessAuthorizationService deviceAccessAuthorizationService =
@ -156,6 +190,30 @@ public class DeviceMgtAPIUtils {
return realmService;
}
public static RegistryService getRegistryService() {
RegistryService registryService;
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
registryService = (RegistryService) ctx.getOSGiService(RegistryService.class, null);
if (registryService == null) {
String msg = "registry service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return registryService;
}
public static JWTClientManagerService getJWTClientManagerService() {
JWTClientManagerService jwtClientManagerService;
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
jwtClientManagerService = (JWTClientManagerService) ctx.getOSGiService(JWTClientManagerService.class, null);
if (jwtClientManagerService == null) {
String msg = "jwtClientManagerServicehas not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return jwtClientManagerService;
}
/**
* Getting the current tenant's user realm
*/
@ -262,16 +320,6 @@ public class DeviceMgtAPIUtils {
return gadgetDataService;
}
public static ScopeManagementService getScopeManagementService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ScopeManagementService scopeManagementService =
(ScopeManagementService) ctx.getOSGiService(ScopeManagementService.class, null);
if (scopeManagementService == null) {
throw new IllegalStateException("Scope Management Service has not been initialized.");
}
return scopeManagementService;
}
public static int getTenantId(String tenantDomain) throws DeviceManagementException {
RealmService realmService =
(RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(RealmService.class, null);

@ -18,7 +18,7 @@
package org.wso2.carbon.device.mgt.jaxrs.util;
import org.wso2.carbon.apimgt.api.model.Scope;
import org.wso2.carbon.device.mgt.core.config.permission.Scope;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorListItem;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.ProfileFeature;

@ -39,6 +39,8 @@
<ref bean="groupManagementAdminService"/>
<ref bean="applicationManagementAdminService"/>
<ref bean="deviceTypeManagementAdminService"/>
<ref bean="deviceTypeManagementAdminService"/>
<ref bean="deviceTypePublisherAdminServiceImpl"/>
<ref bean="swaggerResource"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
@ -80,6 +82,8 @@
<bean id="userManagementAdminService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.UserManagementAdminServiceImpl"/>
<bean id="deviceTypeManagementAdminService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.DeviceTypeManagementServiceImpl"/>
<bean id="deviceAccessAuthorizationAdminService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.DeviceAccessAuthorizationAdminServiceImpl"/>
<bean id="deviceTypePublisherAdminServiceImpl" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.DeviceTypePublisherAdminServiceImpl"/>
<bean id="jsonProvider" class="org.wso2.carbon.device.mgt.jaxrs.common.GsonMessageBodyHandler"/>
<!--<bean id="errorHandler" class="org.wso2.carbon.device.mgt.jaxrs.common.ErrorHandler"/>-->

@ -21,7 +21,7 @@
<parent>
<artifactId>device-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
@ -50,7 +50,6 @@
<Import-Package>
javax.xml.bind.annotation; version="${javax.xml.bind.imp.pkg.version}",
com.fasterxml.jackson.annotation;version="${jackson-annotations.version}",
org.wso2.carbon.apimgt.api.model.*;version="${carbon.api.mgt.version.range}",
io.swagger.annotations; version="${swagger.annotations.version}"; resolution:=optional
</Import-Package>
</instructions>
@ -69,10 +68,6 @@
<groupId>org.wso2.orbit.com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.api</artifactId>
</dependency>
</dependencies>
</project>

@ -0,0 +1,36 @@
/*
* 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.common;
import java.util.List;
public class InitialOperationConfig {
private List<String> operations;
public List<String> getOperations() {
return operations;
}
public void setOperations(List<String> operations) {
this.operations = operations;
}
}

@ -1,57 +0,0 @@
/*
* Copyright (c) 2014, 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.device.mgt.common.scope.mgt;
/**
* This exception is used to throw when there is an issue in scope management service.
*/
public class ScopeManagementException extends Exception {
private static final long serialVersionUID = -315127931137779899L;
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public ScopeManagementException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public ScopeManagementException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public ScopeManagementException(String msg) {
super(msg);
setErrorMessage(msg);
}
public ScopeManagementException() {
super();
}
public ScopeManagementException(Throwable cause) {
super(cause);
}
}

@ -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.device.mgt.common.scope.mgt;
import java.util.List;
import org.wso2.carbon.apimgt.api.model.Scope;
/**
* This interface contains the basic operations related to scope management.
*/
public interface ScopeManagementService {
/**
* This method is used to update the given list of scopes.
*
* @param scopes List of scopes to be updated.
* @throws ScopeManagementException
*/
void updateScopes(List<Scope> scopes) throws ScopeManagementException;
/**
* This method is used to update the given list of scopes keys with the role name.
*
* @param scopeKeys List of scopes to be updated.
* @param roleName Role name
* @throws ScopeManagementException
*/
void updateScopes(List<String> scopeKeys, String roleName) throws ScopeManagementException;
/**
* This method is used to retrieve all the scopes.
*
* @return List of scopes.
* @throws ScopeManagementException
*/
List<Scope> getAllScopes() throws ScopeManagementException;
/**
* This method is to retrieve the roles of the given scope
* @param scopeKey key of the scope
* @return List of roles
* @throws ScopeManagementException
*/
String getRolesOfScope(String scopeKey) throws ScopeManagementException;
/**
* This method is to retrieve the scopes of the given role
* @param roleName key of the scope
* @return List of scopes
* @throws ScopeManagementException
*/
List<Scope> getScopesOfRole(String roleName) throws ScopeManagementException;
/**
* This method is used to remove the scopes of a given user role.
*
* @param roleName Role name
* @throws ScopeManagementException
*/
void removeScopes(String roleName) throws ScopeManagementException;
}

@ -25,7 +25,7 @@ import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "Condition", description = "Contains the advance search parameters.")
public class Condition {
@ApiModelProperty(name = "conditions", value = "Provide the operation code. You can assign the following operation " +
@ApiModelProperty(name = "key", value = "Provide the operation code. You can assign the following operation " +
"codes:\n" +
"DEVICE_MODEL : The model of the device.\n" +
"VENDOR : The name of the device vendor.\n" +

@ -18,10 +18,7 @@
*/
package org.wso2.carbon.device.mgt.common.spi;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
@ -48,4 +45,8 @@ public interface DeviceManagementService {
PolicyMonitoringManager getPolicyMonitoringManager();
InitialOperationConfig getInitialOperationConfig();
}

@ -22,7 +22,7 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>device-mgt</artifactId>
<version>2.0.18-SNAPSHOT</version>
<version>2.0.37-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
@ -77,7 +77,6 @@
org.wso2.carbon.identity.oauth.stub,
org.wso2.carbon.identity.oauth.stub.dto,
org.wso2.carbon.ndatasource.core,
org.wso2.carbon.apimgt.impl,
org.wso2.carbon.ntask.core.*,
org.wso2.carbon.ntask.common,
org.apache.catalina,
@ -86,7 +85,8 @@
org.wso2.carbon.email.sender.*,
io.swagger.annotations.*;resolution:=optional,
org.wso2.carbon,
org.wso2.carbon.base
org.wso2.carbon.base,
org.scannotation.*
</Import-Package>
<Export-Package>
!org.wso2.carbon.device.mgt.core.internal,
@ -94,7 +94,8 @@
</Export-Package>
<Embed-Dependency>
javax.ws.rs-api,
scribe;scope=compile|runtime;inline=false;
scribe;scope=compile|runtime;inline=false,
javassist;inline=false
</Embed-Dependency>
<DynamicImport-Package>*</DynamicImport-Package>
</instructions>
@ -124,6 +125,10 @@
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.orbit.org.scannotation</groupId>
<artifactId>scannotation</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
@ -203,34 +208,6 @@
<groupId>org.apache.ws.commons.axiom.wso2</groupId>
<artifactId>axiom</artifactId>
</dependency-->
<dependency>
<groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.api</artifactId>
<exclusions>
<exclusion>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.user.mgt.stub</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.user.mgt</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.impl</artifactId>
<exclusions>
<exclusion>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.user.mgt.stub</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.user.mgt</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
@ -281,12 +258,6 @@
<artifactId>swagger-annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.orbit.org.scannotation</groupId>
<artifactId>scannotation</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
@ -296,12 +267,14 @@
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
</dependency>
</dependencies>
</project>

@ -19,11 +19,9 @@
package org.wso2.carbon.device.mgt.core.config.permission;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.models.Swagger;
import org.apache.catalina.core.StandardContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.model.Scope;
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import javax.servlet.ServletContext;
@ -80,7 +78,6 @@ public class AnnotationProcessor {
private Class<Path> pathClazz;
private ClassLoader classLoader;
private ServletContext servletContext;
private Swagger swagger;
private Class<SwaggerDefinition> apiClazz;
private Class<Consumes> consumesClass;
private Class<Produces> producesClass;

@ -30,11 +30,11 @@ public class ExtendedAnnotationDB extends AnnotationDB {
}
public void scanArchives(URL... urls) throws IOException {
URL[] arr$ = urls;
int len$ = urls.length;
URL[] arr = urls;
int len = urls.length;
for(int i$ = 0; i$ < len$; ++i$) {
URL url = arr$[i$];
for(int i = 0; i < len; ++i) {
URL url = arr[i];
Filter filter = new Filter() {
public boolean accepts(String filename) {
if(filename.endsWith(".class")) {
@ -60,16 +60,16 @@ public class ExtendedAnnotationDB extends AnnotationDB {
}
private boolean ignoreScan(String intf) {
String[] arr$;
int len$;
int i$;
String[] arr;
int len;
int i;
String ignored;
if(this.scanPackages != null) {
arr$ = this.scanPackages;
len$ = arr$.length;
arr = this.scanPackages;
len = arr.length;
for(i$ = 0; i$ < len$; ++i$) {
ignored = arr$[i$];
for(i = 0; i < len; ++i) {
ignored = arr[i];
if(intf.startsWith(ignored + ".")) {
return false;
}
@ -77,11 +77,11 @@ public class ExtendedAnnotationDB extends AnnotationDB {
return true;
} else {
arr$ = this.ignoredPackages;
len$ = arr$.length;
arr = this.ignoredPackages;
len = arr.length;
for(i$ = 0; i$ < len$; ++i$) {
ignored = arr$[i$];
for(i = 0; i < len; ++i) {
ignored = arr[i];
if(intf.startsWith(ignored + ".")) {
return true;
}

@ -0,0 +1,70 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.device.mgt.core.config.permission;
import java.io.Serializable;
public class Scope implements Serializable {
String key;
String name;
String roles;
String description;
int id;
public Scope() {
}
public String getKey() {
return this.key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getRoles() {
return this.roles;
}
public void setRoles(String roles) {
this.roles = roles;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
}

@ -83,7 +83,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
try {
conn = this.getConnection();
String sql = "UPDATE DM_DEVICE SET NAME = ?, DESCRIPTION = ?, LAST_UPDATED_TIMESTAMP = ? " +
"WHERE DEVICE_TYPE_ID = (SELECT ID FROM DM_DEVICE_TYPE WHERE NAME = ? AND PROVIDER_TENANT_ID = ?) " +
"WHERE DEVICE_TYPE_ID = (SELECT ID FROM DM_DEVICE_TYPE WHERE NAME = ? AND (PROVIDER_TENANT_ID = ? OR SHARED_WITH_ALL_TENANTS = ?)) " +
"AND DEVICE_IDENTIFICATION = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql, new String[] {"id"});
stmt.setString(1, device.getName());
@ -91,8 +91,9 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
stmt.setTimestamp(3, new Timestamp(new Date().getTime()));
stmt.setString(4, device.getType());
stmt.setInt(5, tenantId);
stmt.setString(6, device.getDeviceIdentifier());
stmt.setInt(7, tenantId);
stmt.setBoolean(6, true);
stmt.setString(7, device.getDeviceIdentifier());
stmt.setInt(8, tenantId);
rows = stmt.executeUpdate();
return (rows > 0);
} catch (SQLException e) {

@ -18,7 +18,6 @@
package org.wso2.carbon.device.mgt.core.internal;
import org.wso2.carbon.apimgt.impl.APIManagerConfiguration;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
@ -63,17 +62,10 @@ public class DeviceManagementDataHolder {
private Map<String, OperationMonitoringTaskConfig> map = new HashMap<>();
public void addToMap(OperationMonitoringTaskConfig taskConfig) {
this.map.put("aa", taskConfig);
}
public Map<String, OperationMonitoringTaskConfig> getMap(){
return this.map;
}
private APIManagerConfiguration apiManagerConfiguration;
private DeviceManagementDataHolder() {}
public static DeviceManagementDataHolder getInstance() {

@ -21,7 +21,6 @@ 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.impl.APIManagerConfigurationService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
@ -84,12 +83,6 @@ import java.util.List;
* policy="dynamic"
* bind="setRegistryService"
* unbind="unsetRegistryService"
* @scr.reference name="api.manager.config.service"
* interface="org.wso2.carbon.apimgt.impl.APIManagerConfigurationService"
* cardinality="1..1"
* policy="dynamic"
* bind="setAPIManagerConfigurationService"
* unbind="unsetAPIManagerConfigurationService"
* @scr.reference name="org.wso2.carbon.ndatasource"
* interface="org.wso2.carbon.ndatasource.core.DataSourceService"
* cardinality="1..1"
@ -355,14 +348,6 @@ public class DeviceManagementServiceComponent {
DeviceManagementDataHolder.getInstance().setRegistryService(null);
}
protected void setAPIManagerConfigurationService(APIManagerConfigurationService service) {
//do nothing
}
protected void unsetAPIManagerConfigurationService(APIManagerConfigurationService service) {
//do nothing
}
protected void setDataSourceService(DataSourceService dataSourceService) {
/* This is to avoid mobile device management component getting initialized before the underlying datasources
are registered */
@ -404,13 +389,13 @@ public class DeviceManagementServiceComponent {
}
protected void setDeviceTaskManagerService(DeviceTaskManagerService emailSenderService) {
protected void setDeviceTaskManagerService(DeviceTaskManagerService deviceTaskManagerService) {
if (log.isDebugEnabled()) {
}
DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(emailSenderService);
DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(deviceTaskManagerService);
}
protected void unsetDeviceTaskManagerService(DeviceTaskManagerService emailSenderService) {
protected void unsetDeviceTaskManagerService(DeviceTaskManagerService deviceTaskManagerService) {
if (log.isDebugEnabled()) {
}
DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(null);

@ -317,5 +317,4 @@ public interface DeviceManagementProviderService {
*/
boolean changeDeviceStatus(DeviceIdentifier deviceIdentifier, EnrolmentInfo.Status newStatus)
throws DeviceManagementException;
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save