Search in sources :

Example 26 with Target

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.Target in project carbon-apimgt by wso2.

the class WebSocketAnalyticsDataProvider method getTarget.

@Override
public Target getTarget() {
    Target target = new Target();
    // These properties are not applicable for WS API
    target.setResponseCacheHit(false);
    target.setTargetResponseCode(0);
    String endpointAddress = (String) WebSocketUtils.getPropertyFromChannel(APIMgtGatewayConstants.SYNAPSE_ENDPOINT_ADDRESS, ctx);
    target.setDestination(endpointAddress);
    return target;
}
Also used : Target(org.wso2.carbon.apimgt.common.analytics.publishers.dto.Target)

Example 27 with Target

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.Target in project carbon-apimgt by wso2.

the class AsyncApiParser method buildURITemplate.

private URITemplate buildURITemplate(String target, String verb, Aai20Operation operation, Set<Scope> scopes, Aai20ChannelItem channel) throws APIManagementException {
    URITemplate template = new URITemplate();
    template.setHTTPVerb(verb);
    template.setHttpVerbs(verb);
    template.setUriTemplate(target);
    Extension authTypeExtension = channel.getExtension(APIConstants.SWAGGER_X_AUTH_TYPE);
    if (authTypeExtension != null && authTypeExtension.value instanceof String) {
        template.setAuthType(authTypeExtension.value.toString());
    }
    List<String> opScopes = getScopeOfOperations(operation);
    if (!opScopes.isEmpty()) {
        if (opScopes.size() == 1) {
            String firstScope = opScopes.get(0);
            Scope scope = APIUtil.findScopeByKey(scopes, firstScope);
            if (scope == null) {
                throw new APIManagementException("Scope '" + firstScope + "' not found.");
            }
            template.setScope(scope);
            template.setScopes(scope);
        } else {
            for (String scopeName : opScopes) {
                Scope scope = APIUtil.findScopeByKey(scopes, scopeName);
                if (scope == null) {
                    throw new APIManagementException("Resource Scope '" + scopeName + "' not found.");
                }
                template.setScopes(scope);
            }
        }
    }
    return template;
}
Also used : Extension(io.apicurio.datamodels.core.models.Extension) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate)

Example 28 with Target

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.Target in project carbon-apimgt by wso2.

the class AMDefaultKeyManagerImpl method loadConfiguration.

@Override
public void loadConfiguration(KeyManagerConfiguration configuration) throws APIManagementException {
    this.configuration = configuration;
    String username = (String) configuration.getParameter(APIConstants.KEY_MANAGER_USERNAME);
    String password = (String) configuration.getParameter(APIConstants.KEY_MANAGER_PASSWORD);
    String keyManagerServiceUrl = (String) configuration.getParameter(APIConstants.AUTHSERVER_URL);
    String dcrEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.CLIENT_REGISTRATION_ENDPOINT) != null) {
        dcrEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.CLIENT_REGISTRATION_ENDPOINT);
    } else {
        dcrEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(getTenantAwareContext().trim()).concat(APIConstants.KeyManager.KEY_MANAGER_OPERATIONS_DCR_ENDPOINT);
    }
    String tokenEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.TOKEN_ENDPOINT) != null) {
        tokenEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.TOKEN_ENDPOINT);
    } else {
        tokenEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat("/oauth2/token");
    }
    addKeyManagerConfigsAsSystemProperties(tokenEndpoint);
    String revokeEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.REVOKE_ENDPOINT) != null) {
        revokeEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.REVOKE_ENDPOINT);
    } else {
        revokeEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat("/oauth2/revoke");
    }
    String scopeEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.SCOPE_MANAGEMENT_ENDPOINT) != null) {
        scopeEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.SCOPE_MANAGEMENT_ENDPOINT);
    } else {
        scopeEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(getTenantAwareContext().trim()).concat(APIConstants.KEY_MANAGER_OAUTH2_SCOPES_REST_API_BASE_PATH);
    }
    String introspectionEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.INTROSPECTION_ENDPOINT) != null) {
        introspectionEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.INTROSPECTION_ENDPOINT);
    } else {
        introspectionEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(getTenantAwareContext().trim()).concat("/oauth2/introspect");
    }
    String userInfoEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.USERINFO_ENDPOINT) != null) {
        userInfoEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.USERINFO_ENDPOINT);
    } else {
        userInfoEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(getTenantAwareContext().trim()).concat(APIConstants.KeyManager.KEY_MANAGER_OPERATIONS_USERINFO_ENDPOINT);
    }
    dcrClient = Feign.builder().client(new ApacheFeignHttpClient(APIUtil.getHttpClient(dcrEndpoint))).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger()).requestInterceptor(new BasicAuthRequestInterceptor(username, password)).requestInterceptor(new TenantHeaderInterceptor(tenantDomain)).errorDecoder(new KMClientErrorDecoder()).target(DCRClient.class, dcrEndpoint);
    authClient = Feign.builder().client(new ApacheFeignHttpClient(APIUtil.getHttpClient(tokenEndpoint))).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger()).errorDecoder(new KMClientErrorDecoder()).encoder(new FormEncoder()).target(AuthClient.class, tokenEndpoint);
    introspectionClient = Feign.builder().client(new ApacheFeignHttpClient(APIUtil.getHttpClient(introspectionEndpoint))).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger()).requestInterceptor(new BasicAuthRequestInterceptor(username, password)).requestInterceptor(new TenantHeaderInterceptor(tenantDomain)).errorDecoder(new KMClientErrorDecoder()).encoder(new FormEncoder()).target(IntrospectionClient.class, introspectionEndpoint);
    scopeClient = Feign.builder().client(new ApacheFeignHttpClient(APIUtil.getHttpClient(scopeEndpoint))).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger()).requestInterceptor(new BasicAuthRequestInterceptor(username, password)).requestInterceptor(new TenantHeaderInterceptor(tenantDomain)).errorDecoder(new KMClientErrorDecoder()).target(ScopeClient.class, scopeEndpoint);
    userClient = Feign.builder().client(new ApacheFeignHttpClient(APIUtil.getHttpClient(userInfoEndpoint))).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger()).requestInterceptor(new BasicAuthRequestInterceptor(username, password)).requestInterceptor(new TenantHeaderInterceptor(tenantDomain)).errorDecoder(new KMClientErrorDecoder()).target(UserClient.class, userInfoEndpoint);
}
Also used : UserClient(org.wso2.carbon.apimgt.impl.kmclient.model.UserClient) BasicAuthRequestInterceptor(feign.auth.BasicAuthRequestInterceptor) Slf4jLogger(feign.slf4j.Slf4jLogger) AuthClient(org.wso2.carbon.apimgt.impl.kmclient.model.AuthClient) TenantHeaderInterceptor(org.wso2.carbon.apimgt.impl.kmclient.model.TenantHeaderInterceptor) DCRClient(org.wso2.carbon.apimgt.impl.kmclient.model.DCRClient) KMClientErrorDecoder(org.wso2.carbon.apimgt.impl.kmclient.KMClientErrorDecoder) GsonEncoder(feign.gson.GsonEncoder) ScopeClient(org.wso2.carbon.apimgt.impl.kmclient.model.ScopeClient) IntrospectionClient(org.wso2.carbon.apimgt.impl.kmclient.model.IntrospectionClient) GsonDecoder(feign.gson.GsonDecoder) ApacheFeignHttpClient(org.wso2.carbon.apimgt.impl.kmclient.ApacheFeignHttpClient) FormEncoder(org.wso2.carbon.apimgt.impl.kmclient.FormEncoder)

Example 29 with Target

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.Target in project carbon-apimgt by wso2.

the class ApplicationsApiServiceImpl method applicationsImportPost.

/**
 * Import an Application which has been exported to a zip file
 *
 * @param fileInputStream     Content stream of the zip file which contains exported Application
 * @param fileDetail          Meta information of the zip file
 * @param preserveOwner       If true, preserve the original owner of the application
 * @param skipSubscriptions   If true, skip subscriptions of the application
 * @param appOwner            Target owner of the application
 * @param skipApplicationKeys Skip application keys while importing
 * @param update              Update if existing application found or import
 * @param messageContext      Message Context
 * @return imported Application
 */
@Override
public Response applicationsImportPost(InputStream fileInputStream, Attachment fileDetail, Boolean preserveOwner, Boolean skipSubscriptions, String appOwner, Boolean skipApplicationKeys, Boolean update, MessageContext messageContext) throws APIManagementException {
    String ownerId;
    Application application;
    try {
        String username = RestApiCommonUtil.getLoggedInUsername();
        APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
        String extractedFolderPath = CommonUtil.getArchivePathOfExtractedDirectory(fileInputStream, ImportExportConstants.UPLOAD_APPLICATION_FILE_NAME);
        String jsonContent = ImportUtils.getApplicationDefinitionAsJson(extractedFolderPath);
        // Retrieving the field "data" in api.yaml/json and convert it to a JSON object for further processing
        JsonElement configElement = new JsonParser().parse(jsonContent).getAsJsonObject().get(APIConstants.DATA);
        ExportedApplication exportedApplication = new Gson().fromJson(configElement, ExportedApplication.class);
        // Retrieve the application DTO object from the aggregated exported application
        ApplicationDTO applicationDTO = exportedApplication.getApplicationInfo();
        if (!StringUtils.isBlank(appOwner)) {
            ownerId = appOwner;
        } else if (preserveOwner != null && preserveOwner) {
            ownerId = applicationDTO.getOwner();
        } else {
            ownerId = username;
        }
        if (!MultitenantUtils.getTenantDomain(ownerId).equals(MultitenantUtils.getTenantDomain(username))) {
            throw new APIManagementException("Cross Tenant Imports are not allowed", ExceptionCodes.TENANT_MISMATCH);
        }
        String applicationGroupId = String.join(",", applicationDTO.getGroups());
        if (applicationDTO.getGroups() != null && applicationDTO.getGroups().size() > 0) {
            ImportUtils.validateOwner(username, applicationGroupId, apiConsumer);
        }
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        if (APIUtil.isApplicationExist(ownerId, applicationDTO.getName(), applicationGroupId, organization) && update != null && update) {
            int appId = APIUtil.getApplicationId(applicationDTO.getName(), ownerId);
            Application oldApplication = apiConsumer.getApplicationById(appId);
            application = preProcessAndUpdateApplication(ownerId, applicationDTO, oldApplication, oldApplication.getUUID());
        } else {
            application = preProcessAndAddApplication(ownerId, applicationDTO, organization);
            update = Boolean.FALSE;
        }
        List<APIIdentifier> skippedAPIs = new ArrayList<>();
        if (skipSubscriptions == null || !skipSubscriptions) {
            skippedAPIs = ImportUtils.importSubscriptions(exportedApplication.getSubscribedAPIs(), ownerId, application, update, apiConsumer, organization);
        }
        Application importedApplication = apiConsumer.getApplicationById(application.getId());
        importedApplication.setOwner(ownerId);
        ApplicationInfoDTO importedApplicationDTO = ApplicationMappingUtil.fromApplicationToInfoDTO(importedApplication);
        URI location = new URI(RestApiConstants.RESOURCE_PATH_APPLICATIONS + "/" + importedApplicationDTO.getApplicationId());
        // check whether keys need to be skipped while import
        if (skipApplicationKeys == null || !skipApplicationKeys) {
            // if this is an update, old keys will be removed and the OAuth app will be overridden with new values
            if (update) {
                if (applicationDTO.getKeys().size() > 0 && importedApplication.getKeys().size() > 0) {
                    importedApplication.getKeys().clear();
                }
            }
            // Add application keys if present and keys does not exists in the current application
            if (applicationDTO.getKeys().size() > 0 && importedApplication.getKeys().size() == 0) {
                for (ApplicationKeyDTO applicationKeyDTO : applicationDTO.getKeys()) {
                    ImportUtils.addApplicationKey(ownerId, importedApplication, applicationKeyDTO, apiConsumer, update);
                }
            }
        }
        if (skippedAPIs.isEmpty()) {
            return Response.created(location).entity(importedApplicationDTO).build();
        } else {
            APIInfoListDTO skippedAPIListDTO = APIInfoMappingUtil.fromAPIInfoListToDTO(skippedAPIs);
            return Response.created(location).status(207).entity(skippedAPIListDTO).build();
        }
    } catch (URISyntaxException | UserStoreException | APIImportExportException e) {
        throw new APIManagementException("Error while importing Application", e);
    } catch (UnsupportedEncodingException e) {
        throw new APIManagementException("Error while Decoding apiId", e);
    } catch (IOException e) {
        throw new APIManagementException("Error while reading the application definition", e);
    }
}
Also used : ApplicationDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationDTO) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) ApplicationInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationInfoDTO) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApplicationKeyDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO) JsonElement(com.google.gson.JsonElement) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application) APIInfoListDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIInfoListDTO) JsonParser(com.google.gson.JsonParser)

Example 30 with Target

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.Target in project carbon-apimgt by wso2.

the class ImportUtils method validateOwner.

/**
 * Check whether a provided userId corresponds to a valid consumer of the store and subscribe if valid
 *
 * @param userId      Username of the Owner
 * @param groupId     The groupId to which the target subscriber belongs to
 * @param apiConsumer API Consumer
 * @throws APIManagementException if an error occurs while checking the validity of user
 */
public static void validateOwner(String userId, String groupId, APIConsumer apiConsumer) throws APIManagementException {
    Subscriber subscriber = apiConsumer.getSubscriber(userId);
    try {
        if (subscriber == null && !APIUtil.isPermissionCheckDisabled()) {
            APIUtil.checkPermission(userId, APIConstants.Permissions.API_SUBSCRIBE);
            apiConsumer.addSubscriber(userId, groupId);
        }
    } catch (APIManagementException e) {
        throw new APIManagementException("Provided Application Owner is Invalid", e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber)

Aggregations

BLangAssignment (org.wso2.ballerinalang.compiler.tree.statements.BLangAssignment)11 DiagnosticPos (org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos)11 ArrayList (java.util.ArrayList)9 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)8 File (java.io.File)7 IOException (java.io.IOException)7 Element (org.w3c.dom.Element)6 BLangBinaryExpr (org.wso2.ballerinalang.compiler.tree.expressions.BLangBinaryExpr)5 Target (org.wso2.carbon.apimgt.common.analytics.publishers.dto.Target)5 Gson (com.google.gson.Gson)4 List (java.util.List)4 Map (java.util.Map)4 OMElement (org.apache.axiom.om.OMElement)4 NodeList (org.w3c.dom.NodeList)4 BLangIndexBasedAccess (org.wso2.ballerinalang.compiler.tree.expressions.BLangIndexBasedAccess)4 JsonElement (com.google.gson.JsonElement)3 FileOutputStream (java.io.FileOutputStream)3 HashMap (java.util.HashMap)3 Iterator (java.util.Iterator)3 Set (java.util.Set)3