Search in sources :

Example 21 with Names

use of org.wso2.ballerinalang.compiler.util.Names in project carbon-apimgt by wso2.

the class APIPublisherImplTestCase method testUpdateAPIException.

@Test(description = "Exception when updating API")
public void testUpdateAPIException() throws APIManagementException {
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
    GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
    APIGateway gateway = Mockito.mock(APIGateway.class);
    IdentityProvider identityProvider = Mockito.mock(IdentityProvider.class);
    PolicyDAO policyDAO = Mockito.mock(PolicyDAO.class);
    Policy apiPolicy = new APIPolicy(APIMgtConstants.DEFAULT_API_POLICY);
    apiPolicy.setUuid(UUID.randomUUID().toString());
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.api, APIMgtConstants.DEFAULT_API_POLICY)).thenReturn(apiPolicy);
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, GOLD_TIER)).thenReturn(new SubscriptionPolicy(GOLD_TIER));
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, SILVER_TIER)).thenReturn(new SubscriptionPolicy(SILVER_TIER));
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, BRONZE_TIER)).thenReturn(new SubscriptionPolicy(BRONZE_TIER));
    APIPublisherImpl apiPublisher = getApiPublisherImpl(identityProvider, apiDAO, apiLifecycleManager, gatewaySourceGenerator, gateway, policyDAO);
    API.APIBuilder api = SampleTestObjectCreator.createDefaultAPI();
    String uuid = api.getId();
    Mockito.when(apiDAO.getAPI(uuid)).thenReturn(api.build());
    Mockito.when(identityProvider.getRoleId(ADMIN_ROLE)).thenReturn(ADMIN_ROLE_ID);
    Mockito.when(identityProvider.getRoleId(DEVELOPER_ROLE)).thenReturn(DEVELOPER_ROLE_ID);
    // APIMgtDAOException
    Mockito.doThrow(new APIMgtDAOException("Error occurred while updating the API - " + api.getName())).when(apiDAO).updateAPI(uuid, api.build());
    Mockito.when(apiDAO.getApiSwaggerDefinition(api.getId())).thenReturn(SampleTestObjectCreator.apiDefinition);
    try {
        apiPublisher.updateAPI(api);
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error occurred while updating the API - " + api.getName());
    }
    // ParseException
    try {
        apiPublisher.updateAPI(api.apiPermission("data{{]"));
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error occurred while parsing the permission json from swagger - " + api.getName());
    }
    // GatewayException
    Mockito.doThrow(GatewayException.class).when(gateway).updateAPI(api.apiPermission("").build());
    try {
        apiPublisher.updateAPI(api.apiPermission(""));
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error occurred while updating API - " + api.getName() + " in gateway");
    }
    // Error path
    // When Parse Exception is thrown during getAPIByUUID - replacing group ids with names
    Mockito.when(apiDAO.getAPI(uuid)).thenReturn(api.apiPermission("data{{]").build());
    try {
        apiPublisher.updateAPI(api.apiPermission("data{{]"));
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error occurred while parsing the permission json string for API " + api.getName());
    }
}
Also used : SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIBuilder(org.wso2.carbon.apimgt.core.models.API.APIBuilder) IdentityProvider(org.wso2.carbon.apimgt.core.api.IdentityProvider) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) APILifecycleManager(org.wso2.carbon.apimgt.core.api.APILifecycleManager) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) API(org.wso2.carbon.apimgt.core.models.API) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) PolicyDAO(org.wso2.carbon.apimgt.core.dao.PolicyDAO) Test(org.testng.annotations.Test)

Example 22 with Names

use of org.wso2.ballerinalang.compiler.util.Names in project carbon-apimgt by wso2.

the class DefaultIdentityProviderImplTestCase method testGetRoleNamesOfUser.

@Test
public void testGetRoleNamesOfUser() throws Exception {
    SCIMServiceStub scimServiceStub = Mockito.mock(SCIMServiceStub.class);
    UserNameMapper userNameMapper = Mockito.mock(UserNameMapperImpl.class);
    DefaultIdentityProviderImpl idpImpl = new DefaultIdentityProviderImpl(scimServiceStub, userNameMapper);
    String validUserId = "a42b4760-120d-432e-8042-4a7f12e3346c";
    String roleName1 = "subscriber";
    String roleId1 = "fb5aaf9c-1fdf-4b2d-86bc-6e3203b99618";
    String roleName2 = "manager";
    String roleId2 = "097435bc-c460-402b-9137-8ab65fd28c3e";
    String roleName3 = "engineer";
    String roleId3 = "ac093278-9343-466c-8a71-af47921a575b";
    List<String> roleNames = new ArrayList<>();
    roleNames.add(roleName1);
    roleNames.add(roleName2);
    roleNames.add(roleName3);
    String successResponseBody = "{\"emails\":[{\"type\":\"home\",\"value\":\"john_home.com\"},{\"type\":\"work\"" + ",\"value\":\"john_work.com\"}],\"meta\":{\"created\":\"2017-06-02T10:12:26\",\"location\":" + "\"https://localhost:9443/wso2/scim/Users/" + validUserId + "\",\"lastModified\":" + "\"2017-06-02T10:12:26\"},\"schemas\":[\"urn:scim:schemas:core:1.0\"],\"name\":{\"familyName\":" + "\"Smith\",\"givenName\":\"John\"},\"groups\":[{\"display\":\"" + roleName1 + "\",\"value\":\"" + roleId1 + "\"},{\"display\":\"" + roleName2 + "\",\"value\":\"" + roleId2 + "\"},{\"display\":\"" + roleName3 + "\",\"value\":\"" + roleId3 + "\"}],\"id\":\"" + validUserId + "\",\"userName\":" + "\"John\"}";
    Response successfulResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body(successResponseBody.getBytes()).build();
    Mockito.when(scimServiceStub.getUser(validUserId)).thenReturn(successfulResponse);
    List<String> roles = idpImpl.getRoleNamesOfUser(validUserId);
    Assert.assertEquals(roleNames.size(), roles.size());
    roles.forEach(roleName -> Assert.assertTrue(roleNames.contains(roleName)));
    // Error case - When response is null
    String invalidUserIdResponseNull = "invalidUserId_Response_Null";
    Mockito.when(scimServiceStub.getUser(invalidUserIdResponseNull)).thenReturn(null);
    try {
        idpImpl.getRoleNamesOfUser(invalidUserIdResponseNull);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving user with Id " + invalidUserIdResponseNull + ". Error : Response is null.");
    }
    // Error case - When the request did not return a 200 OK response
    String invalidUserIdNot200OK = "invalidUserId_Not_200_OK";
    String errorResponseBody = "{\"Errors\":[{\"code\":\"404\",\"description\":\"User not found in the user " + "store.\"}]}";
    Response errorResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_404_NOT_FOUND).headers(new HashMap<>()).body(errorResponseBody.getBytes()).build();
    Mockito.when(scimServiceStub.getUser(invalidUserIdNot200OK)).thenReturn(errorResponse);
    try {
        idpImpl.getRoleNamesOfUser(invalidUserIdNot200OK);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving role names of user with Id " + invalidUserIdNot200OK + ". Error : User not found in the user store.");
    }
    // Error case - When response body is empty
    String invalidUserIdResponseEmpty = "invalidUserId_Response_Empty";
    Response emptyResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body("".getBytes()).build();
    Mockito.when(scimServiceStub.getUser(invalidUserIdResponseEmpty)).thenReturn(emptyResponse);
    try {
        idpImpl.getRoleNamesOfUser(invalidUserIdResponseEmpty);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving user with user Id " + invalidUserIdResponseEmpty + " from SCIM endpoint. Response body is null or empty.");
    }
}
Also used : Response(feign.Response) UserNameMapper(org.wso2.carbon.apimgt.core.api.UserNameMapper) ArrayList(java.util.ArrayList) SCIMServiceStub(org.wso2.carbon.apimgt.core.auth.SCIMServiceStub) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) Test(org.testng.annotations.Test)

Example 23 with Names

use of org.wso2.ballerinalang.compiler.util.Names in project wso2-synapse by wso2.

the class EventSourceSerializer method serializeEventSource.

public static OMElement serializeEventSource(OMElement elem, SynapseEventSource eventSource) {
    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace nullNS = fac.createOMNamespace(XMLConfigConstants.NULL_NAMESPACE, "");
    OMElement evenSourceElem = fac.createOMElement("eventSource", XMLConfigConstants.SYNAPSE_OMNAMESPACE);
    if (eventSource.getName() != null) {
        evenSourceElem.addAttribute(fac.createOMAttribute("name", nullNS, eventSource.getName()));
    }
    if (eventSource.getSubscriptionManager() != null) {
        OMElement subManagerElem = fac.createOMElement("subscriptionManager", XMLConfigConstants.SYNAPSE_OMNAMESPACE);
        subManagerElem.addAttribute(fac.createOMAttribute("class", nullNS, eventSource.getSubscriptionManager().getClass().getName()));
        Collection<String> names = (Collection<String>) eventSource.getSubscriptionManager().getPropertyNames();
        for (String name : names) {
            String value;
            if (eventSource.isContainsConfigurationProperty(name)) {
                value = eventSource.getConfigurationProperty(name);
            } else {
                value = eventSource.getSubscriptionManager().getPropertyValue(name);
            }
            OMElement propElem = fac.createOMElement("property", XMLConfigConstants.SYNAPSE_OMNAMESPACE);
            propElem.addAttribute(fac.createOMAttribute("name", nullNS, name));
            propElem.addAttribute(fac.createOMAttribute("value", nullNS, value));
            subManagerElem.addChild(propElem);
        }
        evenSourceElem.addChild(subManagerElem);
        // Adding static subscriptions
        List<Subscription> staticSubscriptionList = eventSource.getSubscriptionManager().getStaticSubscriptions();
        for (Iterator<Subscription> iterator = staticSubscriptionList.iterator(); iterator.hasNext(); ) {
            Subscription staticSubscription = iterator.next();
            OMElement staticSubElem = fac.createOMElement("subscription", XMLConfigConstants.SYNAPSE_OMNAMESPACE);
            staticSubElem.addAttribute(fac.createOMAttribute("id", nullNS, staticSubscription.getId()));
            OMElement filterElem = fac.createOMElement("filter", XMLConfigConstants.SYNAPSE_OMNAMESPACE);
            filterElem.addAttribute(fac.createOMAttribute("source", nullNS, (String) staticSubscription.getFilterValue()));
            filterElem.addAttribute(fac.createOMAttribute("dialect", nullNS, (String) staticSubscription.getFilterDialect()));
            staticSubElem.addChild(filterElem);
            OMElement endpointElem = fac.createOMElement("endpoint", XMLConfigConstants.SYNAPSE_OMNAMESPACE);
            OMElement addressElem = fac.createOMElement("address", XMLConfigConstants.SYNAPSE_OMNAMESPACE);
            addressElem.addAttribute(fac.createOMAttribute("uri", nullNS, staticSubscription.getEndpointUrl()));
            endpointElem.addChild(addressElem);
            staticSubElem.addChild(endpointElem);
            if (staticSubscription.getExpires() != null) {
                OMElement expiresElem = fac.createOMElement("expires", XMLConfigConstants.SYNAPSE_OMNAMESPACE);
                fac.createOMText(expiresElem, ConverterUtil.convertToString(staticSubscription.getExpires()));
                staticSubElem.addChild(expiresElem);
            }
            evenSourceElem.addChild(staticSubElem);
        }
    }
    if (elem != null) {
        elem.addChild(evenSourceElem);
    }
    return evenSourceElem;
}
Also used : OMFactory(org.apache.axiom.om.OMFactory) OMNamespace(org.apache.axiom.om.OMNamespace) Collection(java.util.Collection) OMElement(org.apache.axiom.om.OMElement) Subscription(org.wso2.eventing.Subscription)

Example 24 with Names

use of org.wso2.ballerinalang.compiler.util.Names in project charon by wso2.

the class ServerSideValidator method validateUpdatedSCIMObject.

/*
     * Perform validation on SCIM Object update on service provider side
     *
     * @param oldObject
     * @param newObject
     * @param resourceSchema
     * @return
     * @throws CharonException
     */
public static AbstractSCIMObject validateUpdatedSCIMObject(AbstractSCIMObject oldObject, AbstractSCIMObject newObject, SCIMResourceTypeSchema resourceSchema) throws CharonException, BadRequestException {
    AbstractSCIMObject validatedObject = null;
    if (newObject instanceof User) {
        // set display names for complex multivalued attributes
        setDisplayNameInComplexMultiValuedAttributes(newObject, resourceSchema);
    }
    // check for read only and immutable attributes
    validatedObject = checkIfReadOnlyAndImmutableAttributesModified(oldObject, newObject, resourceSchema);
    // copy meta attribute from old to new
    validatedObject.setAttribute(oldObject.getAttribute(SCIMConstants.CommonSchemaConstants.META));
    // copy id attribute to new group object
    validatedObject.setAttribute(oldObject.getAttribute(SCIMConstants.CommonSchemaConstants.ID));
    // edit last modified date
    Date date = new Date();
    validatedObject.setLastModified(date);
    // check for required attributes.
    validateSCIMObjectForRequiredAttributes(newObject, resourceSchema);
    // check for schema list
    validateSchemaList(validatedObject, resourceSchema);
    return validatedObject;
}
Also used : AbstractSCIMObject(org.wso2.charon3.core.objects.AbstractSCIMObject) User(org.wso2.charon3.core.objects.User) Date(java.util.Date)

Example 25 with Names

use of org.wso2.ballerinalang.compiler.util.Names in project carbon-business-process by wso2.

the class ProcessConfigurationImpl method initPartnerLinks.

/**
 * Initialize partner link details of the BPEL process. Details about partner link's service and
 * port is in the deploy.xml file. This can be used to initialize partner links information in
 * registry. After that we can co-relate this partner links with carbon endpoints. This will
 * help us to dynamically configure endpoint properties like security, RM.
 */
private void initPartnerLinks() {
    if (processInfo.getInvokeList() != null) {
        for (TInvoke invoke : processInfo.getInvokeList()) {
            String plinkName = invoke.getPartnerLink();
            TService service = invoke.getService();
            // configure this value
            if (service == null) {
                continue;
            }
            if (log.isDebugEnabled()) {
                log.debug("Processing <invoke> element for process " + processInfo.getName() + ": partnerlink" + plinkName + " -->" + service);
            }
            QName serviceName = service.getName();
            /* Validating configuration with package content before putting partner role endpoints to map */
            Definition wsdlDef = getDefinitionForService(serviceName);
            if (wsdlDef == null) {
                String errMsg = "Cannot find WSDL definition for invoke service " + serviceName + ". Required resources not found in the BPEL package " + du.getName() + ".";
                log.error(errMsg);
                throw new ContextException(errMsg);
            }
            Service serviceDef = wsdlDef.getService(serviceName);
            if (serviceDef.getPort(service.getPort()) == null) {
                String errMsg = "Cannot find  port for invoking service for the given name " + serviceName + ". Error in deploy.xml.";
                log.error(errMsg);
                throw new ContextException(errMsg);
            }
            partnerRoleInitialValues.put(plinkName, new Endpoint(service.getName(), service.getPort()));
            // TODO add proper variable names
            {
                OFailureHandling g = null;
                if (invoke.isSetFailureHandling()) {
                    FailureHandlingDocument.FailureHandling fh = invoke.getFailureHandling();
                    g = new OFailureHandling();
                    if (fh.isSetFaultOnFailure()) {
                        g.faultOnFailure = fh.getFaultOnFailure();
                    }
                    if (fh.isSetRetryDelay()) {
                        g.retryDelay = fh.getRetryDelay();
                    }
                    if (fh.isSetRetryFor()) {
                        g.retryFor = fh.getRetryFor();
                    }
                }
                PartnerRoleConfig c = new PartnerRoleConfig(g, invoke.getUsePeer2Peer());
                if (log.isDebugEnabled()) {
                    log.debug("PartnerRoleConfig for " + plinkName + " " + c.failureHandling + " usePeer2Peer: " + c.usePeer2Peer);
                }
                partnerRoleConfigurations.put(plinkName, c);
            }
        }
    }
    if (processInfo.getProvideList() != null) {
        for (TProvide proivde : processInfo.getProvideList()) {
            String plinkName = proivde.getPartnerLink();
            TService service = proivde.getService();
            if (proivde.getCorrelationFilter() != null) {
                if (B4P_NAMESPACE.equals(proivde.getCorrelationFilter().getNamespaceURI())) {
                    isB4PTaskIncluded = true;
                }
            }
            /* NOTE:Service cannot be null for provider partner link*/
            if (service == null) {
                String errorMsg = "Error in <provide> element for process " + processInfo.getName() + ";partnerlink" + plinkName + "did not identify an endpoint";
                log.error(errorMsg);
                throw new ContextException(errorMsg);
            }
            if (log.isDebugEnabled()) {
                log.debug("Processing <provide> element for process " + processInfo.getName() + ": partnerlink " + plinkName + " --> " + service.getName() + " : " + service.getPort());
            }
            QName serviceName = service.getName();
            /* Validating configuration with package content before putting myRole endpoints to map */
            Definition wsdlDef = getDefinitionForService(serviceName);
            if (wsdlDef == null) {
                String errMsg = "Cannot find WSDL definition for provide service " + serviceName + ". Required resources not found in the BPEL " + "package " + du.getName() + ".";
                log.error(errMsg);
                throw new ContextException(errMsg);
            }
            Service serviceDef = wsdlDef.getService(serviceName);
            if (serviceDef.getPort(service.getPort()) == null) {
                String errMsg = "Cannot find provide port in the given service " + serviceName + ". Error in deploy.xml.";
                log.error(errMsg);
                throw new ContextException(errMsg);
            }
            myRoleEndpoints.put(plinkName, new Endpoint(service.getName(), service.getPort()));
            if (proivde.isSetEnableSharing()) {
                sharedServices.add(service.getName());
            }
        }
    }
}
Also used : Endpoint(org.apache.ode.bpel.iapi.Endpoint) UnifiedEndpoint(org.wso2.carbon.unifiedendpoint.core.UnifiedEndpoint) OFailureHandling(org.apache.ode.bpel.o.OFailureHandling) QName(javax.xml.namespace.QName) Definition(javax.wsdl.Definition) Service(javax.wsdl.Service) TService(org.apache.ode.bpel.dd.TService) TProvide(org.apache.ode.bpel.dd.TProvide) TInvoke(org.apache.ode.bpel.dd.TInvoke) TService(org.apache.ode.bpel.dd.TService) ContextException(org.apache.ode.bpel.iapi.ContextException) OFailureHandling(org.apache.ode.bpel.o.OFailureHandling)

Aggregations

ArrayList (java.util.ArrayList)10 Query (javax.persistence.Query)8 TaskStatus (org.wso2.carbon.humantask.core.dao.TaskStatus)8 Test (org.testng.annotations.Test)6 BLangVariable (org.wso2.ballerinalang.compiler.tree.BLangVariable)5 Name (org.wso2.ballerinalang.compiler.util.Name)5 Map (java.util.Map)4 BLangXMLQName (org.wso2.ballerinalang.compiler.tree.expressions.BLangXMLQName)4 CompilerContext (org.wso2.ballerinalang.compiler.util.CompilerContext)4 HTTPTestRequest (org.ballerinalang.test.services.testutils.HTTPTestRequest)3 BLangPackage (org.wso2.ballerinalang.compiler.tree.BLangPackage)3 BLangRecordLiteral (org.wso2.ballerinalang.compiler.tree.expressions.BLangRecordLiteral)3 BLangAssignment (org.wso2.ballerinalang.compiler.tree.statements.BLangAssignment)3 Response (feign.Response)2 IOException (java.io.IOException)2 Path (java.nio.file.Path)2 Arrays (java.util.Arrays)2 Date (java.util.Date)2 HashMap (java.util.HashMap)2 Iterator (java.util.Iterator)2