Search in sources :

Example 61 with Resource

use of org.wso2.carbon.registry.api.Resource in project carbon-apimgt by wso2.

the class ApiApiServiceImpl method apiCountOverTimeGet.

/**
 * Get list of API count information
 *
 * @param startTime Filter for start time stamp
 * @param endTime   Filter for end time stamp
 * @param createdBy Filter for created user
 * @param request   MSF4J request
 * @return API Count information
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response apiCountOverTimeGet(String startTime, String endTime, String createdBy, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        log.debug("Retrieving APIs created over time. [From: {}  To: {} Created By: {}]", startTime, endTime, createdBy);
        Analyzer analyzer = RestApiUtil.getAnalyzer(username);
        ZoneId requestTimezone = RestApiUtil.getRequestTimeZone(startTime);
        List<APICount> apiCountList = analyzer.getAPICount(fromISO8601ToInstant(startTime), fromISO8601ToInstant(endTime), createdBy);
        APICountListDTO apiCountListDTO = AnalyticsMappingUtil.fromAPICountToListDTO(apiCountList, requestTimezone);
        return Response.ok().entity(apiCountListDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving API created over time info";
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : APICount(org.wso2.carbon.apimgt.core.models.analytics.APICount) ZoneId(java.time.ZoneId) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APICountListDTO(org.wso2.carbon.apimgt.rest.api.analytics.dto.APICountListDTO) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) Analyzer(org.wso2.carbon.apimgt.core.api.Analyzer)

Example 62 with Resource

use of org.wso2.carbon.registry.api.Resource in project carbon-apimgt by wso2.

the class PolicyExportManager method getApiPolicySiddhiApps.

/**
 * Get execution plan/ siddhi apps for custom policies.
 *
 * @param apiPolicies APIPolicy object list
 * @return Map<String, String> containing execution plan name and execution plans.
 * @throws APITemplateException If template generating fails
 */
private List<Map<String, String>> getApiPolicySiddhiApps(List<APIPolicy> apiPolicies) throws APITemplateException {
    if (log.isDebugEnabled()) {
        log.debug("Get execution plans for API policies.");
    }
    List<Map<String, String>> policies = new ArrayList<>();
    Map<String, String> siddhiApps = new HashMap<>();
    APIThrottlePolicyTemplateBuilder templateBuilder;
    for (APIPolicy apiPolicy : apiPolicies) {
        templateBuilder = new APIThrottlePolicyTemplateBuilder(apiPolicy);
        if (apiPolicy.getPipelines() != null) {
            siddhiApps = templateBuilder.getThrottlePolicyTemplateForPipelines();
        }
        siddhiApps.put(RESOURCE + apiPolicy.getPolicyName() + DEFAULT, templateBuilder.getThrottlePolicyTemplateForAPILevelDefaultCondition());
        policies.add(siddhiApps);
    }
    return policies;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) APIThrottlePolicyTemplateBuilder(org.wso2.carbon.apimgt.core.template.APIThrottlePolicyTemplateBuilder) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) HashMap(java.util.HashMap) Map(java.util.Map)

Example 63 with Resource

use of org.wso2.carbon.registry.api.Resource in project carbon-apimgt by wso2.

the class ApisApiServiceImplTestCase method apisApiIdGatewayConfigGetTestCase.

@Test
public void apisApiIdGatewayConfigGetTestCase() throws Exception {
    ApisApiServiceImpl apisApiService = new ApisApiServiceImpl();
    APIMgtAdminServiceImpl adminService = Mockito.mock(APIMgtAdminServiceImpl.class);
    String apiID = UUID.randomUUID().toString();
    String gatewayConfig = "package deployment.org.wso2.apim;\n" + "import ballerina.net.http;\n" + "\n" + "@http:BasePath(\"/aaa1\")\n" + "service aaa1_1489666767745 {\n" + "\n" + "    @http:GET\n" + "    @http:Path(\"/*\")\n" + "    resource get_star_ (message m) {\n" + "        http:ClientConnector productionEndpoint = create http:ClientConnector(getUrlFromKey" + "(\"aaa1_1.0.0__ep\"));\n   http:ClientConnector sandboxEndpoint = create http:ClientConnector" + "(getUrlFromKey(\"aaa1_1.0.0__ep\"));\n message response;\n string endpointType;\n string " + "productionType;\n \n \n      endpointType = \"production\";\n productionType = \"production\";\n" + "\n      if (endpointType == productionType) {\n" + "            response = http:ClientConnector.execute(productionEndpoint, \"get\", \"\", m);\n" + "        } else {\n" + "            response = http:ClientConnector.execute(sandboxEndpoint, \"get\", \"\", m);\n" + "        }\n" + "\n" + "        reply response;\n" + "    }\n" + "}";
    Mockito.when(adminService.getAPIGatewayServiceConfig(apiID)).thenReturn(gatewayConfig);
    APIManagerFactory instance = Mockito.mock(APIManagerFactory.class);
    PowerMockito.mockStatic(APIManagerFactory.class);
    PowerMockito.when(APIManagerFactory.getInstance()).thenReturn(instance);
    Mockito.when(instance.getAPIMgtAdminService()).thenReturn(adminService);
    Response response = apisApiService.apisApiIdGatewayConfigGet(apiID, null, getRequest());
    Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
}
Also used : Response(javax.ws.rs.core.Response) APIManagerFactory(org.wso2.carbon.apimgt.core.impl.APIManagerFactory) APIMgtAdminServiceImpl(org.wso2.carbon.apimgt.core.impl.APIMgtAdminServiceImpl) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 64 with Resource

use of org.wso2.carbon.registry.api.Resource in project carbon-apimgt by wso2.

the class OAuth2Authenticator method getRestAPIResource.

/*
    * This methos is used to get the rest api resource based on the api context
    * @param Request
    * @return String : api resource object
    * @throws APIMgtSecurityException if resource could not be found.
    * */
private String getRestAPIResource(Request request) throws APIMgtSecurityException {
    // todo improve to get appname as a property in the Request
    String path = (String) request.getProperty(APIConstants.REQUEST_URL);
    String restAPIResource = null;
    // this is publisher API so pick that API
    try {
        if (path.contains(RestApiConstants.REST_API_PUBLISHER_CONTEXT)) {
            restAPIResource = RestApiUtil.getPublisherRestAPIResource();
        } else if (path.contains(RestApiConstants.REST_API_STORE_CONTEXT)) {
            restAPIResource = RestApiUtil.getStoreRestAPIResource();
        } else if (path.contains(RestApiConstants.REST_API_ADMIN_CONTEXT)) {
            restAPIResource = RestApiUtil.getAdminRestAPIResource();
        } else if (path.contains(RestApiConstants.REST_API_ANALYTICS_CONTEXT)) {
            restAPIResource = RestApiUtil.getAnalyticsRestAPIResource();
        } else {
            throw new APIMgtSecurityException("No matching Rest Api definition found for path:" + path);
        }
    } catch (APIManagementException e) {
        throw new APIMgtSecurityException(e.getMessage(), ExceptionCodes.AUTH_GENERAL_ERROR);
    }
    return restAPIResource;
}
Also used : APIMgtSecurityException(org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException)

Example 65 with Resource

use of org.wso2.carbon.registry.api.Resource in project airavata by apache.

the class SecureClient method main.

public static void main(String[] args) throws Exception {
    Scanner scanner = new Scanner(System.in);
    // register client or use existing client
    System.out.println("");
    System.out.println("Please select from the following options:");
    System.out.println("1. Register the client as an OAuth application.");
    System.out.println("2. Client is already registered. Use the existing credentials.");
    String opInput = scanner.next();
    int option = Integer.valueOf(opInput.trim());
    String consumerId = null;
    String consumerSecret = null;
    if (option == 1) {
        // register OAuth application - this happens once during initialization of the gateway.
        /**
         **********************Start obtaining input from user****************************
         */
        System.out.println("");
        System.out.println("Registering an OAuth application representing the client....");
        System.out.println("Please enter following information as you prefer, or use defaults.");
        System.out.println("OAuth application name: (default:" + Properties.appName + ", press 'd' to use default value.)");
        String appNameInput = scanner.next();
        String appName = null;
        if (appNameInput.trim().equals("d")) {
            appName = Properties.appName;
        } else {
            appName = appNameInput.trim();
        }
        System.out.println("Consumer Id: (default:" + Properties.consumerID + ", press 'd' to use default value.)");
        String consumerIdInput = scanner.next();
        if (consumerIdInput.trim().equals("d")) {
            consumerId = Properties.consumerID;
        } else {
            consumerId = consumerIdInput.trim();
        }
        System.out.println("Consumer Secret: (default:" + Properties.consumerSecret + ", press 'd' to use default value.)");
        String consumerSecInput = scanner.next();
        if (consumerSecInput.trim().equals("d")) {
            consumerSecret = Properties.consumerSecret;
        } else {
            consumerSecret = consumerSecInput.trim();
        }
        /**
         ********************* Perform registration of the client as an OAuth app**************************
         */
        try {
            ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
            OAuthAppRegisteringClient authAppRegisteringClient = new OAuthAppRegisteringClient(Properties.oauthAuthzServerURL, Properties.adminUserName, Properties.adminPassword, configContext);
            OAuthConsumerAppDTO appDTO = authAppRegisteringClient.registerApplication(appName, consumerId, consumerSecret);
            /**
             ******************* Complete registering the client **********************************************
             */
            System.out.println("");
            System.out.println("Registered OAuth app successfully. Following is app's details:");
            System.out.println("App Name: " + appDTO.getApplicationName());
            System.out.println("Consumer ID: " + appDTO.getOauthConsumerKey());
            System.out.println("Consumer Secret: " + appDTO.getOauthConsumerSecret());
            System.out.println("");
        } catch (AiravataSecurityException e) {
            e.printStackTrace();
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    } else if (option == 2) {
        System.out.println("");
        System.out.println("Enter Consumer Id: ");
        consumerId = scanner.next().trim();
        System.out.println("Enter Consumer Secret: ");
        consumerSecret = scanner.next().trim();
    }
    // obtain OAuth access token
    /**
     **********************Start obtaining input from user****************************
     */
    System.out.println("");
    System.out.println("Please select the preferred grant type: (or press d to use the default option" + Properties.grantType + ")");
    System.out.println("1. Resource Owner Password Credential.");
    System.out.println("2. Client Credential.");
    String grantTypeInput = scanner.next().trim();
    int grantType = 0;
    if (grantTypeInput.equals("d")) {
        grantType = Properties.grantType;
    } else {
        grantType = Integer.valueOf(grantTypeInput);
    }
    String userName = null;
    String password = null;
    if (grantType == 1) {
        System.out.println("Obtaining OAuth access token via 'Resource Owner Password' grant type....");
        System.out.println("Please enter following information as you prefer, or use defaults.");
        System.out.println("End user's name: (default:" + Properties.userName + ", press 'd' to use default value.)");
        String userNameInput = scanner.next();
        if (userNameInput.trim().equals("d")) {
            userName = Properties.userName;
        } else {
            userName = userNameInput.trim();
        }
        System.out.println("End user's password: (default:" + Properties.password + ", press 'd' to use default value.)");
        String passwordInput = scanner.next();
        if (passwordInput.trim().equals("d")) {
            password = Properties.password;
        } else {
            password = passwordInput.trim();
        }
    } else if (grantType == 2) {
        System.out.println("");
        System.out.println("Please enter the user name to be passed: ");
        String userNameInput = scanner.next();
        userName = userNameInput.trim();
        System.out.println("");
        System.out.println("Obtaining OAuth access token via 'Client Credential' grant type...' grant type....");
    }
    /**
     *************************** Finish obtaining input from user******************************************
     */
    try {
        // obtain the OAuth token for the specified end user.
        String accessToken = new OAuthTokenRetrievalClient().retrieveAccessToken(consumerId, consumerSecret, userName, password, grantType);
        System.out.println("");
        System.out.println("OAuth access token is: " + accessToken);
        // invoke Airavata API by the SecureClient, on behalf of the user.
        System.out.println("");
        System.out.println("Invoking Airavata API...");
        System.out.println("Enter the access token to be used: (default:" + accessToken + ", press 'd' to use default value.)");
        String accessTokenInput = scanner.next();
        String acTk = null;
        if (accessTokenInput.trim().equals("d")) {
            acTk = accessToken;
        } else {
            acTk = accessTokenInput.trim();
        }
        // obtain as input, the method to be invoked
        System.out.println("");
        System.out.println("Enter the number corresponding to the method to be invoked: ");
        System.out.println("1. getAPIVersion");
        System.out.println("2. getAllAppModules");
        System.out.println("3. addGateway");
        String methodNumberString = scanner.next();
        int methodNumber = Integer.valueOf(methodNumberString.trim());
        Airavata.Client client = createAiravataClient(Properties.SERVER_HOST, Properties.SERVER_PORT);
        AuthzToken authzToken = new AuthzToken();
        authzToken.setAccessToken(acTk);
        Map<String, String> claimsMap = new HashMap<>();
        claimsMap.put("userName", userName);
        claimsMap.put("email", "hasini@gmail.com");
        authzToken.setClaimsMap(claimsMap);
        if (methodNumber == 1) {
            String version = client.getAPIVersion(authzToken);
            System.out.println("");
            System.out.println("Airavata API version: " + version);
            System.out.println("");
        } else if (methodNumber == 2) {
            System.out.println("");
            System.out.println("Enter the gateway id: ");
            String gatewayId = scanner.next().trim();
            List<ApplicationModule> appModules = client.getAllAppModules(authzToken, gatewayId);
            System.out.println("Output of getAllAppModuels: ");
            for (ApplicationModule appModule : appModules) {
                System.out.println(appModule.getAppModuleName());
            }
            System.out.println("");
            System.out.println("");
        } else if (methodNumber == 3) {
            System.out.println("");
            System.out.println("Enter the gateway id: ");
            String gatewayId = scanner.next().trim();
            Gateway gateway = new Gateway(gatewayId, GatewayApprovalStatus.REQUESTED);
            gateway.setDomain("airavata.org");
            gateway.setEmailAddress("airavata@apache.org");
            gateway.setGatewayName("airavataGW");
            String output = client.addGateway(authzToken, gateway);
            System.out.println("");
            System.out.println("Output of addGateway: " + output);
            System.out.println("");
        }
    } catch (InvalidRequestException e) {
        e.printStackTrace();
    } catch (TException e) {
        e.printStackTrace();
    } catch (AiravataSecurityException e) {
        e.printStackTrace();
    }
}
Also used : TException(org.apache.thrift.TException) Scanner(java.util.Scanner) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) HashMap(java.util.HashMap) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO) TException(org.apache.thrift.TException) InvalidRequestException(org.apache.airavata.model.error.InvalidRequestException) AiravataClientException(org.apache.airavata.model.error.AiravataClientException) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException) ApplicationModule(org.apache.airavata.model.appcatalog.appdeployment.ApplicationModule) Gateway(org.apache.airavata.model.workspace.Gateway) AuthzToken(org.apache.airavata.model.security.AuthzToken) List(java.util.List) InvalidRequestException(org.apache.airavata.model.error.InvalidRequestException) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException) Airavata(org.apache.airavata.api.Airavata)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)111 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)102 HashMap (java.util.HashMap)91 Test (org.testng.annotations.Test)64 HTTPCarbonMessage (org.wso2.transport.http.netty.message.HTTPCarbonMessage)59 HTTPTestRequest (org.ballerinalang.test.services.testutils.HTTPTestRequest)56 HttpMessageDataStreamer (org.wso2.transport.http.netty.message.HttpMessageDataStreamer)53 BJSON (org.ballerinalang.model.values.BJSON)46 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)38 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)29 BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)27 APIMgtAdminService (org.wso2.carbon.apimgt.core.api.APIMgtAdminService)24 CharonException (org.wso2.charon3.core.exceptions.CharonException)24 IOException (java.io.IOException)23 Map (java.util.Map)20 SCIMResponse (org.wso2.charon3.core.protocol.SCIMResponse)20 NotFoundException (org.wso2.charon3.core.exceptions.NotFoundException)17 SCIMResourceTypeSchema (org.wso2.charon3.core.schema.SCIMResourceTypeSchema)17 ArrayList (java.util.ArrayList)15 InternalErrorException (org.wso2.charon3.core.exceptions.InternalErrorException)15