Search in sources :

Example 61 with Scope

use of org.wso2.ballerinalang.compiler.semantics.model.Scope in project carbon-business-process by wso2.

the class BaseExecutionService method createExecutionVariable.

protected Response createExecutionVariable(Execution execution, boolean override, int variableType, HttpServletRequest httpServletRequest, UriInfo uriInfo) {
    Object result = null;
    Response.ResponseBuilder responseBuilder = Response.ok();
    List<RestVariable> inputVariables = new ArrayList<>();
    List<RestVariable> resultVariables = new ArrayList<>();
    if (Utils.isApplicationJsonRequest(httpServletRequest)) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            @SuppressWarnings("unchecked") List<Object> variableObjects = (List<Object>) objectMapper.readValue(httpServletRequest.getInputStream(), List.class);
            for (Object restObject : variableObjects) {
                RestVariable restVariable = objectMapper.convertValue(restObject, RestVariable.class);
                inputVariables.add(restVariable);
            }
        } catch (Exception e) {
            throw new ActivitiIllegalArgumentException("Failed to serialize to a RestVariable instance", e);
        }
    } else if (Utils.isApplicationXmlRequest(httpServletRequest)) {
        JAXBContext jaxbContext = null;
        try {
            jaxbContext = JAXBContext.newInstance(RestVariableCollection.class);
            XMLInputFactory inputFactory = XMLInputFactory.newInstance();
            inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
            inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
            XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(new StreamSource(httpServletRequest.getInputStream()));
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            RestVariableCollection restVariableCollection = (RestVariableCollection) jaxbUnmarshaller.unmarshal(xmlReader);
            if (restVariableCollection == null) {
                throw new ActivitiIllegalArgumentException("xml request body could not be transformed to a " + "RestVariable Collection instance.");
            }
            List<RestVariable> restVariableList = restVariableCollection.getRestVariables();
            if (restVariableList.size() == 0) {
                throw new ActivitiIllegalArgumentException("xml request body could not identify any rest " + "variables to be updated");
            }
            for (RestVariable restVariable : restVariableList) {
                inputVariables.add(restVariable);
            }
        } catch (JAXBException | IOException | XMLStreamException e) {
            throw new ActivitiIllegalArgumentException("xml request body could not be transformed to a " + "RestVariable instance.", e);
        }
    }
    if (inputVariables.size() == 0) {
        throw new ActivitiIllegalArgumentException("Request didn't contain a list of variables to create.");
    }
    RestVariable.RestVariableScope sharedScope = null;
    RestVariable.RestVariableScope varScope = null;
    Map<String, Object> variablesToSet = new HashMap<String, Object>();
    for (RestVariable var : inputVariables) {
        // Validate if scopes match
        varScope = var.getVariableScope();
        if (var.getName() == null) {
            throw new ActivitiIllegalArgumentException("Variable name is required");
        }
        if (varScope == null) {
            varScope = RestVariable.RestVariableScope.LOCAL;
        }
        if (sharedScope == null) {
            sharedScope = varScope;
        }
        if (varScope != sharedScope) {
            throw new ActivitiIllegalArgumentException("Only allowed to update multiple variables in the same scope.");
        }
        if (!override && hasVariableOnScope(execution, var.getName(), varScope)) {
            throw new BPMNConflictException("Variable '" + var.getName() + "' is already present on execution '" + execution.getId() + "'.");
        }
        Object actualVariableValue = new RestResponseFactory().getVariableValue(var);
        variablesToSet.put(var.getName(), actualVariableValue);
        resultVariables.add(new RestResponseFactory().createRestVariable(var.getName(), actualVariableValue, varScope, execution.getId(), variableType, false, uriInfo.getBaseUri().toString()));
    }
    if (!variablesToSet.isEmpty()) {
        RuntimeService runtimeService = BPMNOSGIService.getRuntimeService();
        if (sharedScope == RestVariable.RestVariableScope.LOCAL) {
            runtimeService.setVariablesLocal(execution.getId(), variablesToSet);
        } else {
            if (execution.getParentId() != null) {
                // Explicitly set on parent, setting non-local variables on execution itself will override local-variables if exists
                runtimeService.setVariables(execution.getParentId(), variablesToSet);
            } else {
                // Standalone task, no global variables possible
                throw new ActivitiIllegalArgumentException("Cannot set global variables on execution '" + execution.getId() + "', task is not part of process.");
            }
        }
    }
    RestVariableCollection restVariableCollection = new RestVariableCollection();
    restVariableCollection.setRestVariables(resultVariables);
    responseBuilder.entity(restVariableCollection);
    return responseBuilder.status(Response.Status.CREATED).build();
}
Also used : BPMNConflictException(org.wso2.carbon.bpmn.rest.common.exception.BPMNConflictException) XMLStreamReader(javax.xml.stream.XMLStreamReader) JAXBContext(javax.xml.bind.JAXBContext) RestVariable(org.wso2.carbon.bpmn.rest.engine.variable.RestVariable) ActivitiIllegalArgumentException(org.activiti.engine.ActivitiIllegalArgumentException) Unmarshaller(javax.xml.bind.Unmarshaller) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) RestResponseFactory(org.wso2.carbon.bpmn.rest.common.RestResponseFactory) RuntimeService(org.activiti.engine.RuntimeService) StreamSource(javax.xml.transform.stream.StreamSource) ActivitiException(org.activiti.engine.ActivitiException) BPMNContentNotSupportedException(org.wso2.carbon.bpmn.rest.common.exception.BPMNContentNotSupportedException) XMLStreamException(javax.xml.stream.XMLStreamException) ActivitiObjectNotFoundException(org.activiti.engine.ActivitiObjectNotFoundException) BPMNConflictException(org.wso2.carbon.bpmn.rest.common.exception.BPMNConflictException) ActivitiIllegalArgumentException(org.activiti.engine.ActivitiIllegalArgumentException) JAXBException(javax.xml.bind.JAXBException) DataResponse(org.wso2.carbon.bpmn.rest.model.common.DataResponse) Response(javax.ws.rs.core.Response) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 62 with Scope

use of org.wso2.ballerinalang.compiler.semantics.model.Scope in project product-iots by wso2.

the class QSGUtils method getOAuthToken.

public static String getOAuthToken() {
    QSGUtils.initConfig();
    ClientCredentials clientCredentials = getClientCredentials();
    String authorizationStr = clientCredentials.getClientKey() + ":" + clientCredentials.getClientSecret();
    String authHeader = "Basic " + new String(Base64.encodeBase64(authorizationStr.getBytes()));
    HashMap<String, String> headers = new HashMap<String, String>();
    // Set the form params
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("username", EMMQSGConfig.getInstance().getUsername()));
    urlParameters.add(new BasicNameValuePair("password", EMMQSGConfig.getInstance().getPassword()));
    urlParameters.add(new BasicNameValuePair("grant_type", "password"));
    urlParameters.add(new BasicNameValuePair("scope", "user:view user:manage user:admin:reset-password role:view role:manage policy:view policy:manage " + "application:manage appm:administration appm:create appm:publish appm:update appm:read"));
    // Set the headers
    headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_URL_ENCODED);
    headers.put(Constants.Header.AUTH, authHeader);
    HTTPResponse httpResponse = HTTPInvoker.sendHTTPPostWithURLParams(EMMQSGConfig.getInstance().getOauthEndPoint(), urlParameters, headers);
    if (httpResponse.getResponseCode() == Constants.HTTPStatus.OK) {
        try {
            JSONObject jsonObject = (JSONObject) new JSONParser().parse(httpResponse.getResponse());
            return (String) jsonObject.get("access_token");
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    return null;
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) JSONObject(org.json.simple.JSONObject) HashMap(java.util.HashMap) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HTTPResponse(org.wso2.mdm.qsg.dto.HTTPResponse) ArrayList(java.util.ArrayList) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) ClientCredentials(org.wso2.mdm.qsg.dto.ClientCredentials)

Example 63 with Scope

use of org.wso2.ballerinalang.compiler.semantics.model.Scope in project carbon-apimgt by wso2.

the class APIPublisherImplTestCase method testUpdateScopeToApi.

@Test(description = "update existing Scope to API")
public void testUpdateScopeToApi() throws APIManagementException, IOException {
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    API api = SampleTestObjectCreator.createDefaultAPI().build();
    String uuid = api.getId();
    Mockito.when(apiDAO.getAPI(uuid)).thenReturn(api);
    GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
    APIGateway gateway = Mockito.mock(APIGateway.class);
    IdentityProvider identityProvider = Mockito.mock(IdentityProvider.class);
    KeyManager keyManager = Mockito.mock(KeyManager.class);
    APIPublisherImpl apiPublisher = getApiPublisherImpl(identityProvider, apiDAO, gatewaySourceGenerator, gateway, keyManager);
    String oldSwagger = IOUtils.toString(new FileInputStream("src" + File.separator + "test" + File.separator + "resources" + File.separator + "swagger" + File.separator + "swaggerWithAuthorization" + ".yaml"));
    Scope scope = new Scope("apim:api_create", "apim:api_create");
    Mockito.when(apiDAO.getApiSwaggerDefinition(uuid)).thenReturn(oldSwagger);
    Mockito.when(keyManager.updateScope(scope)).thenReturn(true);
    Mockito.when(keyManager.retrieveScope("apim:api_create")).thenReturn(new Scope("apim:api_create", "Create " + "API"));
    apiPublisher.updateScopeOfTheApi(api.getId(), scope);
}
Also used : Scope(org.wso2.carbon.apimgt.core.models.Scope) API(org.wso2.carbon.apimgt.core.models.API) IdentityProvider(org.wso2.carbon.apimgt.core.api.IdentityProvider) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) KeyManager(org.wso2.carbon.apimgt.core.api.KeyManager) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) FileInputStream(java.io.FileInputStream) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) Test(org.testng.annotations.Test)

Example 64 with Scope

use of org.wso2.ballerinalang.compiler.semantics.model.Scope in project carbon-apimgt by wso2.

the class APIDefinitionFromSwagger20TestCase method testUpdateScope.

@Test()
public void testUpdateScope() throws IOException, APIManagementException {
    APIDefinitionFromSwagger20 apiDefinitionFromSwagger20 = new APIDefinitionFromSwagger20();
    String sampleApi = IOUtils.toString(this.getClass().getResourceAsStream(File.separator + "swagger" + File.separator + "swaggerWithAuthorization.yaml"));
    Scope scope = new Scope();
    scope.setName("apim:api_create");
    scope.setDescription("Delete API");
    String scopeAddedSwagger = apiDefinitionFromSwagger20.updateScopesOnSwaggerDefinition(sampleApi, scope);
    Map<String, String> scopes = apiDefinitionFromSwagger20.getScopesFromSecurityDefinition(scopeAddedSwagger);
    Assert.assertTrue(scopes.containsKey("apim:api_create"));
// commented due to parallel test run
// Assert.assertEquals(scopes.get("apim:api_delete").getDescription(),"Delete API");
}
Also used : Scope(org.wso2.carbon.apimgt.core.models.Scope) Test(org.testng.annotations.Test)

Example 65 with Scope

use of org.wso2.ballerinalang.compiler.semantics.model.Scope in project carbon-apimgt by wso2.

the class APIDefinitionFromSwagger20TestCase method testAddNewScopeToSecurityDefinitionExistingSwaggerNonExisting.

@Test()
public void testAddNewScopeToSecurityDefinitionExistingSwaggerNonExisting() throws IOException, APIManagementException {
    APIDefinitionFromSwagger20 apiDefinitionFromSwagger20 = new APIDefinitionFromSwagger20();
    String sampleApi = IOUtils.toString(this.getClass().getResourceAsStream(File.separator + "swagger" + File.separator + "swaggerWithAuthorizationApiKey.yaml"));
    Scope scope = new Scope();
    scope.setName("apim:api_delete");
    scope.setDescription("Delete API");
    String scopeAddedSwagger = apiDefinitionFromSwagger20.addScopeToSwaggerDefinition(sampleApi, scope);
    Map<String, String> scopes = apiDefinitionFromSwagger20.getScopesFromSecurityDefinition(scopeAddedSwagger);
    Assert.assertTrue(scopes.containsKey("apim:api_delete"));
}
Also used : Scope(org.wso2.carbon.apimgt.core.models.Scope) Test(org.testng.annotations.Test)

Aggregations

Scope (org.wso2.carbon.apimgt.core.models.Scope)41 HashMap (java.util.HashMap)25 RestVariable (org.wso2.carbon.bpmn.rest.engine.variable.RestVariable)25 Test (org.testng.annotations.Test)23 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)19 Response (javax.ws.rs.core.Response)16 ScopeInfo (org.wso2.carbon.apimgt.core.auth.dto.ScopeInfo)15 FileInputStream (java.io.FileInputStream)14 API (org.wso2.carbon.apimgt.core.models.API)14 ArrayList (java.util.ArrayList)13 KeyManager (org.wso2.carbon.apimgt.core.api.KeyManager)13 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)13 Map (java.util.Map)12 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)12 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)12 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)12 IdentityProvider (org.wso2.carbon.apimgt.core.api.IdentityProvider)11 RestResponseFactory (org.wso2.carbon.bpmn.rest.common.RestResponseFactory)11 ActivitiObjectNotFoundException (org.activiti.engine.ActivitiObjectNotFoundException)10 Scope (org.wso2.ballerinalang.compiler.semantics.model.Scope)10