merged web app publisher code and refactored jwt client extension to adhere to new artefact name

revert-70aa11f8
ayyoob 9 years ago
parent 576509e50f
commit 1b4a9227d8

@ -1,5 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<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"> <!--
~ 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> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
@ -61,6 +81,30 @@
<groupId>org.apache.axis2.wso2</groupId> <groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId> <artifactId>axis2</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.orbit.org.scannotation</groupId>
<artifactId>scannotation</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.governance</groupId>
<artifactId>org.wso2.carbon.governance.api</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.governance</groupId>
<artifactId>org.wso2.carbon.governance.lcm</artifactId>
</dependency>
</dependencies> </dependencies>
@ -81,7 +125,8 @@
<Bundle-Name>${project.artifactId}</Bundle-Name> <Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version> <Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
<Bundle-Description>API Management Webapp Publisher</Bundle-Description> <Bundle-Description>API Management Webapp Publisher</Bundle-Description>
<Private-Package>org.wso2.carbon.apimgt.webapp.publisher.internal</Private-Package> <Private-Package>org.wso2.carbon.apimgt.webapp.publisher.internal
</Private-Package>
<Export-Package> <Export-Package>
!org.wso2.carbon.apimgt.webapp.publisher.internal, !org.wso2.carbon.apimgt.webapp.publisher.internal,
org.wso2.carbon.apimgt.webapp.publisher.* org.wso2.carbon.apimgt.webapp.publisher.*
@ -91,7 +136,8 @@
org.osgi.service.component, org.osgi.service.component,
org.apache.commons.logging, org.apache.commons.logging,
javax.servlet, javax.servlet,
javax.xml.bind.annotation, javax.xml.*,
com.google.gson.*,
org.apache.catalina, org.apache.catalina,
org.apache.catalina.core, org.apache.catalina.core,
org.wso2.carbon.apimgt.api, org.wso2.carbon.apimgt.api,
@ -99,8 +145,16 @@
org.wso2.carbon.apimgt.impl, org.wso2.carbon.apimgt.impl,
org.apache.axis2.*;version="${axis2.osgi.version.range}", org.apache.axis2.*;version="${axis2.osgi.version.range}",
org.wso2.carbon.core, org.wso2.carbon.core,
org.wso2.carbon.utils org.apache.commons.lang,
org.wso2.carbon.utils,
org.wso2.carbon.apimgt.annotations.*,
org.wso2.carbon.governance.lcm.util.*,
org.wso2.carbon.registry.core.*
</Import-Package> </Import-Package>
<Embed-Dependency>
scribe;scope=compile|runtime;inline=false;
</Embed-Dependency>
<DynamicImport-Package>*</DynamicImport-Package>
</instructions> </instructions>
</configuration> </configuration>
</plugin> </plugin>

@ -20,11 +20,16 @@ package org.wso2.carbon.apimgt.webapp.publisher;
import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIProvider; 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.apimgt.impl.APIManagerFactory;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlTransient;
import java.util.List;
import java.util.Set;
/** /**
* This bean class carries the properties used by some API that needs to be published within the underlying * This bean class carries the properties used by some API that needs to be published within the underlying
@ -48,20 +53,35 @@ public class APIConfig {
private String name; private String name;
private String owner; private String owner;
private String context; private String context;
private String contextTemplate;
private String endpoint; private String endpoint;
private String version; private String version;
private String transports; private String transports;
private APIProvider provider; private APIProvider provider;
private boolean isSecured; private boolean isSecured;
private Set<URITemplate> uriTemplates;
private List<String> tenants;
private boolean isSharedWithAllTenants;
private String tenantDomain;
private String[] tags;
public void init() throws APIManagementException { public void init() throws APIManagementException {
try { try {
this.provider = APIManagerFactory.getInstance().getAPIProvider(this.getOwner()); this.provider = APIManagerFactory.getInstance().getAPIProvider(owner);
} catch (APIManagementException e) { } catch (APIManagementException e) {
throw new APIManagementException("Error occurred while initializing API provider", e); throw new APIManagementException("Error occurred while initializing API provider", e);
} }
} }
@XmlElement(name = "ContextTemplate", required = true)
public String getContextTemplate() {
return contextTemplate;
}
public void setContextTemplate(String contextTemplate) {
this.contextTemplate = contextTemplate;
}
@XmlTransient @XmlTransient
public APIProvider getProvider() { public APIProvider getProvider() {
return provider; return provider;
@ -136,4 +156,43 @@ public class APIConfig {
isSecured = secured; isSecured = secured;
} }
@XmlElement(name = "UriTemplates", required = false)
public Set<URITemplate> getUriTemplates() {
return uriTemplates;
}
@SuppressWarnings("unused")
public void setUriTemplates(Set<URITemplate> uriTemplates) {
this.uriTemplates = uriTemplates;
}
@XmlElement(name = "isSharedWithAllTenants", required = false)
public boolean isSharedWithAllTenants() {
return isSharedWithAllTenants;
}
@SuppressWarnings("unused")
public void setSharedWithAllTenants(boolean isSharedWithAllTenants) {
this.isSharedWithAllTenants = isSharedWithAllTenants;
}
@XmlElement(name = "tenantDomain", required = false)
public String getTenantDomain() {
return tenantDomain;
}
@SuppressWarnings("unused")
public void setTenantDomain(String tenantDomain) {
this.tenantDomain = tenantDomain;
}
@XmlElement(name = "tags", required = false)
public String[] getTags() {
return tags;
}
@SuppressWarnings("unused")
public void setTags(String[] tags) {
this.tags = tags;
}
} }

@ -19,9 +19,9 @@
package org.wso2.carbon.apimgt.webapp.publisher; package org.wso2.carbon.apimgt.webapp.publisher;
import org.wso2.carbon.apimgt.api.APIManagementException; 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.API;
import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import java.util.List; import java.util.List;
/** /**
@ -39,7 +39,7 @@ public interface APIPublisherService {
* @param api An instance of the bean that passes metadata related to the API being published * @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 * @throws APIManagementException Is thrown if some unexpected event occurs while publishing the API
*/ */
void publishAPI(API api) throws APIManagementException; void publishAPI(API api) throws APIManagementException, FaultGatewaysException;
/** /**
* This method removes an API that's already published within the underlying API-Management infrastructure. * This method removes an API that's already published within the underlying API-Management infrastructure.
@ -55,6 +55,5 @@ public interface APIPublisherService {
* @param apis A list of the beans that passes metadata related to the APIs being published * @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 * @throws APIManagementException Is thrown if some unexpected event occurs while publishing the APIs
*/ */
void publishAPIs(List<API> apis) throws APIManagementException; void publishAPIs(List<API> apis) throws APIManagementException, FaultGatewaysException;
} }

@ -18,6 +18,7 @@
*/ */
package org.wso2.carbon.apimgt.webapp.publisher; package org.wso2.carbon.apimgt.webapp.publisher;
import com.google.gson.JsonObject;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIManagementException;
@ -25,8 +26,17 @@ import org.wso2.carbon.apimgt.api.APIProvider;
import org.wso2.carbon.apimgt.api.FaultGatewaysException; import org.wso2.carbon.apimgt.api.FaultGatewaysException;
import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import org.wso2.carbon.apimgt.api.model.URITemplate;
import org.wso2.carbon.apimgt.impl.APIManagerFactory; import org.wso2.carbon.apimgt.impl.APIManagerFactory;
import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
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.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.xml.stream.XMLStreamException;
import java.io.FileNotFoundException;
import java.util.List; import java.util.List;
/** /**
@ -38,33 +48,82 @@ public class APIPublisherServiceImpl implements APIPublisherService {
private static final Log log = LogFactory.getLog(APIPublisherServiceImpl.class); private static final Log log = LogFactory.getLog(APIPublisherServiceImpl.class);
@Override @Override
public void publishAPI(API api) throws APIManagementException { public void publishAPI(API api) throws APIManagementException, FaultGatewaysException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Publishing API '" + api.getId() + "'"); log.debug("Publishing API '" + api.getId() + "'");
} }
APIProvider provider = APIManagerFactory.getInstance().getAPIProvider(api.getApiOwner()); try {
if (provider != null) { String tenantDomain = MultitenantUtils.getTenantDomain(api.getApiOwner());
if (!provider.isAPIAvailable(api.getId())) { int tenantId =
provider.addAPI(api); APIPublisherDataHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
log.info("Successfully published API '" + api.getId().getApiName() + "' with context '" + // Below code snippet is added load API Lifecycle in tenant mode, where in it does not load when tenant is loaded.
api.getContext() + "' and version '" + api.getId().getVersion() + "'"); RegistryService registryService = APIPublisherDataHolder.getInstance().getRegistryService();
} else { CommonUtil.addDefaultLifecyclesIfNotAvailable(registryService.getConfigSystemRegistry(tenantId),
try { CommonUtil.getRootSystemRegistry(tenantId));
APIProvider provider = APIManagerFactory.getInstance().getAPIProvider(api.getApiOwner());
MultitenantUtils.getTenantDomain(api.getApiOwner());
if (provider != null) {
if (!provider.isAPIAvailable(api.getId())) {
provider.addAPI(api);
log.info("Successfully published API '" + api.getId().getApiName() + "' with context '" +
api.getContext() + "' and version '" + api.getId().getVersion() + "'");
} else {
provider.updateAPI(api); provider.updateAPI(api);
log.info("An API already exists with the name '" + api.getId().getApiName() + "', context '" + log.info("An API already exists with the name '" + api.getId().getApiName() + "', context '" +
api.getContext() + "' and version '" + api.getId().getVersion() + api.getContext() + "' and version '" + api.getId().getVersion() +
"'. Thus, the API config is updated"); "'. Thus, the API config is updated");
} catch (FaultGatewaysException e) {
throw new APIManagementException("Error occurred while updating API " + api.getId().getApiName() +
"' with context '" + api.getContext() + "' and version '" + api.getId().getVersion() + "'");
} }
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");
} }
} else { } catch (UserStoreException e) {
throw new APIManagementException("API provider configured for the given API configuration is null. " + throw new APIManagementException("Failed to get the tenant id for the user " + api.getApiOwner(), e);
"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);
} }
} }
private String createSwaggerDefinition(API api) {
//{"paths":{"/controller/*":{"get":{"responses":{"200":{}}}},"/manager/*":{"get":{"responses":{"200":{}}}}},
// "swagger":"2.0","info":{"title":"RaspberryPi","version":"1.0.0"}}
JsonObject swaggerDefinition = new JsonObject();
JsonObject paths = new JsonObject();
for (URITemplate uriTemplate : api.getUriTemplates()) {
JsonObject response = new JsonObject();
response.addProperty("200", "");
JsonObject responses = new JsonObject();
responses.add("responses", response);
JsonObject httpVerb = new JsonObject();
httpVerb.add(uriTemplate.getHTTPVerb().toLowerCase(), responses);
JsonObject path = new JsonObject();
path.add(uriTemplate.getUriTemplate(), httpVerb);
paths.add(uriTemplate.getUriTemplate(), httpVerb);
}
swaggerDefinition.add("paths", paths);
swaggerDefinition.addProperty("swagger", "2.0");
JsonObject info = new JsonObject();
info.addProperty("title", api.getId().getApiName());
info.addProperty("version", api.getId().getVersion());
swaggerDefinition.add("info", info);
return swaggerDefinition.toString();
//return "{\"paths\":{\"/controller/*\":{\"get\":{\"responses\":{\"200\":{}}}},
// \"/manager/*\":{\"get\":{\"responses\":{\"200\":{}}}}},\"swagger\":\"2.0\",
// \"info\":{\"title\":\"RaspberryPi\",\"version\":\"1.0.0\"}}";
}
@Override @Override
public void removeAPI(APIIdentifier id) throws APIManagementException { public void removeAPI(APIIdentifier id) throws APIManagementException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -78,7 +137,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
} }
@Override @Override
public void publishAPIs(List<API> apis) throws APIManagementException { public void publishAPIs(List<API> apis) throws APIManagementException, FaultGatewaysException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Publishing a batch of APIs"); log.debug("Publishing a batch of APIs");
} }
@ -93,5 +152,4 @@ public class APIPublisherServiceImpl implements APIPublisherService {
log.debug("End of publishing the batch of APIs"); log.debug("End of publishing the batch of APIs");
} }
} }
} }

@ -1,42 +1,43 @@
/* /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* *
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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; package org.wso2.carbon.apimgt.webapp.publisher;
import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIProvider; import org.wso2.carbon.apimgt.api.APIProvider;
import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.*;
import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import org.wso2.carbon.apimgt.api.model.APIStatus;
import org.wso2.carbon.apimgt.api.model.URITemplate;
import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.user.api.TenantManager;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.ConfigurationContextService;
import org.wso2.carbon.utils.NetworkUtils; import org.wso2.carbon.utils.NetworkUtils;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.util.ArrayList; import java.util.*;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class APIPublisherUtil { public class APIPublisherUtil {
private static final String DEFAULT_API_VERSION = "1.0.0";
public static final String API_VERSION_PARAM="{version}";
enum HTTPMethod { enum HTTPMethod {
GET, POST, DELETE, PUT, OPTIONS GET, POST, DELETE, PUT, OPTIONS
} }
@ -54,21 +55,53 @@ public class APIPublisherUtil {
public static API getAPI(APIConfig config) throws APIManagementException { public static API getAPI(APIConfig config) throws APIManagementException {
APIProvider provider = config.getProvider(); APIProvider provider = config.getProvider();
APIIdentifier id = new APIIdentifier(config.getOwner(), config.getName(), config.getVersion()); String apiVersion = config.getVersion();
APIIdentifier id = new APIIdentifier(replaceEmailDomain(config.getOwner()), config.getName(), apiVersion);
API api = new API(id); API api = new API(id);
api.setApiOwner(config.getOwner()); api.setApiOwner(config.getOwner());
api.setContext(config.getContext()); 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.setUrl(config.getEndpoint());
api.setUriTemplates(
getURITemplates(config.getEndpoint(), APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN));
api.setVisibility(APIConstants.API_GLOBAL_VISIBILITY);
api.addAvailableTiers(provider.getTiers()); api.addAvailableTiers(provider.getTiers());
api.setEndpointSecured(true); api.setEndpointSecured(true);
api.setStatus(APIStatus.PUBLISHED); api.setStatus(APIStatus.PUBLISHED);
api.setTransports(config.getTransports()); api.setTransports(config.getTransports());
api.setAsDefaultVersion(true); api.setContextTemplate(config.getContextTemplate());
api.setAsPublishedDefaultVersion(true); api.setUriTemplates(config.getUriTemplates());
Set<Tier> tiers = new HashSet<Tier>();
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},\"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);
}
return api; return api;
} }
@ -125,4 +158,35 @@ public class APIPublisherUtil {
return getServerBaseUrl() + context; 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;
}
} }

@ -0,0 +1,87 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.webapp.publisher.config;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Resource")
public class APIResource{
private String AuthType;
private String HttpVerb;
private String Uri;
private String UriTemplate;
private String consumes;
private String produces;
public String getAuthType() {
return AuthType;
}
@XmlElement(name = "AuthType", required = true)
public void setAuthType(String authType) {
AuthType = authType;
}
public String getHttpVerb() {
return HttpVerb;
}
@XmlElement(name = "HttpVerb", required = true)
public void setHttpVerb(String httpVerb) {
HttpVerb = httpVerb;
}
public String getUri() {
return Uri;
}
@XmlElement(name = "Uri", required = true)
public void setUri(String uri) {
Uri = uri;
}
public String getUriTemplate() {
return UriTemplate;
}
@XmlElement(name = "UriTemplate", required = true)
public void setUriTemplate(String uriTemplate) {
UriTemplate = uriTemplate;
}
public String getConsumes() {
return consumes;
}
@XmlElement(name = "Consumes", required = true)
public void setConsumes(String consumes) {
this.consumes = consumes;
}
public String getProduces() {
return produces;
}
@XmlElement(name = "Produces", required = true)
public void setProduces(String produces) {
this.produces = produces;
}
}

@ -0,0 +1,79 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.webapp.publisher.config;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement(name = "ResourceConfiguration")
public class APIResourceConfiguration {
private String name;
private String context;
private String version;
private List<APIResource> resources;
private String[] tags;
public List<APIResource> getResources() {
return resources;
}
@XmlElement(name = "Resources", required = true)
public void setResources(List<APIResource> resources) {
this.resources = resources;
}
public String getContext() {
return context;
}
@XmlElement(name = "Context", required = true)
public void setContext(String context) {
this.context = context;
}
public String getName() {
return name;
}
@XmlElement(name = "Name")
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
@XmlElement(name = "Version")
public void setVersion(String version) {
this.version = version;
}
public String[] getTags() {
return tags;
}
@XmlElement(name = "Tags")
public void setTags(String[] tags) {
this.tags = tags;
}
}

@ -0,0 +1,38 @@
package org.wso2.carbon.apimgt.webapp.publisher.config;
public class APIResourceManagementException extends Exception{
private static final long serialVersionUID = -3151279311929070297L;
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public APIResourceManagementException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public APIResourceManagementException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public APIResourceManagementException(String msg) {
super(msg);
setErrorMessage(msg);
}
public APIResourceManagementException() {
super();
}
public APIResourceManagementException(Throwable cause) {
super(cause);
}
}

@ -0,0 +1,69 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.webapp.publisher.config;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.InputStream;
import java.util.List;
import java.util.Set;
/**
* This class will add, update custom permissions defined in resources.xml in webapps.
*/
public class APIResourceManager {
private static APIResourceManager resourceManager;
private List<APIResource> resourceList;
private APIResourceManager(){};
public static APIResourceManager getInstance() {
if (resourceManager == null) {
synchronized (APIResourceManager.class) {
if (resourceManager == null) {
resourceManager = new APIResourceManager();
}
}
}
return resourceManager;
}
public void initializeResources(InputStream resourceStream) throws APIResourceManagementException {
try {
if(resourceStream != null){
/* Un-marshaling Device Management configuration */
JAXBContext cdmContext = JAXBContext.newInstance(APIResourceConfiguration.class);
Unmarshaller unmarshaller = cdmContext.createUnmarshaller();
APIResourceConfiguration resourcesConfiguration = (APIResourceConfiguration)
unmarshaller.unmarshal(resourceStream);
if((resourcesConfiguration != null) && (resourcesConfiguration.getResources() != null)){
this.resourceList = resourcesConfiguration.getResources();
}
}
} catch (JAXBException e) {
throw new APIResourceManagementException("Error occurred while initializing Data Source config", e);
}
}
public List<APIResource> getAPIResources(){
return resourceList;
}
}

@ -18,13 +18,20 @@
*/ */
package org.wso2.carbon.apimgt.webapp.publisher.internal; package org.wso2.carbon.apimgt.webapp.publisher.internal;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.core.tenant.TenantManager;
import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.ConfigurationContextService;
public class APIPublisherDataHolder { public class APIPublisherDataHolder {
private APIPublisherService apiPublisherService; private APIPublisherService apiPublisherService;
private ConfigurationContextService configurationContextService; private ConfigurationContextService configurationContextService;
private RealmService realmService;
private TenantManager tenantManager;
private RegistryService registryService;
private static APIPublisherDataHolder thisInstance = new APIPublisherDataHolder(); private static APIPublisherDataHolder thisInstance = new APIPublisherDataHolder();
@ -57,4 +64,34 @@ public class APIPublisherDataHolder {
return configurationContextService; return configurationContextService;
} }
public RealmService getRealmService() {
if (realmService == null) {
throw new IllegalStateException("Realm service is not initialized properly");
}
return realmService;
}
public void setRealmService(RealmService realmService) {
this.realmService = realmService;
this.setTenantManager(realmService);
}
private void setTenantManager(RealmService realmService) {
if (realmService == null) {
throw new IllegalStateException("Realm service is not initialized properly");
}
this.tenantManager = realmService.getTenantManager();
}
public TenantManager getTenantManager() {
return tenantManager;
}
public RegistryService getRegistryService() {
return registryService;
}
public void setRegistryService(RegistryService registryService) {
this.registryService = registryService;
}
} }

@ -25,6 +25,8 @@ import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherServiceImpl; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherServiceImpl;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.ConfigurationContextService;
/** /**
@ -35,6 +37,18 @@ import org.wso2.carbon.utils.ConfigurationContextService;
* policy="dynamic" * policy="dynamic"
* bind="setConfigurationContextService" * bind="setConfigurationContextService"
* unbind="unsetConfigurationContextService" * unbind="unsetConfigurationContextService"
* @scr.reference name="user.realmservice.default"
* interface="org.wso2.carbon.user.core.service.RealmService"
* cardinality="1..1"
* policy="dynamic"
* bind="setRealmService"
* unbind="unsetRealmService"
* @scr.reference name="registry.service"
* interface="org.wso2.carbon.registry.core.service.RegistryService"
* cardinality="1..1"
* policy="dynamic"
* bind="setRegistryService"
* unbind="unsetRegistryService"
*/ */
public class APIPublisherServiceComponent { public class APIPublisherServiceComponent {
@ -95,4 +109,28 @@ public class APIPublisherServiceComponent {
APIPublisherDataHolder.getInstance().setConfigurationContextService(null); APIPublisherDataHolder.getInstance().setConfigurationContextService(null);
} }
protected void setRealmService(RealmService realmService) {
if (log.isDebugEnabled()) {
log.debug("Setting Realm Service");
}
APIPublisherDataHolder.getInstance().setRealmService(realmService);
}
protected void unsetRealmService(RealmService realmService) {
if (log.isDebugEnabled()) {
log.debug("Unsetting Realm Service");
}
APIPublisherDataHolder.getInstance().setRealmService(null);
}
protected void setRegistryService(RegistryService registryService) {
if (registryService != null && log.isDebugEnabled()) {
log.debug("Registry service initialized");
}
APIPublisherDataHolder.getInstance().setRegistryService(registryService);
}
protected void unsetRegistryService(RegistryService registryService) {
APIPublisherDataHolder.getInstance().setRegistryService(null);
}
} }

@ -24,135 +24,209 @@ import org.apache.catalina.LifecycleListener;
import org.apache.catalina.core.StandardContext; import org.apache.catalina.core.StandardContext;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.*;
import org.wso2.carbon.apimgt.webapp.publisher.APIConfig; import org.wso2.carbon.apimgt.webapp.publisher.*;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService; import org.wso2.carbon.apimgt.webapp.publisher.config.APIResource;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil; import org.wso2.carbon.apimgt.webapp.publisher.config.APIResourceConfiguration;
import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util.AnnotationUtil;
import org.wso2.carbon.base.MultitenantConstants;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class APIPublisherLifecycleListener implements LifecycleListener { public class APIPublisherLifecycleListener implements LifecycleListener {
private static final String API_CONFIG_DEFAULT_VERSION = "1.0.0"; private static final String API_CONFIG_DEFAULT_VERSION = "1.0.0";
private static final String PARAM_MANAGED_API_ENABLED = "managed-api-enabled"; private static final String PARAM_MANAGED_API_ENABLED = "managed-api-enabled";
private static final String PARAM_MANAGED_API_NAME = "managed-api-name"; private static final String PARAM_MANAGED_API_NAME = "managed-api-name";
private static final String PARAM_MANAGED_API_VERSION = "managed-api-version"; private static final String PARAM_MANAGED_API_VERSION = "managed-api-version";
private static final String PARAM_MANAGED_API_CONTEXT = "managed-api-context"; private static final String PARAM_MANAGED_API_CONTEXT = "managed-api-context";
private static final String PARAM_MANAGED_API_ENDPOINT = "managed-api-endpoint"; private static final String PARAM_MANAGED_API_ENDPOINT = "managed-api-endpoint";
private static final String PARAM_MANAGED_API_OWNER = "managed-api-owner"; private static final String PARAM_MANAGED_API_OWNER = "managed-api-owner";
private static final String PARAM_MANAGED_API_TRANSPORTS = "managed-api-transports"; private static final String PARAM_MANAGED_API_TRANSPORTS = "managed-api-transports";
private static final String PARAM_MANAGED_API_IS_SECURED = "managed-api-isSecured"; private static final String PARAM_MANAGED_API_IS_SECURED = "managed-api-isSecured";
private static final String PARAM_MANAGED_API_APPLICATION = "managed-api-application";
private static final Log log = LogFactory.getLog(APIPublisherLifecycleListener.class); private static final String PARAM_MANAGED_API_CONTEXT_TEMPLATE = "managed-api-context-template";
private static final String PARAM_SHARED_WITH_ALL_TENANTS = "isSharedWithAllTenants";
@Override private static final String PARAM_PROVIDER_TENANT_DOMAIN = "providerTenantDomain";
public void lifecycleEvent(LifecycleEvent lifecycleEvent) { private static final Log log = LogFactory.getLog(APIPublisherLifecycleListener.class);
if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) {
StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); @Override
ServletContext servletContext = context.getServletContext(); public void lifecycleEvent(LifecycleEvent lifecycleEvent) {
if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) {
StandardContext context = (StandardContext) lifecycleEvent.getLifecycle();
String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); ServletContext servletContext = context.getServletContext();
boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED);
boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param);
if (isManagedApi) {
APIConfig apiConfig = this.buildApiConfig(servletContext); if (isManagedApi) {
try { try {
apiConfig.init(); AnnotationUtil annotationUtil = new AnnotationUtil(context);
API api = APIPublisherUtil.getAPI(apiConfig); Set<String> annotatedAPIClasses = annotationUtil.
APIPublisherService apiPublisherService = scanStandardContext(org.wso2.carbon.apimgt.annotations.api.API.class.getName());
APIPublisherDataHolder.getInstance().getApiPublisherService(); List<APIResourceConfiguration> apiDefinitions = annotationUtil.extractAPIInfo(annotatedAPIClasses);
if (apiPublisherService == null) {
throw new IllegalStateException("API Publisher service is not initialized properly"); for (APIResourceConfiguration apiDefinition : apiDefinitions) {
} APIConfig apiConfig = this.buildApiConfig(servletContext, apiDefinition);
apiPublisherService.publishAPI(api); try {
} catch (Throwable e) { int tenantId = APIPublisherDataHolder.getInstance().getTenantManager().getTenantId(apiConfig.getTenantDomain());
/* Throwable is caught as none of the RuntimeExceptions that can potentially occur at this point boolean isTenantActive = APIPublisherDataHolder.getInstance().getTenantManager().isTenantActive(tenantId);
does not seem to be logged anywhere else within the framework */ if (isTenantActive) {
log.error("Error occurred while publishing API '" + apiConfig.getName() + "' with the context '" + apiConfig.init();
apiConfig.getContext() + "' and version '" + apiConfig.getVersion() + "'", e); API api = APIPublisherUtil.getAPI(apiConfig);
} APIPublisherService apiPublisherService =
} APIPublisherDataHolder.getInstance().getApiPublisherService();
} if (apiPublisherService == null) {
} throw new IllegalStateException(
"API Publisher service is not initialized properly");
private APIConfig buildApiConfig(ServletContext servletContext) { }
APIConfig apiConfig = new APIConfig(); apiPublisherService.publishAPI(api);
} else {
String name = servletContext.getInitParameter(PARAM_MANAGED_API_NAME); log.error("No tenant [" + apiConfig.getTenantDomain() + "] found when publishing the webapp");
if (name == null || name.isEmpty()) { }
if (log.isDebugEnabled()) { } catch (Throwable e) {
log.debug("'managed-api-name' attribute is not configured. Therefore, using the default, " + log.error("Error occurred while publishing API '" + apiConfig.getName() +
"which is the name of the web application"); "' with the context '" + apiConfig.getContext() +
} "' and version '" + apiConfig.getVersion() + "'", e);
name = servletContext.getServletContextName(); }
} }
apiConfig.setName(name); } catch (IOException e) {
log.error("Error enconterd while discovering annotated classes", e);
String version = servletContext.getInitParameter(PARAM_MANAGED_API_VERSION); } catch (ClassNotFoundException e) {
if (version == null || version.isEmpty()) { log.error("Error while scanning class for annotations", e);
if (log.isDebugEnabled()) { }
log.debug("'managed-api-version' attribute is not configured. Therefore, using the " + }
"default, which is '1.0.0'"); }
} }
version = API_CONFIG_DEFAULT_VERSION;
} private List<APIResourceConfiguration> mergeAPIDefinitions(List<APIResourceConfiguration> inputList) {
apiConfig.setVersion(version); //TODO : Need to implemented, to merge API Definitions in cases where implementation of an API Lies in two
// classes
String context = servletContext.getInitParameter(PARAM_MANAGED_API_CONTEXT); return null;
if (context == null || context.isEmpty()) { }
if (log.isDebugEnabled()) {
log.debug("'managed-api-context' attribute is not configured. Therefore, using the default, " + /**
"which is the original context assigned to the web application"); * Build the API Configuration to be passed to APIM, from a given list of URL templates
} *
context = servletContext.getContextPath(); * @param servletContext
} * @return
apiConfig.setContext(context); */
private APIConfig buildApiConfig(ServletContext servletContext, APIResourceConfiguration apidef) {
String endpoint = servletContext.getInitParameter(PARAM_MANAGED_API_ENDPOINT); APIConfig apiConfig = new APIConfig();
if (endpoint == null || endpoint.isEmpty()) {
if (log.isDebugEnabled()) { String name = apidef.getName();
log.debug("'managed-api-endpoint' attribute is not configured"); if (name == null || name.isEmpty()) {
} if (log.isDebugEnabled()) {
endpoint = APIPublisherUtil.getApiEndpointUrl(context); log.debug("API Name not set in @API Annotation");
} }
apiConfig.setEndpoint(endpoint); name = servletContext.getServletContextName();
}
String owner = servletContext.getInitParameter(PARAM_MANAGED_API_OWNER); apiConfig.setName(name);
if (owner == null || owner.isEmpty()) {
if (log.isDebugEnabled()) { String version = apidef.getVersion();
log.debug("'managed-api-owner' attribute is not configured"); if (version == null || version.isEmpty()) {
} if (log.isDebugEnabled()) {
} log.debug("'API Version not set in @API Annotation'");
apiConfig.setOwner(owner); }
version = API_CONFIG_DEFAULT_VERSION;
String isSecuredParam = servletContext.getInitParameter(PARAM_MANAGED_API_IS_SECURED); }
boolean isSecured; apiConfig.setVersion(version);
if (isSecuredParam == null || isSecuredParam.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-isSecured' attribute is not configured. Therefore, using the default, " + String context = apidef.getContext();
"which is 'true'"); if (context == null || context.isEmpty()) {
} if (log.isDebugEnabled()) {
isSecured = false; log.debug("'API Context not set in @API Annotation'");
} else { }
isSecured = Boolean.parseBoolean(isSecuredParam); context = servletContext.getContextPath();
} }
apiConfig.setSecured(isSecured); apiConfig.setContext(context);
String transports = servletContext.getInitParameter(PARAM_MANAGED_API_TRANSPORTS); String[] tags = apidef.getTags();
if (transports == null || transports.isEmpty()) { if (tags == null || tags.length == 0) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("'managed-api-transports' attribute is not configured. Therefore using the default, " + log.debug("'API tag not set in @API Annotation'");
"which is 'https'"); }
} } else {
transports = "https"; apiConfig.setTags(tags);
} }
apiConfig.setTransports(transports);
String contextTemplate = servletContext.getInitParameter(PARAM_MANAGED_API_CONTEXT_TEMPLATE);
return apiConfig; if (contextTemplate == null || contextTemplate.isEmpty()) {
} if (log.isDebugEnabled()) {
log.debug("'managed-api-context-template' attribute is not configured. Therefore, using the default," +
" " +
"which is the original context template assigned to the web application");
}
contextTemplate = servletContext.getContextPath();
}
apiConfig.setContextTemplate(contextTemplate);
String endpoint = servletContext.getInitParameter(PARAM_MANAGED_API_ENDPOINT);
if (endpoint == null || endpoint.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-endpoint' attribute is not configured");
}
endpoint = APIPublisherUtil.getApiEndpointUrl(context);
}
apiConfig.setEndpoint(endpoint);
String owner = servletContext.getInitParameter(PARAM_MANAGED_API_OWNER);
if (owner == null || owner.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-owner' attribute is not configured");
}
}
apiConfig.setOwner(owner);
String isSecuredParam = servletContext.getInitParameter(PARAM_MANAGED_API_IS_SECURED);
boolean isSecured;
if (isSecuredParam == null || isSecuredParam.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-isSecured' attribute is not configured. Therefore, using the default, " +
"which is 'true'");
}
isSecured = false;
} else {
isSecured = Boolean.parseBoolean(isSecuredParam);
}
apiConfig.setSecured(isSecured);
String transports = servletContext.getInitParameter(PARAM_MANAGED_API_TRANSPORTS);
if (transports == null || transports.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-transports' attribute is not configured. Therefore using the default, " +
"which is 'https'");
}
transports = "https";
}
apiConfig.setTransports(transports);
String sharingValueParam = servletContext.getInitParameter(PARAM_SHARED_WITH_ALL_TENANTS);
boolean isSharedWithAllTenants = (sharingValueParam == null || (!sharingValueParam.isEmpty()) && Boolean.parseBoolean(sharingValueParam) );
apiConfig.setSharedWithAllTenants(isSharedWithAllTenants);
String tenantDomain = servletContext.getInitParameter(PARAM_PROVIDER_TENANT_DOMAIN);
tenantDomain = (tenantDomain!= null && !tenantDomain.isEmpty()) ? tenantDomain : MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
apiConfig.setTenantDomain(tenantDomain);
Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>();
for (APIResource apiResource : apidef.getResources()) {
URITemplate template = new URITemplate();
template.setAuthType(apiResource.getAuthType());
template.setHTTPVerb(apiResource.getHttpVerb());
template.setResourceURI(apiResource.getUri());
template.setUriTemplate(apiResource.getUriTemplate());
uriTemplates.add(template);
}
apiConfig.setUriTemplates(uriTemplates);
return apiConfig;
}
} }

@ -0,0 +1,265 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util;
import org.apache.catalina.core.StandardContext;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.scannotation.AnnotationDB;
import org.scannotation.WarUrlFinder;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResource;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResourceConfiguration;
import javax.servlet.ServletContext;
import javax.ws.rs.*;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.*;
public class AnnotationUtil {
private static final Log log = LogFactory.getLog(AnnotationUtil.class);
private static final String PACKAGE_ORG_APACHE = "org.apache";
private static final String PACKAGE_ORG_CODEHAUS = "org.codehaus";
private static final String PACKAGE_ORG_SPRINGFRAMEWORK = "org.springframework";
private static final String AUTH_TYPE = "Any";
private static final String PROTOCOL_HTTP = "http";
private static final String SERVER_HOST = "carbon.local.ip";
private static final String HTTP_PORT = "httpPort";
public static final String DIR_WEB_INF_LIB = "/WEB-INF/lib";
public static final String STRING_ARR = "string_arr";
public static final String STRING = "string";
private StandardContext context;
private Method[] pathClazzMethods;
private Class<Path> pathClazz;
private ClassLoader classLoader;
private ServletContext servletContext;
public AnnotationUtil(final StandardContext context) {
this.context = context;
servletContext = context.getServletContext();
classLoader = servletContext.getClassLoader();
}
/**
* Scan the context for classes with annotations
* @return
* @throws IOException
*/
public Set<String> scanStandardContext(String className) throws IOException {
AnnotationDB db = new AnnotationDB();
db.addIgnoredPackages(PACKAGE_ORG_APACHE);
db.addIgnoredPackages(PACKAGE_ORG_CODEHAUS);
db.addIgnoredPackages(PACKAGE_ORG_SPRINGFRAMEWORK);
URL[] libPath = WarUrlFinder.findWebInfLibClasspaths(servletContext);
URL classPath = WarUrlFinder.findWebInfClassesPath(servletContext);
URL[] urls = (URL[]) ArrayUtils.add(libPath, libPath.length, classPath);
db.scanArchives(urls);
//Returns a list of classes with given Annotation
return db.getAnnotationIndex().get(className);
}
/**
* Method identifies the URL templates and context by reading the annotations of a class
* @param entityClasses
* @return
*/
public List<APIResourceConfiguration> extractAPIInfo(Set<String> entityClasses)
throws ClassNotFoundException {
List<APIResourceConfiguration> apiResourceConfigs = new ArrayList<APIResourceConfiguration>();
if (entityClasses != null && !entityClasses.isEmpty()) {
for (final String className : entityClasses) {
APIResourceConfiguration resource =
AccessController.doPrivileged(new PrivilegedAction<APIResourceConfiguration>() {
public APIResourceConfiguration run() {
Class<?> clazz = null;
APIResourceConfiguration apiResourceConfig = null;
try {
clazz = classLoader.loadClass(className);
Class<Path> apiClazz = (Class<Path>)
classLoader.loadClass(org.wso2.carbon.apimgt.annotations.api.API.class.getName());
Annotation apiAnno = clazz.getAnnotation(apiClazz);
List<APIResource> resourceList = null;
apiResourceConfig = new APIResourceConfiguration();
if (apiAnno != null) {
Method[] apiClazzMethods = apiClazz.getMethods();
if (log.isDebugEnabled()) {
log.debug("Application Context root = " + servletContext.getContextPath());
}
try {
for(int k=0;k<apiClazzMethods.length;k++){
switch (apiClazzMethods[k].getName()){
case "name" :
apiResourceConfig.setName(invokeMethod(apiClazzMethods[k], apiAnno, STRING));
break;
case "version" :
apiResourceConfig.setVersion(invokeMethod(apiClazzMethods[k], apiAnno, STRING));
break;
case "context" :
apiResourceConfig.setContext(invokeMethod(apiClazzMethods[k], apiAnno, STRING));
break;
case "tags" :
apiResourceConfig.setTags(invokeMethod(apiClazzMethods[k], apiAnno));
break;
}
}
String rootContext = "";
pathClazz = (Class<Path>) classLoader.loadClass(Path.class.getName());
pathClazzMethods = pathClazz.getMethods();
Annotation rootContectAnno = clazz.getAnnotation(pathClazz);
if (rootContectAnno != null) {
rootContext = invokeMethod(pathClazzMethods[0], rootContectAnno, STRING);
if (log.isDebugEnabled()) {
log.debug("API Root Context = " + rootContext);
}
}
Method[] annotatedMethods = clazz.getDeclaredMethods();
resourceList = getApiResources(rootContext, annotatedMethods);
apiResourceConfig.setResources(resourceList);
} catch (Throwable throwable) {
log.error("Error encountered while scanning for annotations", throwable);
}
}
} catch (ClassNotFoundException e) {
log.error("Error when passing the api annotation for device type apis.");
}
return apiResourceConfig;
}
});
apiResourceConfigs.add(resource);
}
}
return apiResourceConfigs;
}
private List<APIResource> getApiResources(String rootContext, Method[] annotatedMethods) throws Throwable {
List<APIResource> resourceList;
resourceList = new ArrayList<APIResource>();
for (Method method : annotatedMethods) {
Annotation methodContextAnno = method.getAnnotation(pathClazz);
if (methodContextAnno != null) {
String subCtx = invokeMethod(pathClazzMethods[0], methodContextAnno, STRING);
APIResource resource = new APIResource();
resource.setUriTemplate(makeContextURLReady(subCtx));
String serverIP = System.getProperty(SERVER_HOST);
String httpServerPort = System.getProperty(HTTP_PORT);
resource.setUri(PROTOCOL_HTTP + "://" + serverIP + ":" + httpServerPort + makeContextURLReady(rootContext) + makeContextURLReady(subCtx));
resource.setAuthType(AUTH_TYPE);
Annotation[] annotations = method.getDeclaredAnnotations();
for(int i=0; i<annotations.length; i++){
if(annotations[i].annotationType().getName().equals(GET.class.getName())){
resource.setHttpVerb(HttpMethod.GET);
}
if(annotations[i].annotationType().getName().equals(POST.class.getName())){
resource.setHttpVerb(HttpMethod.POST);
}
if(annotations[i].annotationType().getName().equals(OPTIONS.class.getName())){
resource.setHttpVerb(HttpMethod.OPTIONS);
}
if(annotations[i].annotationType().getName().equals(DELETE.class.getName())){
resource.setHttpVerb(HttpMethod.DELETE);
}
if(annotations[i].annotationType().getName().equals(PUT.class.getName())){
resource.setHttpVerb(HttpMethod.PUT);
}
if(annotations[i].annotationType().getName().equals(Consumes.class.getName())){
Class<Consumes> consumesClass = (Class<Consumes>) classLoader.loadClass(Consumes.class.getName());
Method[] consumesClassMethods = consumesClass.getMethods();
Annotation consumesAnno = method.getAnnotation(consumesClass);
resource.setConsumes(invokeMethod(consumesClassMethods[0], consumesAnno, STRING_ARR));
}
if(annotations[i].annotationType().getName().equals(Produces.class.getName())){
Class<Produces> producesClass = (Class<Produces>) classLoader.loadClass(Produces.class.getName());
Method[] producesClassMethods = producesClass.getMethods();
Annotation producesAnno = method.getAnnotation(producesClass);
resource.setProduces(invokeMethod(producesClassMethods[0], producesAnno, STRING_ARR));
}
}
resourceList.add(resource);
}
}
return resourceList;
}
private String makeContextURLReady(String context){
if(context != null && !context.equalsIgnoreCase("")){
if(context.startsWith("/")){
return context;
}else{
return "/"+context;
}
}
return "";
}
/**
* When an annotation and method is passed, this method invokes that executes said method against the annotation
* @param method
* @param annotation
* @param returnType
* @return
* @throws Throwable
*/
private String invokeMethod(Method method, Annotation annotation, String returnType) throws Throwable {
InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation);
switch (returnType){
case STRING:
return (String) methodHandler.invoke(annotation, method, null);
case STRING_ARR:
return ((String[])methodHandler.invoke(annotation, method, null))[0];
default:
return null;
}
}
/**
* When an annotation and method is passed, this method invokes that executes said method against the annotation
*/
private String[] invokeMethod(Method method, Annotation annotation) throws Throwable {
InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation);
return ((String[])methodHandler.invoke(annotation, method, null));
}
}

@ -125,7 +125,7 @@
javax.servlet;resolution:=optional, javax.servlet;resolution:=optional,
javax.xml.*;resolution:=optional, javax.xml.*;resolution:=optional,
org.apache.commons.lang, org.apache.commons.lang,
javax.ws.rs;resolution:=optional, javax.ws.rs;version="0.0.0",
org.scannotation org.scannotation
</Import-Package> </Import-Package>
</instructions> </instructions>

@ -133,10 +133,10 @@
<Bundle-Name>${project.artifactId}</Bundle-Name> <Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version> <Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
<Bundle-Description>Device Management JWT Client Bundle</Bundle-Description> <Bundle-Description>Device Management JWT Client Bundle</Bundle-Description>
<Private-Package>org.wso2.carbon.device.mgt.jwt.client.extension.internal</Private-Package> <Private-Package>org.wso2.carbon.identity.jwt.client.extension.internal</Private-Package>
<Export-Package> <Export-Package>
!org.wso2.carbon.device.mgt.jwt.client.extension.internal, !org.wso2.carbon.identity.jwt.client.extension.internal,
org.wso2.carbon.device.mgt.jwt.client.extension.* org.wso2.carbon.identity.jwt.client.extension.*
</Export-Package> </Export-Package>
<Import-Package> <Import-Package>
org.osgi.framework, org.osgi.framework,

@ -16,7 +16,7 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.jwt.client.extension; package org.wso2.carbon.identity.jwt.client.extension;
import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.JWSAlgorithm;
@ -39,11 +39,11 @@ import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException; import org.json.simple.parser.ParseException;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.util.KeyStoreManager; import org.wso2.carbon.core.util.KeyStoreManager;
import org.wso2.carbon.device.mgt.jwt.client.extension.constant.JWTConstants; import org.wso2.carbon.identity.jwt.client.extension.constant.JWTConstants;
import org.wso2.carbon.device.mgt.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.device.mgt.jwt.client.extension.dto.JWTConfig; import org.wso2.carbon.identity.jwt.client.extension.dto.JWTConfig;
import org.wso2.carbon.device.mgt.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.device.mgt.jwt.client.extension.util.JWTClientUtil; import org.wso2.carbon.identity.jwt.client.extension.util.JWTClientUtil;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;

@ -16,17 +16,17 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.jwt.client.extension; package org.wso2.carbon.identity.jwt.client.extension;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.jwt.client.extension.dto.JWTConfig; import org.wso2.carbon.identity.jwt.client.extension.dto.JWTConfig;
import org.wso2.carbon.device.mgt.jwt.client.extension.exception.JWTClientAlreadyExistsException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientAlreadyExistsException;
import org.wso2.carbon.device.mgt.jwt.client.extension.exception.JWTClientConfigurationException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientConfigurationException;
import org.wso2.carbon.device.mgt.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.device.mgt.jwt.client.extension.util.JWTClientUtil; import org.wso2.carbon.identity.jwt.client.extension.util.JWTClientUtil;
import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.exceptions.RegistryException;

@ -15,7 +15,7 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.jwt.client.extension.constant; package org.wso2.carbon.identity.jwt.client.extension.constant;
/** /**
* This holds the constants related JWT client component. * This holds the constants related JWT client component.

@ -16,7 +16,7 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.jwt.client.extension.dto; package org.wso2.carbon.identity.jwt.client.extension.dto;
/** /**
* This holds the token information that return from the token endpoint. * This holds the token information that return from the token endpoint.

@ -1,4 +1,4 @@
package org.wso2.carbon.device.mgt.jwt.client.extension.dto; package org.wso2.carbon.identity.jwt.client.extension.dto;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;

@ -17,7 +17,7 @@
* *
*/ */
package org.wso2.carbon.device.mgt.jwt.client.extension.exception; package org.wso2.carbon.identity.jwt.client.extension.exception;
public class JWTClientAlreadyExistsException extends Exception { public class JWTClientAlreadyExistsException extends Exception {
public JWTClientAlreadyExistsException() { public JWTClientAlreadyExistsException() {

@ -16,7 +16,7 @@
* under the License. * under the License.
* *
*/ */
package org.wso2.carbon.device.mgt.jwt.client.extension.exception; package org.wso2.carbon.identity.jwt.client.extension.exception;
public class JWTClientConfigurationException extends Exception { public class JWTClientConfigurationException extends Exception {
public JWTClientConfigurationException() { public JWTClientConfigurationException() {

@ -16,7 +16,7 @@
* under the License. * under the License.
* *
*/ */
package org.wso2.carbon.device.mgt.jwt.client.extension.exception; package org.wso2.carbon.identity.jwt.client.extension.exception;
public class JWTClientException extends Exception{ public class JWTClientException extends Exception{
public JWTClientException() { public JWTClientException() {

@ -16,7 +16,7 @@
* under the License. * under the License.
* *
*/ */
package org.wso2.carbon.device.mgt.jwt.client.extension.internal; package org.wso2.carbon.identity.jwt.client.extension.internal;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.registry.core.service.TenantRegistryLoader; import org.wso2.carbon.registry.core.service.TenantRegistryLoader;

@ -16,12 +16,12 @@
* under the License. * under the License.
* *
*/ */
package org.wso2.carbon.device.mgt.jwt.client.extension.internal; package org.wso2.carbon.identity.jwt.client.extension.internal;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.jwt.client.extension.util.JWTClientUtil; import org.wso2.carbon.identity.jwt.client.extension.util.JWTClientUtil;
import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.registry.core.service.TenantRegistryLoader; import org.wso2.carbon.registry.core.service.TenantRegistryLoader;
@ -30,7 +30,7 @@ import org.wso2.carbon.user.core.service.RealmService;
import java.io.IOException; import java.io.IOException;
/** /**
* @scr.component name="org.wso2.carbon.device.mgt.jwt.client.extension.internal.JWTClientExtensionServiceComponent" * @scr.component name="org.wso2.carbon.identity.jwt.client.extension.internal.JWTClientExtensionServiceComponent"
* immediate="true" * immediate="true"
* @scr.reference name="registry.service" * @scr.reference name="registry.service"
* interface="org.wso2.carbon.registry.core.service.RegistryService" * interface="org.wso2.carbon.registry.core.service.RegistryService"

@ -15,7 +15,7 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.jwt.client.extension.util; package org.wso2.carbon.identity.jwt.client.extension.util;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -29,7 +29,7 @@ import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.jwt.client.extension.internal.JWTClientExtensionDataHolder; import org.wso2.carbon.identity.jwt.client.extension.internal.JWTClientExtensionDataHolder;
import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.exceptions.RegistryException;

@ -1,2 +1,2 @@
instructions.configure = \ instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.server_${feature.version}/conf/device-analytics-config.xml,target:${installFolder}/../../conf/etc/device-analytics-config.xml,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.analytics.data.publisher_${feature.version}/conf/device-analytics-config.xml,target:${installFolder}/../../conf/etc/device-analytics-config.xml,overwrite:true);\

@ -445,6 +445,11 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.governance</groupId>
<artifactId>org.wso2.carbon.governance.lcm</artifactId>
<version>${carbon.governance.version}</version>
</dependency>
<!-- End of Governance dependencies --> <!-- End of Governance dependencies -->
<!-- OSGi dependencies--> <!-- OSGi dependencies-->

Loading…
Cancel
Save