Search in sources :

Example 21 with ResponseCode

use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.

the class CertificateManagerImplTest method testRemoveFromPublisherCertificateManagementException.

@Test
public void testRemoveFromPublisherCertificateManagementException() {
    PowerMockito.stub(PowerMockito.method(CertificateMgtUtils.class, "removeCertificateFromTrustStore", String.class)).toReturn(ResponseCode.INTERNAL_SERVER_ERROR);
    try {
        Mockito.when(certificateMgtDAO.deleteCertificate("testRemoveFromPublisherCertificateManagementException", "testRemoveFromPublisherCertificateManagementException", TENANT_ID)).thenReturn(true);
        Mockito.when(certificateMgtDAO.addCertificate(BASE64_ENCODED_CERT, "testRemoveFromPublisherCertificateManagementException", "testRemoveFromPublisherCertificateManagementException", TENANT_ID)).thenThrow(CertificateManagementException.class);
        CertificateMetadataDTO certificateMetadataDTO = new CertificateMetadataDTO();
        certificateMetadataDTO.setEndpoint("testRemoveFromPublisherCertificateManagementException");
        certificateMetadataDTO.setCertificate(BASE64_ENCODED_CERT);
        certificateMetadataDTO.setAlias("testRemoveFromPublisherCertificateManagementException");
        List<CertificateMetadataDTO> certificateMetadataDTOList = new ArrayList<>();
        certificateMetadataDTOList.add(certificateMetadataDTO);
        Mockito.when(certificateMgtDAO.getCertificates("testRemoveFromPublisherCertificateManagementException", null, TENANT_ID)).thenReturn(certificateMetadataDTOList);
    } catch (CertificateManagementException | CertificateAliasExistsException e) {
        e.printStackTrace();
    }
    ResponseCode responseCode = certificateManager.deleteCertificateFromParentNode("testRemoveFromPublisherCertificateManagementException", "testRemoveFromPublisherCertificateManagementException", TENANT_ID);
    Assert.assertEquals(ResponseCode.INTERNAL_SERVER_ERROR, responseCode);
}
Also used : CertificateMetadataDTO(org.wso2.carbon.apimgt.api.dto.CertificateMetadataDTO) CertificateAliasExistsException(org.wso2.carbon.apimgt.impl.certificatemgt.exceptions.CertificateAliasExistsException) ArrayList(java.util.ArrayList) CertificateManagementException(org.wso2.carbon.apimgt.impl.certificatemgt.exceptions.CertificateManagementException) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 22 with ResponseCode

use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.

the class OAS2Parser method generateExample.

/**
 * This method  generates Sample/Mock payloads for Swagger (2.0) definitions
 *
 * @param swaggerDef Swagger Definition
 * @return Swagger Json
 */
@Override
public Map<String, Object> generateExample(String swaggerDef) throws APIManagementException {
    // create APIResourceMediationPolicy List = policyList
    SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(swaggerDef);
    Swagger swagger = parseAttemptForV2.getSwagger();
    // return map
    Map<String, Object> returnMap = new HashMap<>();
    // List for APIResMedPolicyList
    List<APIResourceMediationPolicy> apiResourceMediationPolicyList = new ArrayList<>();
    for (Map.Entry<String, Path> entry : swagger.getPaths().entrySet()) {
        int responseCode = 0;
        int minResponseCode = 0;
        String path = entry.getKey();
        Map<String, Model> definitions = swagger.getDefinitions();
        // operation map to get verb
        Map<HttpMethod, Operation> operationMap = entry.getValue().getOperationMap();
        List<Operation> operations = swagger.getPaths().get(path).getOperations();
        for (int i = 0, operationsSize = operations.size(); i < operationsSize; i++) {
            Operation op = operations.get(i);
            // initializing apiResourceMediationPolicyObject
            APIResourceMediationPolicy apiResourceMediationPolicyObject = new APIResourceMediationPolicy();
            // setting path for apiResourceMediationPolicyObject
            apiResourceMediationPolicyObject.setPath(path);
            ArrayList<Integer> responseCodes = new ArrayList<Integer>();
            Object[] operationsArray = operationMap.entrySet().toArray();
            if (operationsArray.length > i) {
                Map.Entry<HttpMethod, Operation> operationEntry = (Map.Entry<HttpMethod, Operation>) operationsArray[i];
                apiResourceMediationPolicyObject.setVerb(String.valueOf(operationEntry.getKey()));
            } else {
                throw new APIManagementException("Cannot find the HTTP method for the API Resource Mediation Policy");
            }
            StringBuilder genCode = new StringBuilder();
            boolean hasJsonPayload = false;
            boolean hasXmlPayload = false;
            // for setting only one initializing if condition per response code
            boolean respCodeInitialized = false;
            for (String responseEntry : op.getResponses().keySet()) {
                if (!responseEntry.equals("default")) {
                    responseCode = Integer.parseInt(responseEntry);
                    responseCodes.add(responseCode);
                    minResponseCode = Collections.min(responseCodes);
                }
                if (op.getResponses().get(responseEntry).getExamples() != null) {
                    Object applicationJson = op.getResponses().get(responseEntry).getExamples().get(APPLICATION_JSON_MEDIA_TYPE);
                    Object applicationXml = op.getResponses().get(responseEntry).getExamples().get(APPLICATION_XML_MEDIA_TYPE);
                    if (applicationJson != null) {
                        String jsonExample = Json.pretty(applicationJson);
                        genCode.append(getGeneratedResponsePayloads(responseEntry, jsonExample, "json", false));
                        respCodeInitialized = true;
                        hasJsonPayload = true;
                    }
                    if (applicationXml != null) {
                        String xmlExample = applicationXml.toString();
                        genCode.append(getGeneratedResponsePayloads(responseEntry, xmlExample, "xml", respCodeInitialized));
                        hasXmlPayload = true;
                    }
                } else if (op.getResponses().get(responseEntry).getResponseSchema() != null) {
                    Model model = op.getResponses().get(responseEntry).getResponseSchema();
                    String schemaExample = getSchemaExample(model, definitions, new HashSet<String>());
                    genCode.append(getGeneratedResponsePayloads(responseEntry, schemaExample, "json", respCodeInitialized));
                    hasJsonPayload = true;
                } else if (op.getResponses().get(responseEntry).getExamples() == null && op.getResponses().get(responseEntry).getResponseSchema() == null) {
                    setDefaultGeneratedResponse(genCode, responseEntry);
                    hasJsonPayload = true;
                    hasXmlPayload = true;
                }
            }
            // inserts minimum response code and mock payload variables to static script
            String finalGenCode = getMandatoryScriptSection(minResponseCode, genCode);
            // gets response section string depending on availability of json/xml payloads
            String responseConditions = getResponseConditionsSection(hasJsonPayload, hasXmlPayload);
            String finalScript = finalGenCode + responseConditions;
            apiResourceMediationPolicyObject.setContent(finalScript);
            apiResourceMediationPolicyList.add(apiResourceMediationPolicyObject);
            // sets script to each resource in the swagger
            op.setVendorExtension(APIConstants.SWAGGER_X_MEDIATION_SCRIPT, finalScript);
        }
        returnMap.put(APIConstants.SWAGGER, Json.pretty(swagger));
        returnMap.put(APIConstants.MOCK_GEN_POLICY_LIST, apiResourceMediationPolicyList);
    }
    return returnMap;
}
Also used : APIResourceMediationPolicy(org.wso2.carbon.apimgt.api.model.APIResourceMediationPolicy) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) Operation(io.swagger.models.Operation) SwaggerParser(io.swagger.parser.SwaggerParser) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Swagger(io.swagger.models.Swagger) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) RefPath(io.swagger.models.RefPath) Path(io.swagger.models.Path) SwaggerDeserializationResult(io.swagger.parser.util.SwaggerDeserializationResult) Model(io.swagger.models.Model) RefModel(io.swagger.models.RefModel) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpMethod(io.swagger.models.HttpMethod)

Example 23 with ResponseCode

use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.

the class CertificateMgtUtilTest method testAddCertificateWithFileNotFoundException.

@Test
public void testAddCertificateWithFileNotFoundException() throws NoSuchFieldException, IllegalAccessException {
    Field field = CertificateMgtUtils.class.getDeclaredField(TRUST_STORE_FIELD);
    field.setAccessible(true);
    field.set(certificateMgtUtils, INVALID_TRUST_STORE_FILE);
    ResponseCode responseCode = certificateMgtUtils.addCertificateToTrustStore(ALIAS, BASE64_ENCODED_ERROR_CERT);
    field.set(certificateMgtUtils, CERT_PATH.getPath());
    Assert.assertEquals(responseCode, ResponseCode.INTERNAL_SERVER_ERROR);
}
Also used : Field(java.lang.reflect.Field) ResponseCode(org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode) Test(org.junit.Test)

Example 24 with ResponseCode

use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.

the class CertificateMgtUtilTest method testValidateCertificate.

/**
 * This method tests the validateCertificate method's behaviour, during different conditions
 */
@Test
public void testValidateCertificate() {
    certificateMgtUtils.addCertificateToTrustStore(BASE64_ENCODED_CERT_STRING, ALIAS + "_" + MultitenantConstants.SUPER_TENANT_ID);
    ResponseCode responseCode = certificateMgtUtils.validateCertificate(ALIAS, MultitenantConstants.SUPER_TENANT_ID, BASE64_ENCODED_CERT_STRING);
    Assert.assertEquals("Validation succeeded, even though certificate with same alias exist already", ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE, responseCode);
    certificateMgtUtils.removeCertificateFromTrustStore(ALIAS + "_" + MultitenantConstants.SUPER_TENANT_ID);
    responseCode = certificateMgtUtils.validateCertificate(ALIAS, MultitenantConstants.SUPER_TENANT_ID, EXPIRED_CERTIFICATE);
    Assert.assertEquals("Validation succeeded for an expired certificate", ResponseCode.CERTIFICATE_EXPIRED, responseCode);
    responseCode = certificateMgtUtils.validateCertificate(ALIAS, MultitenantConstants.SUPER_TENANT_ID, BASE64_ENCODED_CERT_STRING);
    Assert.assertEquals("Validation failed for a valid certificate", ResponseCode.SUCCESS, responseCode);
}
Also used : ResponseCode(org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode) Test(org.junit.Test)

Example 25 with ResponseCode

use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.

the class CertificateMgtUtilTest method testAddCertificateWithCertificateException.

@Test
public void testAddCertificateWithCertificateException() {
    ResponseCode responseCode = certificateMgtUtils.addCertificateToTrustStore(ALIAS, BASE64_ENCODED_ERROR_CERT);
    Assert.assertEquals(responseCode, ResponseCode.INTERNAL_SERVER_ERROR);
}
Also used : ResponseCode(org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode) Test(org.junit.Test)

Aggregations

ResponseCode (org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode)18 Test (org.junit.Test)17 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)9 IOException (java.io.IOException)8 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)6 ArrayList (java.util.ArrayList)5 CertificateMetadataDTO (org.wso2.carbon.apimgt.api.dto.CertificateMetadataDTO)5 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 UserStoreException (org.wso2.carbon.user.api.UserStoreException)4 URI (java.net.URI)3 URISyntaxException (java.net.URISyntaxException)3 ContentDisposition (org.apache.cxf.jaxrs.ext.multipart.ContentDisposition)3 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)3 API (org.wso2.carbon.apimgt.api.model.API)3 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)3 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)3 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)3 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)3 CertificateAliasExistsException (org.wso2.carbon.apimgt.impl.certificatemgt.exceptions.CertificateAliasExistsException)3 CertificateManagementException (org.wso2.carbon.apimgt.impl.certificatemgt.exceptions.CertificateManagementException)3