Java Code Examples for org.apache.velocity.VelocityContext#get()

The following examples show how to use org.apache.velocity.VelocityContext#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CodeGenerator.java    From ueboot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 生成repository及repositoryImpl类
 *
 * @param clz                   实体类
 * @param repositoryPackageName repository包名路径
 * @param repositoryModuleName  repository模块名称
 */
public void createRepository(Class<?> clz, String repositoryPackageName, String repositoryModuleName) {
    log("repository类生成包名:" + repositoryPackageName);
    VelocityContext context = getBaseContext(clz);
    String entityClassName = (String) context.get("entityName");
    context.put("repositoryPackageName", repositoryPackageName);
    String baseJava = getTemplateString("BaseRepository.vm", context);
    String java = getTemplateString("Repository.vm", context);
    String java2 = getTemplateString("RepositoryImpl.vm", context);

    log("repository文件内容:" + java);
    String filePath = repositoryPackageName.replace(".", separator);
    String interfaceFilePath = projectPah + repositoryModuleName + separator + "src" + separator + "main" + separator + "java" + separator + filePath + separator + entityClassName + "Repository.java";
    String baseFilePath = projectPah + repositoryModuleName + separator + "src" + separator + "main" + separator + "java" + separator + filePath + separator + entityClassName + "BaseRepository.java";
    String implFilePath = projectPah + repositoryModuleName + separator + "src" + separator + "main" + separator + "java" + separator + filePath + separator + "impl" + separator + entityClassName + "RepositoryImpl.java";
    log("baseRepository文件保存路径:" + baseFilePath);
    log("repository文件保存路径:" + interfaceFilePath);
    log("repositoryImpl文件保存路径:" + implFilePath);
    saveFile(baseFilePath, baseJava);
    saveFile(interfaceFilePath, java);
    saveFile(implFilePath, java2);
}
 
Example 2
Source File: CodeGenerator.java    From ueboot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 生成service及serviceImpl类
 *
 * @param clz                   实体类
 * @param servicePackageName    service类包名路径
 * @param serviceModuleName     service类模块名称
 * @param repositoryPackageName repository类包名路径
 */
public void createService(Class<?> clz, String servicePackageName, String serviceModuleName, String repositoryPackageName) {
    log("service类生成包名:" + servicePackageName);
    VelocityContext context = getBaseContext(clz);
    String entityClassName = (String) context.get("entityName");
    context.put("servicePackageName", servicePackageName);
    String java = getTemplateString("Service.vm", context);
    log("service文件内容:" + java);
    context.put("repositoryPackageName", repositoryPackageName);

    String java2 = getTemplateString("ServiceImpl.vm", context);
    log("serviceImpl文件内容:" + java2);

    String filePath = servicePackageName.replace(".", separator);

    String interfaceFilePath = projectPah + serviceModuleName + separator + "src" + separator + "main" + separator + "java" + separator + filePath + separator + entityClassName + "Service.java";
    String implFilePath = projectPah + serviceModuleName + separator + "src" + separator + "main" + separator + "java" + separator + filePath + separator + "impl" + separator + entityClassName + "ServiceImpl.java";

    log("service文件保存路径:" + interfaceFilePath);
    log("serviceImpl文件保存路径:" + implFilePath);

    saveFile(interfaceFilePath, java);
    saveFile(implFilePath, java2);
}
 
Example 3
Source File: CodeGenerator.java    From ueboot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void createPages(Class<?> clz, String vuePageModuleName, String vueFilePath, String requestPath) {
    log("pagePath:" + vueFilePath);

    VelocityContext context = getBaseContext(clz);
    String entityClassName = (String) context.get("entityName");

    try {
        List<ObjectField> fields = getObjectValue(clz);
        context.put("fields", fields);
    } catch (Exception e) {
        e.printStackTrace();
    }
    context.put("requestPath", requestPath);

    String js = getTemplateString("VUE.vm", context);
    log("vue 页面文件内容:" + js);
    String jsFilePath = projectPah + vuePageModuleName + separator + vueFilePath + separator + entityClassName + ".vue";
    log("vueFilePath文件保存路径:" + jsFilePath);
    saveFile(jsFilePath, js);

}
 
Example 4
Source File: BrowseSelectedTypePage.java    From hollow with Apache License 2.0 6 votes vote down vote up
@Override
protected void renderPage(HttpServletRequest req, VelocityContext ctx, Writer writer) {
    String key = (String) ctx.get("key");
    Integer ordinal = (Integer) ctx.get("ordinal");
    ui.getVelocityEngine().getTemplate("browse-selected-type-top.vm").merge(ctx, writer);
    try {
        Writer htmlEscapingWriter = new HtmlEscapingWriter(writer);
        if (!"".equals(key) && ordinal != null && ordinal.equals(-1)) {
            htmlEscapingWriter.append("ERROR: Key " + key + " was not found!");
        } else if (ordinal != null && !ordinal.equals(-1)) {
            HollowStringifier stringifier = "json".equals(req.getParameter("display"))
                ? new HollowRecordJsonStringifier() : new HollowRecordStringifier();
            stringifier.stringify(htmlEscapingWriter, ui.getStateEngine(),
                getTypeState(req).getSchema().getName(), ordinal);
        }
    } catch (IOException e) {
        throw new RuntimeException("Error streaming response", e);
    }
    ui.getVelocityEngine().getTemplate("browse-selected-type-bottom.vm").merge(ctx, writer);
}
 
Example 5
Source File: FileGenerator.java    From Asqatasun with GNU Affero General Public License v3.0 6 votes vote down vote up
public void writeTestCaseGenerate(VelocityContext context, Template temp,
        String className, String testCaseNumber) throws IOException {
    StringWriter wr = new StringWriter();
    if (StringUtils.isNotBlank(className)) {
        vpc.setClassString(className);
        context.put("rule", vpc.getClassString());
    }
    temp.merge(context, wr);
    File testCaseFile = new File(vpc.getDestinationFolder()
            + "/src/test/resources/testcases/"
            + vpc.getReferential().replace(".", "").toLowerCase() + "/"
            + vpc.getClassString() + "/" + vpc.getReferential().replace(".", "")
            + ".Test." + vpc.getTestCode().replace('-', '.')
            + "-" + testCaseNumber + context.get("state") + "-01.html");
    FileUtils.writeStringToFile(testCaseFile, wr.toString());
}
 
Example 6
Source File: CodeGenerator.java    From ueboot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 生成controller类
 *
 * @param clz                   实体类
 * @param controllerPackageName controller类包名路径
 * @param servicePackageName    service类包名路径
 * @param controllerModuleName  controller模块名称
 * @param requestPath  请求上下文,加了这个则会多加一个路径,默认为类名,如:/role
 */
public void createController(Class<?> clz, String controllerPackageName, String servicePackageName, String controllerModuleName,String requestPath) {
    createVO(clz, controllerModuleName, controllerPackageName);

    log("controller类生成包名:" + controllerPackageName);

    VelocityContext context = getBaseContext(clz);
    String entityClassName = (String) context.get("entityName");

    context.put("controllerPackageName", controllerPackageName);
    context.put("servicePackageName", servicePackageName);
    if(requestPath==null || "".equals(requestPath)){
        requestPath = "/";
    }
    if(!requestPath.startsWith("/")){
        requestPath = "/"+requestPath;
    }
    if(!requestPath.endsWith("/")){
        requestPath +="/";
    }
    context.put("requestPath", requestPath);

    String java = getTemplateString("Controller.vm", context);
    log("controller文件内容:" + java);
    String filepath = controllerPackageName.replace(".", separator);

    String controllerfilepath = projectPah + controllerModuleName + separator + "src" + separator + "main" + separator + "java" + separator + filepath + separator + entityClassName + "Controller.java";
    log("controller文件保存路径:" + controllerfilepath);
    saveFile(controllerfilepath, java);
}
 
Example 7
Source File: CodeGenerator.java    From ueboot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void createVO(Class<?> clz, String controllerModuleName, String controllerPackageName) {

        String voPackageName = controllerPackageName + ".vo";
        String filepath = voPackageName.replace(".", "/");

        VelocityContext context = getBaseContext(clz);
        context.put("controllerPackageName", controllerPackageName);

        try {
            List<ObjectField> fields = getObjectValue(clz);
            context.put("fields", fields);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Map<String, String> transCodes = new HashMap<String, String>();
        transCodes.put("FindReq", "");
        transCodes.put("Resp", "");
        transCodes.put("Req", "");

        for (Map.Entry<String, String> entry : transCodes.entrySet()) {
            String key = entry.getKey();
            String java = getTemplateString(key + ".vm", context);
            log(key + "文件内容:" + java);
            String reqFilePath = projectPah + controllerModuleName + separator + "src" + separator + "main" + separator + "java" + separator + filepath + separator + context.get("entityName") + key + ".java";
            log(key + "文件保存路径:" + reqFilePath);
            saveFile(reqFilePath, java);

        }
    }
 
Example 8
Source File: HTTPPostSimpleSignEncoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Build the form control data string over which the signature is computed.
 * 
 * @param velocityContext the Velocity context which is already populated with the values for SAML message and relay
 *            state
 * @param messageContext  the SAML message context being processed
 * @param sigAlgURI the signature algorithm URI
 * 
 * @return the form control data string for signature computation
 */
protected String buildFormDataToSign(VelocityContext velocityContext, SAMLMessageContext messageContext, String sigAlgURI) {
    StringBuilder builder = new StringBuilder();

    boolean isRequest = false;
    if (velocityContext.get("SAMLRequest") != null) {
        isRequest = true;
    }

    String msgB64;
    if (isRequest) {
        msgB64 = (String) velocityContext.get("SAMLRequest");
    } else {
        msgB64 = (String) velocityContext.get("SAMLResponse");
    }

    String msg = null;
    try {
        msg = new String(Base64.decode(msgB64), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // All JVM's required to support UTF-8
    }

    if (isRequest) {
        builder.append("SAMLRequest=" + msg);
    } else {
        builder.append("SAMLResponse=" + msg);
    }

    if (messageContext.getRelayState() != null) {
        builder.append("&RelayState=" + messageContext.getRelayState());
    }

    builder.append("&SigAlg=" + sigAlgURI);

    return builder.toString();
}
 
Example 9
Source File: WebServicePostEncoder.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
/**
 * Build the form control data string over which the signature is computed.
 * 
 * @param velocityContext
 *            the Velocity context which is already populated with the
 *            values for SAML message and relay state
 * @param messageContext
 *            the SAML message context being processed
 * @param sigAlgURI
 *            the signature algorithm URI
 * 
 * @return the form control data string for signature computation
 */
@SuppressWarnings("rawtypes")
protected String buildFormDataToSign(VelocityContext velocityContext,
		SAMLMessageContext messageContext, String sigAlgURI) {
	StringBuilder builder = new StringBuilder();

	boolean isRequest = false;
	if (velocityContext.get("SAMLRequest") != null) {
		isRequest = true;
	}

	String msgB64;
	if (isRequest) {
		msgB64 = (String) velocityContext.get("SAMLRequest");
	} else {
		msgB64 = (String) velocityContext.get("SAMLResponse");
	}

	String msg = null;
	try {
		msg = new String(Base64.decode(msgB64), "UTF-8");
	} catch (UnsupportedEncodingException e) {
		// All JVM's required to support UTF-8
	}

	if (isRequest) {
		builder.append("SAMLRequest=" + msg);
	} else {
		builder.append("SAMLResponse=" + msg);
	}

	if (messageContext.getRelayState() != null) {
		builder.append("&RelayState=" + messageContext.getRelayState());
	}

	builder.append("&SigAlg=" + sigAlgURI);

	return builder.toString();
}
 
Example 10
Source File: SecurityConfigContextTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testSecurityConfigContext() throws Exception {

    API api = new API(new APIIdentifier("admin", "TestAPI", "1.0.0"));
    api.setStatus(APIConstants.CREATED);
    api.setContextTemplate("/");
    api.setTransports(Constants.TRANSPORT_HTTP);
    api.setEndpointUTUsername("admin");
    api.setEndpointUTPassword("admin123");
    api.setEndpointSecured(true);
    api.setEndpointAuthDigest(true);
    ConfigContext configcontext = new APIConfigContext(api);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.API_SECUREVAULT_ENABLE)).thenReturn("true");
    SecurityConfigContext securityConfigContext =
            new SecurityConfigContextWrapper(configcontext, api, apiManagerConfiguration);
    securityConfigContext.validate();
    VelocityContext velocityContext = securityConfigContext.getContext();
    Assert.assertNotNull(velocityContext.get("endpoint_security"));
    Map<String, EndpointSecurityModel> endpointSecurityModelMap =
            (Map<String, EndpointSecurityModel>) velocityContext.get("endpoint_security");
    for (Map.Entry<String, EndpointSecurityModel> endpointSecurityModelEntry : endpointSecurityModelMap
            .entrySet()) {
        Assert.assertTrue("Property isEndpointSecured cannot be false.",
                endpointSecurityModelEntry.getValue().isEnabled());
        Assert.assertTrue("Property isEndpointAuthDigest cannot be false.",
                endpointSecurityModelEntry.getValue().getType().contains("digest"));
        Assert.assertTrue("Property username does not match.",
                "admin".equals(endpointSecurityModelEntry.getValue().getUsername()));
        Assert.assertTrue("Property base64unpw does not match. ",
                new String(Base64.encodeBase64("admin:admin123".getBytes()))
                        .equalsIgnoreCase(endpointSecurityModelEntry.getValue().getBase64EncodedPassword()));
        Assert.assertTrue("Property securevault_alias does not match.",
                "admin--TestAPI1.0.0".equalsIgnoreCase(endpointSecurityModelEntry.getValue().getAlias()));
    }
    Assert.assertTrue("Property isSecureVaultEnabled cannot be false. ",
            velocityContext.get("isSecureVaultEnabled").equals(true));
}
 
Example 11
Source File: SecurityConfigContextTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testSecurityConfigContextPerEndpointProductionType() throws Exception {

    String json = "{\"endpoint_security\":{\n" +
            "  \"production\":{\n" +
            "    \"enabled\":true,\n" +
            "    \"type\":\"BASIC\",\n" +
            "    \"username\":\"admin\",\n" +
            "    \"password\":\"admin123#QA\"\n" +
            "  }\n" +
            "  }\n" +
            "}";
    API api = new API(new APIIdentifier("admin", "TestAPI", "1.0.0"));
    api.setStatus(APIConstants.CREATED);
    api.setContextTemplate("/");
    api.setTransports(Constants.TRANSPORT_HTTP);
    api.setEndpointConfig(json);
    ConfigContext configcontext = new APIConfigContext(api);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.API_SECUREVAULT_ENABLE)).thenReturn("true");
    SecurityConfigContext securityConfigContext =
            new SecurityConfigContextWrapper(configcontext, api, apiManagerConfiguration);
    securityConfigContext.validate();
    VelocityContext velocityContext = securityConfigContext.getContext();
    Assert.assertNotNull(velocityContext.get("endpoint_security"));
    Map<String, EndpointSecurityModel> endpointSecurityModelMap =
            (Map<String, EndpointSecurityModel>) velocityContext.get("endpoint_security");
    EndpointSecurityModel production = endpointSecurityModelMap.get("production");
    Assert.assertTrue("Property enabled cannot be false.", production.isEnabled());
    Assert.assertTrue("Property type cannot be other.", production.getType().equalsIgnoreCase("basic"));
    Assert.assertTrue("Property username does not match.", "admin".equals(production.getUsername()));
    Assert.assertTrue("Property base64value does not match. ",
            new String(Base64.encodeBase64("admin:admin123#QA".getBytes()))
                    .equalsIgnoreCase(production.getBase64EncodedPassword()));
    Assert.assertTrue("Property securevault_alias does not match.",
            "admin--TestAPI1.0.0--production".equalsIgnoreCase(production.getAlias()));
    Assert.assertTrue("Property isSecureVaultEnabled cannot be false. ",
            velocityContext.get("isSecureVaultEnabled").equals(true));
    EndpointSecurityModel sandbox = endpointSecurityModelMap.get("sandbox");
    Assert.assertFalse("Property enabled cannot be true.", sandbox.isEnabled());
}
 
Example 12
Source File: SecurityConfigContextTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testSecurityConfigContextPerEndpointSandbox() throws Exception {

    String json = "{\"endpoint_security\":{\n" +
            "  \"sandbox\":{\n" +
            "    \"enabled\":true,\n" +
            "    \"type\":\"DIGEST\",\n" +
            "    \"username\":\"admin\",\n" +
            "    \"password\":\"admin123#QA\"\n" +
            "  }\n" +
            "  }\n" +
            "}";
    API api = new API(new APIIdentifier("admin", "TestAPI", "1.0.0"));
    api.setStatus(APIConstants.CREATED);
    api.setContextTemplate("/");
    api.setTransports(Constants.TRANSPORT_HTTP);
    api.setEndpointConfig(json);
    ConfigContext configcontext = new APIConfigContext(api);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.API_SECUREVAULT_ENABLE)).thenReturn("true");
    SecurityConfigContext securityConfigContext =
            new SecurityConfigContextWrapper(configcontext, api, apiManagerConfiguration);
    securityConfigContext.validate();
    VelocityContext velocityContext = securityConfigContext.getContext();
    Assert.assertNotNull(velocityContext.get("endpoint_security"));
    Map<String, EndpointSecurityModel> endpointSecurityModelMap =
            (Map<String, EndpointSecurityModel>) velocityContext.get("endpoint_security");
    EndpointSecurityModel sandbox = endpointSecurityModelMap.get("sandbox");
    Assert.assertTrue("Property enabled cannot be false.", sandbox.isEnabled());
    Assert.assertTrue("Property type cannot be other.", sandbox.getType().equalsIgnoreCase("digest"));
    Assert.assertTrue("Property username does not match.", "admin".equals(sandbox.getUsername()));
    Assert.assertTrue("Property base64value does not match. ",
            new String(Base64.encodeBase64("admin:admin123#QA".getBytes()))
                    .equalsIgnoreCase(sandbox.getBase64EncodedPassword()));
    Assert.assertTrue("Property securevault_alias does not match.",
            "admin--TestAPI1.0.0--sandbox".equalsIgnoreCase(sandbox.getAlias()));
    Assert.assertTrue("Property isSecureVaultEnabled cannot be false. ",
            velocityContext.get("isSecureVaultEnabled").equals(true));
    EndpointSecurityModel production = endpointSecurityModelMap.get("production");
    Assert.assertFalse("Property enabled cannot be true.", production.isEnabled());
}
 
Example 13
Source File: SecurityConfigContextTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testSecurityConfigContextPerEndpointBothType() throws Exception {

    String json = "{\"endpoint_security\":{\n" +
            "  \"production\":{\n" +
            "    \"enabled\":true,\n" +
            "    \"type\":\"BASIC\",\n" +
            "    \"username\":\"admin\",\n" +
            "    \"password\":\"admin123#QA\"\n" +
            "  },\n" +
            "  \"sandbox\":{\n" +
            "    \"enabled\":true,\n" +
            "    \"type\":\"DIGEST\",\n" +
            "    \"username\":\"admin\",\n" +
            "    \"password\":\"admin123\"\n" +
            "  }\n" +
            "  }\n" +
            "}";
    API api = new API(new APIIdentifier("admin", "TestAPI", "1.0.0"));
    api.setStatus(APIConstants.CREATED);
    api.setContextTemplate("/");
    api.setTransports(Constants.TRANSPORT_HTTP);
    api.setEndpointConfig(json);
    ConfigContext configcontext = new APIConfigContext(api);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.API_SECUREVAULT_ENABLE)).thenReturn("true");
    SecurityConfigContext securityConfigContext =
            new SecurityConfigContextWrapper(configcontext, api, apiManagerConfiguration);
    securityConfigContext.validate();
    VelocityContext velocityContext = securityConfigContext.getContext();
    Assert.assertNotNull(velocityContext.get("endpoint_security"));
    Map<String, EndpointSecurityModel> endpointSecurityModelMap =
            (Map<String, EndpointSecurityModel>) velocityContext.get("endpoint_security");
    EndpointSecurityModel production = endpointSecurityModelMap.get("production");
    Assert.assertTrue("Property enabled cannot be false.", production.isEnabled());
    Assert.assertTrue("Property type cannot be other.", production.getType().equalsIgnoreCase("basic"));
    Assert.assertTrue("Property username does not match.", "admin".equals(production.getUsername()));
    Assert.assertTrue("Property base64value does not match. ",
            new String(Base64.encodeBase64("admin:admin123#QA".getBytes()))
                    .equalsIgnoreCase(production.getBase64EncodedPassword()));
    Assert.assertTrue("Property securevault_alias does not match.",
            "admin--TestAPI1.0.0--production".equalsIgnoreCase(production.getAlias()));
    EndpointSecurityModel sandbox = endpointSecurityModelMap.get("sandbox");
    Assert.assertTrue("Property enabled cannot be false.", sandbox.isEnabled());
    Assert.assertTrue("Property type cannot be other.", sandbox.getType().equalsIgnoreCase("digest"));
    Assert.assertTrue("Property username does not match.", "admin".equals(sandbox.getUsername()));
    Assert.assertTrue("Property base64value does not match. ",
            new String(Base64.encodeBase64("admin:admin123".getBytes()))
                    .equalsIgnoreCase(sandbox.getBase64EncodedPassword()));
    Assert.assertTrue("Property securevault_alias does not match.",
            "admin--TestAPI1.0.0--sandbox".equalsIgnoreCase(sandbox.getAlias()));
    Assert.assertTrue("Property isSecureVaultEnabled cannot be false. ",
            velocityContext.get("isSecureVaultEnabled").equals(true));
}
 
Example 14
Source File: SecurityConfigContextTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testSecurityConfigContextIgnoringEndpointConfig() throws Exception {

    String json = "{\"endpoint_security\":{\n" +
            "  \"sandbox\":{\n" +
            "    \"enabled\":true,\n" +
            "    \"type\":\"DIGEST\",\n" +
            "    \"username\":\"admin\",\n" +
            "    \"password\":\"admin123#QA\"\n" +
            "  }\n" +
            "  }\n" +
            "}";

    API api = new API(new APIIdentifier("admin", "TestAPI", "1.0.0"));
    api.setStatus(APIConstants.CREATED);
    api.setContextTemplate("/");
    api.setTransports(Constants.TRANSPORT_HTTP);
    api.setEndpointConfig(json);
    api.setEndpointUTUsername("admin");
    api.setEndpointUTPassword("admin123");
    api.setEndpointSecured(true);
    api.setEndpointAuthDigest(true);
    ConfigContext configcontext = new APIConfigContext(api);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.API_SECUREVAULT_ENABLE)).thenReturn("true");
    SecurityConfigContext securityConfigContext =
            new SecurityConfigContextWrapper(configcontext, api, apiManagerConfiguration);
    securityConfigContext.validate();
    VelocityContext velocityContext = securityConfigContext.getContext();
    Assert.assertNotNull(velocityContext.get("endpoint_security"));
    Map<String, EndpointSecurityModel> endpointSecurityModelMap =
            (Map<String, EndpointSecurityModel>) velocityContext.get("endpoint_security");
    for (Map.Entry<String, EndpointSecurityModel> endpointSecurityModelEntry : endpointSecurityModelMap
            .entrySet()) {
        Assert.assertTrue("Property isEndpointSecured cannot be false.",
                endpointSecurityModelEntry.getValue().isEnabled());
        Assert.assertTrue("Property isEndpointAuthDigest cannot be false.",
                endpointSecurityModelEntry.getValue().getType().contains("digest"));
        Assert.assertTrue("Property username does not match.",
                "admin".equals(endpointSecurityModelEntry.getValue().getUsername()));
        Assert.assertTrue("Property base64unpw does not match. ",
                new String(Base64.encodeBase64("admin:admin123".getBytes()))
                        .equalsIgnoreCase(endpointSecurityModelEntry.getValue().getBase64EncodedPassword()));
        Assert.assertTrue("Property securevault_alias does not match.",
                "admin--TestAPI1.0.0".equalsIgnoreCase(endpointSecurityModelEntry.getValue().getAlias()));
    }
    Assert.assertTrue("Property isSecureVaultEnabled cannot be false. ",
            velocityContext.get("isSecureVaultEnabled").equals(true));
}
 
Example 15
Source File: SecurityConfigContextTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testSecurityConfigContextForAPIProduct() throws Exception {

    APIProduct apiProduct = new APIProduct(new APIProductIdentifier("admin", "TestProduct", "1.0.0"));
    apiProduct.setUuid(UUID.randomUUID().toString());
    List<APIProductResource> apiProductResourceList = new ArrayList<>();
    APIProductResource apiProductResource = new APIProductResource();
    apiProductResource.setApiIdentifier(new APIIdentifier("admin_api1_v1"));
    apiProductResource.setApiId(UUID.randomUUID().toString());
    Map<String, EndpointSecurity> endpointSecurityMap = new HashMap<>();
    EndpointSecurity endpointSecurity = new EndpointSecurity();
    endpointSecurity.setType("BASIC");
    endpointSecurity.setUsername("admin");
    endpointSecurity.setPassword("admin123");
    endpointSecurity.setEnabled(true);
    endpointSecurityMap.put("production", endpointSecurity);
    apiProductResource.setApiId(UUID.randomUUID().toString());
    apiProductResource.setEndpointSecurityMap(endpointSecurityMap);
    apiProductResourceList.add(apiProductResource);
    apiProduct.setProductResources(apiProductResourceList);
    ConfigContext configcontext = new APIConfigContext(apiProduct);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.API_SECUREVAULT_ENABLE)).thenReturn("true");
    SecurityConfigContext securityConfigContext =
            new SecurityConfigContextWrapper(configcontext, apiProduct, apiManagerConfiguration);
    securityConfigContext.validate();
    VelocityContext velocityContext = securityConfigContext.getContext();
    Assert.assertNotNull(velocityContext.get("endpoint_security"));
    Map<String, Map<String, EndpointSecurityModel>> endpointSecurityModelMap =
            (Map<String, Map<String, EndpointSecurityModel>>) velocityContext.get("endpoint_security");
    Map<String, EndpointSecurityModel> endpointSecurityModelMap1 =
            endpointSecurityModelMap.get(apiProductResource.getApiId());
    EndpointSecurityModel production = endpointSecurityModelMap1.get("production");
    Assert.assertTrue("Property enabled cannot be false.", production.isEnabled());
    Assert.assertTrue("Property type cannot be other.", production.getType().equalsIgnoreCase("basic"));
    Assert.assertTrue("Property username does not match.", "admin".equals(production.getUsername()));
    Assert.assertTrue("Property base64value does not match. ",
            new String(Base64.encodeBase64("admin:admin123".getBytes()))
                    .equalsIgnoreCase(production.getBase64EncodedPassword()));
    Assert.assertTrue("Property securevault_alias does not match.",
            "admin--api1v1--production".equalsIgnoreCase(production.getAlias()));
    Assert.assertTrue("Property isSecureVaultEnabled cannot be false. ",
            velocityContext.get("isSecureVaultEnabled").equals(true));
}