Search in sources :

Example 71 with Subscriber

use of org.wso2.carbon.apimgt.api.model.Subscriber in project carbon-apimgt by wso2.

the class APIProviderImpl method getSubscriberClaims.

/**
 * Returns the claims of subscriber for the given subscriber.
 *
 * @param subscriber The name of the subscriber to be returned
 * @return The looked up claims of the subscriber or null if the requested subscriber does not exist
 * @throws APIManagementException if failed to get Subscriber
 */
@Override
public Map<String, String> getSubscriberClaims(String subscriber) throws APIManagementException {
    String tenantDomain = MultitenantUtils.getTenantDomain(subscriber);
    int tenantId = 0;
    Map<String, String> claimMap = new HashMap<>();
    Map<String, String> subscriberClaims = null;
    String configuredClaims = "";
    try {
        tenantId = getTenantId(tenantDomain);
        UserStoreManager userStoreManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getUserStoreManager();
        if (userStoreManager.isExistingUser(subscriber)) {
            subscriberClaims = APIUtil.getClaims(subscriber, tenantId, ClaimsRetriever.DEFAULT_DIALECT_URI);
            APIManagerConfiguration configuration = getAPIManagerConfiguration();
            configuredClaims = configuration.getFirstProperty(APIConstants.API_PUBLISHER_SUBSCRIBER_CLAIMS);
        }
        for (String claimURI : configuredClaims.split(",")) {
            if (subscriberClaims != null) {
                claimMap.put(claimURI, subscriberClaims.get(claimURI));
            }
        }
    } catch (UserStoreException e) {
        throw new APIManagementException("Error while retrieving tenant id for tenant domain " + tenantDomain, e);
    }
    return claimMap;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) UserStoreException(org.wso2.carbon.user.api.UserStoreException) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager)

Example 72 with Subscriber

use of org.wso2.carbon.apimgt.api.model.Subscriber in project carbon-apimgt by wso2.

the class AbstractAPIManager method addSubscriber.

public void addSubscriber(String username, String groupingId) throws APIManagementException {
    Subscriber subscriber = new Subscriber(username);
    subscriber.setSubscribedDate(new Date());
    try {
        int tenantId = getTenantManager().getTenantId(getTenantDomain(username));
        subscriber.setEmail(StringUtils.EMPTY);
        subscriber.setTenantId(tenantId);
        apiMgtDAO.addSubscriber(subscriber, groupingId);
        if (APIUtil.isDefaultApplicationCreationEnabled() && !APIUtil.isDefaultApplicationCreationDisabledForTenant(getTenantDomain(username))) {
            // Add a default application once subscriber is added
            addDefaultApplicationForSubscriber(subscriber);
        }
    } catch (APIManagementException e) {
        String msg = "Error while adding the subscriber " + subscriber.getName();
        throw new APIManagementException(msg, e);
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        String msg = "Error while adding the subscriber " + subscriber.getName();
        throw new APIManagementException(msg, e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) Date(java.util.Date)

Example 73 with Subscriber

use of org.wso2.carbon.apimgt.api.model.Subscriber in project carbon-apimgt by wso2.

the class PersistenceHelper method getSampleAPIArtifactForTenant.

public static GenericArtifact getSampleAPIArtifactForTenant() throws GovernanceException {
    GenericArtifact artifact = new GenericArtifactImpl(new QName("", "PizzaShackAPI", ""), "application/vnd.wso2-api+xml");
    artifact.setAttribute("overview_endpointSecured", "false");
    artifact.setAttribute("overview_transports", "http,https");
    artifact.setAttribute("URITemplate_authType3", "Application & Application User");
    artifact.setAttribute("overview_wadl", null);
    artifact.setAttribute("URITemplate_authType4", "Application & Application User");
    artifact.setAttribute("overview_authorizationHeader", "Authorization");
    artifact.setAttribute("URITemplate_authType1", "Application & Application User");
    artifact.setAttribute("overview_visibleTenants", null);
    artifact.setAttribute("URITemplate_authType2", "Application & Application User");
    artifact.setAttribute("overview_wsdl", null);
    artifact.setAttribute("overview_apiSecurity", "oauth2,oauth_basic_auth_api_key_mandatory");
    artifact.setAttribute("URITemplate_authType0", "Application & Application User");
    artifact.setAttribute("overview_keyManagers", "[\"all\"]");
    artifact.setAttribute("overview_environments", "Default");
    artifact.setAttribute("overview_context", "/t/wso2.com/pizzashack/1.0.0");
    artifact.setAttribute("overview_visibility", "restricted");
    artifact.setAttribute("overview_isLatest", "true");
    artifact.setAttribute("overview_outSequence", "log_out_message");
    artifact.setAttribute("overview_provider", "admin-AT-wso2.com");
    artifact.setAttribute("apiCategories_categoryName", "testcategory");
    artifact.setAttribute("overview_thumbnail", "/t/wso2.com/t/wso2.com/registry/resource/_system/governance/apimgt/applicationdata/provider/admin-AT-wso2.com/PizzaShackAPI/1.0.0/icon");
    artifact.setAttribute("overview_contextTemplate", "/t/wso2.com/pizzashack/{version}");
    artifact.setAttribute("overview_description", "This is a simple API for Pizza Shack online pizza delivery store.");
    artifact.setAttribute("overview_technicalOwner", "John Doe");
    artifact.setAttribute("overview_type", "HTTP");
    artifact.setAttribute("overview_technicalOwnerEmail", "architecture@pizzashack.com");
    artifact.setAttribute("URITemplate_httpVerb4", "DELETE");
    artifact.setAttribute("overview_inSequence", "log_in_message");
    artifact.setAttribute("URITemplate_httpVerb2", "GET");
    artifact.setAttribute("URITemplate_httpVerb3", "PUT");
    artifact.setAttribute("URITemplate_httpVerb0", "POST");
    artifact.setAttribute("URITemplate_httpVerb1", "GET");
    artifact.setAttribute("labels_labelName", "gwlable");
    artifact.setAttribute("overview_businessOwner", "Jane Roe");
    artifact.setAttribute("overview_version", "1.0.0");
    artifact.setAttribute("overview_endpointConfig", "{\"endpoint_type\":\"http\",\"sandbox_endpoints\":{\"url\":\"https://localhost:9443/am/sample/pizzashack/v1/api/\"}," + "\"endpoint_security\":{\"production\":{\"password\":\"admin\",\"tokenUrl\":null,\"clientId\":null," + "\"clientSecret\":null,\"customParameters\":\"{}\",\"additionalProperties\":{},\"type\":\"BASIC\"," + "\"grantType\":null,\"enabled\":true,\"uniqueIdentifier\":null,\"username\":\"admin\"}," + "\"sandbox\":{\"password\":null,\"tokenUrl\":null,\"clientId\":null,\"clientSecret\":null," + "\"customParameters\":\"{}\",\"additionalProperties\":{},\"type\":null,\"grantType\":null,\"enabled\":false," + "\"uniqueIdentifier\":null,\"username\":null}},\"production_endpoints\":" + "{\"url\":\"https://localhost:9443/am/sample/pizzashack/v1/api/\"}}");
    artifact.setAttribute("overview_tier", "Bronze||Silver||Gold||Unlimited");
    artifact.setAttribute("overview_sandboxTps", "1000");
    artifact.setAttribute("overview_apiOwner", "admin@wso2.com");
    artifact.setAttribute("overview_businessOwnerEmail", "marketing@pizzashack.com");
    artifact.setAttribute("isMonetizationEnabled", "false");
    artifact.setAttribute("overview_implementation", "ENDPOINT");
    artifact.setAttribute("overview_deployments", "null");
    artifact.setAttribute("overview_redirectURL", null);
    artifact.setAttribute("monetizationProperties", "{}");
    artifact.setAttribute("overview_name", "PizzaShackAPI");
    artifact.setAttribute("overview_subscriptionAvailability", "current_tenant");
    artifact.setAttribute("overview_productionTps", "1000");
    artifact.setAttribute("overview_cacheTimeout", "300");
    artifact.setAttribute("overview_visibleRoles", "admin,internal/subscriber");
    artifact.setAttribute("overview_testKey", null);
    artifact.setAttribute("overview_corsConfiguration", "{\"corsConfigurationEnabled\":true,\"accessControlAllowOrigins\":[\"*\"]," + "\"accessControlAllowCredentials\":false,\"accessControlAllowHeaders\":[\"authorization\"," + "\"Access-Control-Allow-Origin\",\"Content-Type\",\"SOAPAction\",\"apikey\",\"testKey\"]," + "\"accessControlAllowMethods\":[\"GET\",\"PUT\",\"POST\",\"DELETE\",\"PATCH\",\"OPTIONS\"]}");
    artifact.setAttribute("overview_advertiseOnly", "false");
    artifact.setAttribute("overview_versionType", "context");
    artifact.setAttribute("overview_status", "PUBLISHED");
    artifact.setAttribute("overview_endpointPpassword", null);
    artifact.setAttribute("overview_tenants", null);
    artifact.setAttribute("overview_endpointAuthDigest", "false");
    artifact.setAttribute("overview_faultSequence", "json_fault");
    artifact.setAttribute("overview_responseCaching", "Enabled");
    artifact.setAttribute("URITemplate_urlPattern4", "/order/{orderId}");
    artifact.setAttribute("overview_isDefaultVersion", "true");
    artifact.setAttribute("URITemplate_urlPattern2", "/order/{orderId}");
    artifact.setAttribute("URITemplate_urlPattern3", "/order/{orderId}");
    artifact.setAttribute("URITemplate_urlPattern0", "/order");
    artifact.setAttribute("URITemplate_urlPattern1", "/menu");
    artifact.setAttribute("overview_enableStore", "true");
    artifact.setAttribute("overview_enableSchemaValidation", "true");
    artifact.setAttribute("overview_endpointUsername", null);
    artifact.setAttribute("overview_status", "PUBLISHED");
    artifact.setId("88e758b7-6924-4e9f-8882-431070b6492b");
    return artifact;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) QName(javax.xml.namespace.QName) GenericArtifactImpl(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifactImpl)

Example 74 with Subscriber

use of org.wso2.carbon.apimgt.api.model.Subscriber in project carbon-apimgt by wso2.

the class RegistrySearchUtilTestCase method testDevPortalUserQueryInDevPortal.

@Test
public void testDevPortalUserQueryInDevPortal() throws APIPersistenceException {
    // Normal dev portal api listing
    String inputQuery = "";
    UserContext ctx = new UserContext("devUser", organization, null, devPortalRoles);
    String searchQuery = RegistrySearchUtil.getDevPortalSearchQuery(inputQuery, ctx, false, false);
    String expected = "store_view_roles=(null OR internal\\/subscriber OR internal\\/everyone)&name=*" + "&enableStore=(true OR null)&group=true&group.field=name&group.ngroups=true&group.sort=versionTimestamp desc" + "&lcState=(PUBLISHED OR PROTOTYPED)";
    Assert.assertEquals("Generated query mismatched. ", expected, searchQuery);
    // search for 'test' in description
    inputQuery = "description:test";
    expected = "store_view_roles=(null OR internal\\/subscriber OR internal\\/everyone)&" + "description=*test*&lcState=(PUBLISHED OR PROTOTYPED)";
    searchQuery = RegistrySearchUtil.getDevPortalSearchQuery(inputQuery, ctx, false, false);
    Assert.assertEquals("Generated query mismatched for description search. ", expected, searchQuery);
    // search for provider 'pubuser'
    inputQuery = "provider:pubuser";
    expected = "store_view_roles=(null OR internal\\/subscriber OR internal\\/everyone)&" + "provider=*pubuser*&lcState=(PUBLISHED OR PROTOTYPED)";
    searchQuery = RegistrySearchUtil.getDevPortalSearchQuery(inputQuery, ctx, false, false);
    Assert.assertEquals("Generated query mismatched for provider search. ", expected, searchQuery);
    // search for propertyname 'test'
    inputQuery = "property_name:test";
    expected = "store_view_roles=(null OR internal\\/subscriber OR internal\\/everyone)" + "&api_meta.property_name__display=*test*&lcState=(PUBLISHED OR PROTOTYPED)";
    searchQuery = RegistrySearchUtil.getDevPortalSearchQuery(inputQuery, ctx, false, false);
    Assert.assertEquals("Generated query mismatched for property search. ", expected, searchQuery);
}
Also used : UserContext(org.wso2.carbon.apimgt.persistence.dto.UserContext) Test(org.junit.Test)

Example 75 with Subscriber

use of org.wso2.carbon.apimgt.api.model.Subscriber in project carbon-apimgt by wso2.

the class SolaceApplicationNotifier method removeSolaceApplication.

/**
 * Remove applications from Solace broker
 *
 * @param event ApplicationEvent to remove Solace applications
 * @throws NotifierException if error occurs when removing applications from Solace broker
 */
private void removeSolaceApplication(ApplicationEvent event) throws NotifierException {
    // get list of subscribed APIs in the application
    Subscriber subscriber = new Subscriber(event.getSubscriber());
    try {
        Set<SubscribedAPI> subscriptions = apiMgtDAO.getSubscribedAPIs(subscriber, event.getApplicationName(), event.getGroupId());
        List<SubscribedAPI> subscribedApiList = new ArrayList<>(subscriptions);
        boolean hasSubscribedAPIDeployedInSolace = false;
        String organizationNameOfSolaceDeployment = null;
        Map<String, Environment> gatewayEnvironments = APIUtil.getReadOnlyGatewayEnvironments();
        labelOne: for (SubscribedAPI api : subscribedApiList) {
            List<APIRevisionDeployment> deployments = apiMgtDAO.getAPIRevisionDeploymentByApiUUID(api.getUUID());
            for (APIRevisionDeployment deployment : deployments) {
                if (gatewayEnvironments.containsKey(deployment.getDeployment())) {
                    if (SolaceConstants.SOLACE_ENVIRONMENT.equalsIgnoreCase(gatewayEnvironments.get(deployment.getDeployment()).getProvider())) {
                        hasSubscribedAPIDeployedInSolace = true;
                        organizationNameOfSolaceDeployment = gatewayEnvironments.get(deployment.getDeployment()).getAdditionalProperties().get(SolaceConstants.SOLACE_ENVIRONMENT_ORGANIZATION);
                        break labelOne;
                    }
                }
            }
        }
        boolean applicationFoundInSolaceBroker = false;
        if (hasSubscribedAPIDeployedInSolace) {
            SolaceAdminApis solaceAdminApis = SolaceNotifierUtils.getSolaceAdminApis();
            // check existence of application in Solace Broker
            CloseableHttpResponse response1 = solaceAdminApis.applicationGet(organizationNameOfSolaceDeployment, event.getUuid(), "default");
            if (response1.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                applicationFoundInSolaceBroker = true;
                if (log.isDebugEnabled()) {
                    log.info("Found application '" + event.getApplicationName() + "' in Solace broker");
                    log.info("Waiting until application removing workflow gets finished");
                }
            } else if (response1.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                throw new NotifierException("Application '" + event.getApplicationName() + "' cannot be found in " + "Solace Broker");
            } else {
                if (log.isDebugEnabled()) {
                    log.error("Error while searching for application '" + event.getApplicationName() + "'" + " in Solace Broker. : " + response1.getStatusLine().toString());
                }
                throw new NotifierException("Error while searching for application '" + event.getApplicationName() + "' in Solace Broker");
            }
        }
        if (applicationFoundInSolaceBroker) {
            log.info("Deleting application from Solace Broker");
            // delete application from solace
            SolaceAdminApis solaceAdminApis = SolaceNotifierUtils.getSolaceAdminApis();
            CloseableHttpResponse response2 = solaceAdminApis.deleteApplication(organizationNameOfSolaceDeployment, event.getUuid());
            if (response2.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) {
                log.info("Successfully deleted application '" + event.getApplicationName() + "' " + "in Solace Broker");
            } else {
                if (log.isDebugEnabled()) {
                    log.error("Error while deleting application " + event.getApplicationName() + " in Solace. :" + response2.getStatusLine().toString());
                }
                throw new NotifierException("Error while deleting application '" + event.getApplicationName() + "' in Solace");
            }
        }
    } catch (APIManagementException e) {
        throw new NotifierException(e.getMessage());
    }
}
Also used : ArrayList(java.util.ArrayList) APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment) NotifierException(org.wso2.carbon.apimgt.impl.notifier.exceptions.NotifierException) SolaceAdminApis(org.wso2.carbon.apimgt.solace.SolaceAdminApis) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) Environment(org.wso2.carbon.apimgt.api.model.Environment) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

Subscriber (org.wso2.carbon.apimgt.api.model.Subscriber)98 Test (org.junit.Test)64 Application (org.wso2.carbon.apimgt.api.model.Application)63 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)60 PreparedStatement (java.sql.PreparedStatement)39 SQLException (java.sql.SQLException)39 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)39 ResultSet (java.sql.ResultSet)37 Connection (java.sql.Connection)31 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)28 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)25 Tier (org.wso2.carbon.apimgt.api.model.Tier)20 ArrayList (java.util.ArrayList)19 HashSet (java.util.HashSet)19 Date (java.util.Date)14 HashMap (java.util.HashMap)11 LinkedHashSet (java.util.LinkedHashSet)10 JSONObject (org.json.simple.JSONObject)10 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)10 TreeMap (java.util.TreeMap)9