few changes on web app publisher after testing

revert-70aa11f8
ayyoob 9 years ago
parent d3418462d9
commit 12db341d33

@ -26,13 +26,15 @@ 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.APIStatus;
import org.wso2.carbon.apimgt.api.model.URITemplate; 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.exception.APIPublisherException;
import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; 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.governance.lcm.util.CommonUtil;
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.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamException;
@ -41,7 +43,6 @@ import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
/** /**
* This class represents the concrete implementation of the APIPublisherService that corresponds to providing all * This class represents the concrete implementation of the APIPublisherService that corresponds to providing all
@ -50,89 +51,134 @@ import java.util.Set;
public class APIPublisherServiceImpl implements APIPublisherService { public class APIPublisherServiceImpl implements APIPublisherService {
private static final Log log = LogFactory.getLog(APIPublisherServiceImpl.class); private static final Log log = LogFactory.getLog(APIPublisherServiceImpl.class);
private static final String PUBLISH_ACTION = "Publish";
@Override @Override
public void publishAPI(API api) throws APIManagementException, FaultGatewaysException { public void publishAPI(final API api) throws APIManagementException, FaultGatewaysException {
if (log.isDebugEnabled()) { // A thread is initialized because we cannot guarantee that the gateway is initialized before publishing.
log.debug("Publishing API '" + api.getId() + "'"); // A better solution is needs to be implemented - should check in apimanager whether
} // the gateway is local and if so then publish it through OSGI
try { Runnable connector = new Runnable() {
String tenantDomain = MultitenantUtils.getTenantDomain(api.getApiOwner()); public void run() {
int tenantId = if (waitForServerStartup()) {
APIPublisherDataHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain); return;
// Below code snippet is added load API Lifecycle in tenant mode, where in it does not load when tenant is loaded. }
RegistryService registryService = APIPublisherDataHolder.getInstance().getRegistryService(); if (log.isDebugEnabled()) {
CommonUtil.addDefaultLifecyclesIfNotAvailable(registryService.getConfigSystemRegistry(tenantId), log.debug("Publishing API '" + api.getId() + "");
CommonUtil.getRootSystemRegistry(tenantId)); }
APIProvider provider = APIManagerFactory.getInstance().getAPIProvider(api.getApiOwner()); try {
MultitenantUtils.getTenantDomain(api.getApiOwner()); Thread.sleep(5000);
if (provider != null) { } catch (InterruptedException e) {
if (provider.isDuplicateContextTemplate(api.getContext())) { Thread.interrupted();
throw new APIManagementException("Error occurred while adding the API. A duplicate API" + }
" context already exists for " + api.getContext()); synchronized (APIPublisherServiceImpl.class) {
} String tenantDomain = MultitenantUtils.getTenantDomain(api.getApiOwner());
if (!provider.isAPIAvailable(api.getId())) { PrivilegedCarbonContext.startTenantFlow();
provider.addAPI(api); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
log.info("Successfully published API '" + api.getId().getApiName() + "' with context '" + try {
api.getContext() + "' and version '" + api.getId().getVersion() + "'"); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
} else { // Below code snippet is added to load API Lifecycle in tenant mode.
provider.updateAPI(api); RegistryService registryService = APIPublisherDataHolder.getInstance().getRegistryService();
log.info("An API already exists with the name '" + api.getId().getApiName() + "', context '" + CommonUtil.addDefaultLifecyclesIfNotAvailable(registryService.getConfigSystemRegistry(tenantId),
api.getContext() + "' and version '" + api.getId().getVersion() + CommonUtil.getRootSystemRegistry(tenantId));
"'. Thus, the API config is updated"); APIProvider provider = APIManagerFactory.getInstance().getAPIProvider(api.getApiOwner());
} MultitenantUtils.getTenantDomain(api.getApiOwner());
provider.saveSwagger20Definition(api.getId(), createSwaggerDefinition(api)); if (provider != null) {
} else { if (provider.isDuplicateContextTemplate(api.getContext())) {
throw new APIManagementException("API provider configured for the given API configuration is null. " + throw new APIManagementException(
"Thus, the API is not published"); "Error occurred while adding the API. A duplicate API" +
} " context already exists for " + api.getContext());
} catch (UserStoreException e) { }
throw new APIManagementException("Failed to get the tenant id for the user " + api.getApiOwner(), e); if (!provider.isAPIAvailable(api.getId())) {
} catch (FileNotFoundException e) { provider.addAPI(api);
throw new APIManagementException("Failed to retrieve life cycle file ", e); provider.changeLifeCycleStatus(api.getId(), PUBLISH_ACTION);
} catch (RegistryException e) { if (log.isDebugEnabled()) {
throw new APIManagementException("Failed to access the registry ", e); log.debug("Successfully published API '" + api.getId().getApiName() +
} catch (XMLStreamException e) { "' with context '" + api.getContext() + "' and version '"
throw new APIManagementException("Failed parsing the lifecycle xml.", e); + api.getId().getVersion() + "'");
} }
} } else {
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 APIPublisherException("Failed to retrieve life cycle file ", e);
} catch (RegistryException e) {
throw new APIPublisherException("Failed to access the registry ", e);
} catch (XMLStreamException e) {
throw new APIPublisherException("Failed parsing the lifecycle xml.", e);
} catch (FaultGatewaysException e) {
throw new APIPublisherException("Failed when publishing to the gateway", e);
} catch (APIManagementException e) {
throw new APIPublisherException("Failed publishing the API " + api.getId().getApiName(), e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
private String createSwaggerDefinition(API api) { private boolean waitForServerStartup() {
Map<String, JsonObject> httpVerbsMap = new HashMap<>(); while (!APIPublisherDataHolder.getInstance().getServerStartupListener().isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
return false;
}
for (URITemplate uriTemplate : api.getUriTemplates()) { private String createSwaggerDefinition(API api) {
JsonObject response = new JsonObject(); Map<String, JsonObject> httpVerbsMap = new HashMap<>();
response.addProperty("200", "");
JsonObject responses = new JsonObject(); for (URITemplate uriTemplate : api.getUriTemplates()) {
responses.add("responses", response); JsonObject response = new JsonObject();
JsonObject httpVerbs = httpVerbsMap.get(uriTemplate.getUriTemplate()); response.addProperty("200", "");
if (httpVerbs == null) {
httpVerbs = new JsonObject();
}
httpVerbs.add(uriTemplate.getHTTPVerb().toLowerCase(), responses);
httpVerbsMap.put(uriTemplate.getUriTemplate(), httpVerbs);
}
Iterator it = httpVerbsMap.entrySet().iterator(); JsonObject responses = new JsonObject();
JsonObject paths = new JsonObject(); responses.add("responses", response);
while (it.hasNext()) { JsonObject httpVerbs = httpVerbsMap.get(uriTemplate.getUriTemplate());
Map.Entry<String, JsonObject> pair = (Map.Entry)it.next(); if (httpVerbs == null) {
paths.add(pair.getKey(), pair.getValue()); httpVerbs = new JsonObject();
it.remove(); }
} httpVerbs.add(uriTemplate.getHTTPVerb().toLowerCase(), responses);
httpVerbsMap.put(uriTemplate.getUriTemplate(), httpVerbs);
}
JsonObject info = new JsonObject(); Iterator it = httpVerbsMap.entrySet().iterator();
info.addProperty("title", api.getId().getApiName()); JsonObject paths = new JsonObject();
info.addProperty("version", api.getId().getVersion()); while (it.hasNext()) {
Map.Entry<String, JsonObject> pair = (Map.Entry) it.next();
paths.add(pair.getKey(), pair.getValue());
it.remove();
}
JsonObject swaggerDefinition = new JsonObject(); JsonObject info = new JsonObject();
swaggerDefinition.add("paths", paths); info.addProperty("title", api.getId().getApiName());
swaggerDefinition.addProperty("swagger", "2.0"); info.addProperty("version", api.getId().getVersion());
swaggerDefinition.add("info", info);
return swaggerDefinition.toString(); JsonObject swaggerDefinition = new JsonObject();
} swaggerDefinition.add("paths", paths);
swaggerDefinition.addProperty("swagger", "2.0");
swaggerDefinition.add("info", info);
return swaggerDefinition.toString();
}
@Override @Override
public void removeAPI(APIIdentifier id) throws APIManagementException { public void removeAPI(APIIdentifier id) throws APIManagementException {

@ -37,6 +37,7 @@ public class APIPublisherUtil {
private static final String DEFAULT_API_VERSION = "1.0.0"; private static final String DEFAULT_API_VERSION = "1.0.0";
public static final String API_VERSION_PARAM="{version}"; public static final String API_VERSION_PARAM="{version}";
public static final String API_PUBLISH_ENVIRONEMENT = "Production and Sandbox";
enum HTTPMethod { enum HTTPMethod {
GET, POST, DELETE, PUT, OPTIONS GET, POST, DELETE, PUT, OPTIONS
@ -75,10 +76,13 @@ public class APIPublisherUtil {
api.setUrl(config.getEndpoint()); api.setUrl(config.getEndpoint());
api.addAvailableTiers(provider.getTiers()); api.addAvailableTiers(provider.getTiers());
api.setEndpointSecured(true); api.setEndpointSecured(true);
api.setStatus(APIStatus.PUBLISHED); api.setStatus(APIStatus.CREATED);
api.setTransports(config.getTransports()); api.setTransports(config.getTransports());
api.setContextTemplate(config.getContextTemplate()); api.setContextTemplate(config.getContextTemplate());
api.setUriTemplates(config.getUriTemplates()); api.setUriTemplates(config.getUriTemplates());
Set<String> environements = new HashSet<>();
environements.add(API_PUBLISH_ENVIRONEMENT);
api.setEnvironments(environements);
Set<Tier> tiers = new HashSet<Tier>(); Set<Tier> tiers = new HashSet<Tier>();
tiers.add(new Tier(APIConstants.UNLIMITED_TIER)); tiers.add(new Tier(APIConstants.UNLIMITED_TIER));
api.addAvailableTiers(tiers); api.addAvailableTiers(tiers);
@ -91,7 +95,7 @@ public class APIPublisherUtil {
} }
api.setResponseCache(APIConstants.DISABLED); api.setResponseCache(APIConstants.DISABLED);
String endpointConfig = "{\"production_endpoints\":{\"url\":\" " + config.getEndpoint() + "\",\"config\":null},\"endpoint_type\":\"http\"}"; String endpointConfig = "{\"production_endpoints\":{\"url\":\" " + config.getEndpoint() + "\",\"config\":null},\"implementation_status\":\"managed\",\"endpoint_type\":\"http\"}";
api.setEndpointConfig(endpointConfig); api.setEndpointConfig(endpointConfig);
if ("".equals(id.getVersion()) || (DEFAULT_API_VERSION.equals(id.getVersion()))) { if ("".equals(id.getVersion()) || (DEFAULT_API_VERSION.equals(id.getVersion()))) {

@ -0,0 +1,56 @@
/*
* 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.exception;
public class APIPublisherException extends RuntimeException {
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public APIPublisherException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public APIPublisherException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public APIPublisherException(String msg) {
super(msg);
setErrorMessage(msg);
}
public APIPublisherException() {
super();
}
public APIPublisherException(Throwable cause) {
super(cause);
}
}

@ -20,6 +20,8 @@ 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.apimgt.webapp.publisher.lifecycle.util.ServerStartupListener;
import org.wso2.carbon.core.ServerStartupObserver;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.carbon.user.core.tenant.TenantManager;
@ -32,6 +34,7 @@ public class APIPublisherDataHolder {
private RealmService realmService; private RealmService realmService;
private TenantManager tenantManager; private TenantManager tenantManager;
private RegistryService registryService; private RegistryService registryService;
private ServerStartupListener serverStartupListener;
private static APIPublisherDataHolder thisInstance = new APIPublisherDataHolder(); private static APIPublisherDataHolder thisInstance = new APIPublisherDataHolder();
@ -94,4 +97,12 @@ public class APIPublisherDataHolder {
public void setRegistryService(RegistryService registryService) { public void setRegistryService(RegistryService registryService) {
this.registryService = registryService; this.registryService = registryService;
} }
public ServerStartupListener getServerStartupListener() {
return serverStartupListener;
}
public void setServerStartupListener(ServerStartupListener serverStartupListener) {
this.serverStartupListener = serverStartupListener;
}
} }

@ -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.apimgt.webapp.publisher.lifecycle.util.ServerStartupListener;
import org.wso2.carbon.core.ServerStartupObserver;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.ConfigurationContextService;
@ -59,7 +61,10 @@ public class APIPublisherServiceComponent {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Initializing device management core bundle"); log.debug("Initializing device management core bundle");
} }
BundleContext bundleContext = componentContext.getBundleContext();
ServerStartupListener serverStartupListener = new ServerStartupListener();
bundleContext.registerService(ServerStartupObserver.class.getName(), serverStartupListener, null);
APIPublisherDataHolder.getInstance().setServerStartupListener(serverStartupListener);
/* Registering declarative service instances exposed by DeviceManagementServiceComponent */ /* Registering declarative service instances exposed by DeviceManagementServiceComponent */
this.registerServices(componentContext); this.registerServices(componentContext);

@ -25,6 +25,7 @@ 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.*; import org.wso2.carbon.apimgt.api.model.*;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.webapp.publisher.*; import org.wso2.carbon.apimgt.webapp.publisher.*;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResource; 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.APIResourceConfiguration;
@ -47,14 +48,12 @@ public class APIPublisherLifecycleListener implements LifecycleListener {
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_ENDPOINT_CONTEXT = "managed-api-endpoint-context";
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 String PARAM_MANAGED_API_APPLICATION = "managed-api-application";
private static final String PARAM_SHARED_WITH_ALL_TENANTS = "isSharedWithAllTenants"; private static final String PARAM_SHARED_WITH_ALL_TENANTS = "isSharedWithAllTenants";
private static final String PARAM_PROVIDER_TENANT_DOMAIN = "providerTenantDomain"; private static final String PARAM_PROVIDER_TENANT_DOMAIN = "providerTenantDomain";
private static final String VERSION_PLACEHOLDER = "{version}";
private static final Log log = LogFactory.getLog(APIPublisherLifecycleListener.class); private static final Log log = LogFactory.getLog(APIPublisherLifecycleListener.class);
@Override @Override
@ -70,7 +69,7 @@ public class APIPublisherLifecycleListener implements LifecycleListener {
AnnotationUtil annotationUtil = new AnnotationUtil(context); AnnotationUtil annotationUtil = new AnnotationUtil(context);
Set<String> annotatedAPIClasses = annotationUtil. Set<String> annotatedAPIClasses = annotationUtil.
scanStandardContext(org.wso2.carbon.apimgt.annotations.api.API.class.getName()); scanStandardContext(org.wso2.carbon.apimgt.annotations.api.API.class.getName());
List<APIResourceConfiguration> apiDefinitions = annotationUtil.extractAPIInfo(annotatedAPIClasses); List<APIResourceConfiguration> apiDefinitions = annotationUtil.extractAPIInfo(servletContext, annotatedAPIClasses);
for (APIResourceConfiguration apiDefinition : apiDefinitions) { for (APIResourceConfiguration apiDefinition : apiDefinitions) {
APIConfig apiConfig = this.buildApiConfig(servletContext, apiDefinition); APIConfig apiConfig = this.buildApiConfig(servletContext, apiDefinition);
@ -161,9 +160,9 @@ public class APIPublisherLifecycleListener implements LifecycleListener {
tenantDomain = (tenantDomain != null && !tenantDomain.isEmpty()) ? tenantDomain : tenantDomain = (tenantDomain != null && !tenantDomain.isEmpty()) ? tenantDomain :
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
apiConfig.setTenantDomain(tenantDomain); apiConfig.setTenantDomain(tenantDomain);
String contextTemplate = context + "/" + VERSION_PLACEHOLDER; String contextTemplate = context + "/" + APIConstants.VERSION_PLACEHOLDER;
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
contextTemplate = context + "/t/" + tenantDomain + "/" + VERSION_PLACEHOLDER; contextTemplate = context + "/t/" + tenantDomain + "/" + APIConstants.VERSION_PLACEHOLDER;
} }
apiConfig.setContextTemplate(contextTemplate); apiConfig.setContextTemplate(contextTemplate);
@ -172,13 +171,8 @@ public class APIPublisherLifecycleListener implements LifecycleListener {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("'managed-api-endpoint' attribute is not configured"); log.debug("'managed-api-endpoint' attribute is not configured");
} }
String endpointContext = servletContext.getInitParameter(PARAM_MANAGED_API_ENDPOINT_CONTEXT); String endpointContext = servletContext.getContextPath();
if (endpointContext != null && !endpointContext.isEmpty()) { endpoint = APIPublisherUtil.getApiEndpointUrl(endpointContext);
endpoint = APIPublisherUtil.getApiEndpointUrl(endpointContext);
} else {
endpoint = APIPublisherUtil.getApiEndpointUrl(context);
}
} }
apiConfig.setEndpoint(endpoint); apiConfig.setEndpoint(endpoint);

@ -92,7 +92,7 @@ public class AnnotationUtil {
* @param entityClasses * @param entityClasses
* @return * @return
*/ */
public List<APIResourceConfiguration> extractAPIInfo(Set<String> entityClasses) public List<APIResourceConfiguration> extractAPIInfo(final ServletContext servletContext, Set<String> entityClasses)
throws ClassNotFoundException { throws ClassNotFoundException {
List<APIResourceConfiguration> apiResourceConfigs = new ArrayList<APIResourceConfiguration>(); List<APIResourceConfiguration> apiResourceConfigs = new ArrayList<APIResourceConfiguration>();
@ -111,7 +111,7 @@ public class AnnotationUtil {
classLoader.loadClass(org.wso2.carbon.apimgt.annotations.api.API.class.getName()); classLoader.loadClass(org.wso2.carbon.apimgt.annotations.api.API.class.getName());
Annotation apiAnno = clazz.getAnnotation(apiClazz); Annotation apiAnno = clazz.getAnnotation(apiClazz);
List<APIResource> resourceList = null; List<APIResource> resourceList;
apiResourceConfig = new APIResourceConfiguration(); apiResourceConfig = new APIResourceConfiguration();
if (apiAnno != null) { if (apiAnno != null) {
@ -139,21 +139,27 @@ public class AnnotationUtil {
break; break;
} }
} }
// All the apis should map to same root "/"
String rootContext = ""; String rootContext = servletContext.getContextPath();
pathClazz = (Class<Path>) classLoader.loadClass(Path.class.getName()); pathClazz = (Class<Path>) classLoader.loadClass(Path.class.getName());
pathClazzMethods = pathClazz.getMethods(); pathClazzMethods = pathClazz.getMethods();
Annotation rootContectAnno = clazz.getAnnotation(pathClazz); Annotation rootContectAnno = clazz.getAnnotation(pathClazz);
String subContext = "";
if (rootContectAnno != null) { if (rootContectAnno != null) {
rootContext = invokeMethod(pathClazzMethods[0], rootContectAnno, STRING); subContext = invokeMethod(pathClazzMethods[0], rootContectAnno, STRING);
if (subContext != null && !subContext.isEmpty()) {
rootContext = rootContext + "/" + subContext;
} else {
subContext = "";
}
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("API Root Context = " + rootContext); log.debug("API Root Context = " + rootContext);
} }
} }
Method[] annotatedMethods = clazz.getDeclaredMethods(); Method[] annotatedMethods = clazz.getDeclaredMethods();
resourceList = getApiResources(rootContext, annotatedMethods); resourceList = getApiResources(rootContext, subContext, annotatedMethods);
apiResourceConfig.setResources(resourceList); apiResourceConfig.setResources(resourceList);
} catch (Throwable throwable) { } catch (Throwable throwable) {
log.error("Error encountered while scanning for annotations", throwable); log.error("Error encountered while scanning for annotations", throwable);
@ -171,7 +177,7 @@ public class AnnotationUtil {
return apiResourceConfigs; return apiResourceConfigs;
} }
private List<APIResource> getApiResources(String rootContext, Method[] annotatedMethods) throws Throwable { private List<APIResource> getApiResources(String resourceRootContext, String apiRootContext, Method[] annotatedMethods) throws Throwable {
List<APIResource> resourceList; List<APIResource> resourceList;
resourceList = new ArrayList<APIResource>(); resourceList = new ArrayList<APIResource>();
for (Method method : annotatedMethods) { for (Method method : annotatedMethods) {
@ -179,12 +185,13 @@ public class AnnotationUtil {
if (methodContextAnno != null) { if (methodContextAnno != null) {
String subCtx = invokeMethod(pathClazzMethods[0], methodContextAnno, STRING); String subCtx = invokeMethod(pathClazzMethods[0], methodContextAnno, STRING);
APIResource resource = new APIResource(); APIResource resource = new APIResource();
resource.setUriTemplate(makeContextURLReady(subCtx)); resource.setUriTemplate(makeContextURLReady(apiRootContext + subCtx));
String serverIP = System.getProperty(SERVER_HOST); String serverIP = System.getProperty(SERVER_HOST);
String httpServerPort = System.getProperty(HTTP_PORT); String httpServerPort = System.getProperty(HTTP_PORT);
resource.setUri(PROTOCOL_HTTP + "://" + serverIP + ":" + httpServerPort + makeContextURLReady(rootContext) + makeContextURLReady(subCtx)); resource.setUri(PROTOCOL_HTTP + "://" + serverIP + ":" + httpServerPort + makeContextURLReady(
resourceRootContext) + makeContextURLReady(subCtx));
resource.setAuthType(AUTH_TYPE); resource.setAuthType(AUTH_TYPE);
Annotation[] annotations = method.getDeclaredAnnotations(); Annotation[] annotations = method.getDeclaredAnnotations();

@ -0,0 +1,44 @@
/*
* 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.lifecycle.util;
import org.wso2.carbon.core.ServerStartupObserver;
/**
* This is added to make sure that the apis are publishsed after gateway services are intiialized.
*/
public class ServerStartupListener implements ServerStartupObserver {
private static volatile boolean serverReady = false;
@Override
public void completingServerStartup() {
}
@Override
public void completedServerStartup() {
ServerStartupListener.setServerReady(true);
}
public static boolean isServerReady() {
return ServerStartupListener.serverReady;
}
public static void setServerReady(boolean serverReady) {
ServerStartupListener.serverReady = serverReady;
}
}
Loading…
Cancel
Save