Skip to content

Commit

Permalink
Spring Security Test Added
Browse files Browse the repository at this point in the history
Conflicts:
	src/main/java/org/jboss/forge/spec/spring/mvc/impl/SpringPlugin.java
	src/test/java/org/jboss/forge/scaffold/spring/SpringScaffoldTest.java
	src/test/java/org/jboss/forge/spec/spring/mvc/SpringPluginTest.java
  • Loading branch information
Tejas committed Feb 5, 2013
1 parent d4ca274 commit fee5ea0
Show file tree
Hide file tree
Showing 6 changed files with 255 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ public List<Resource<?>> setup(String targetDir, Resource<?> template, boolean o
persistence.saveConfig(descriptor);

List<Resource<?>> result = generateIndex(targetDir, template, overwrite);

result.add(ScaffoldUtil.createOrOverwrite(this.prompt, resources.getResource("META-INF/spring/applicationContext.xml"),
this.applicationContextTemplate.render(context), overwrite));

Expand Down Expand Up @@ -300,8 +300,8 @@ public List<Resource<?>> setup(String targetDir, Resource<?> template, boolean o
spring.addServlet(targetDir, targetDir.replace('/', '-').toLowerCase() + "-mvc-context.xml");
}
}

result.add(setupTilesLayout(targetDir));


return result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ public interface SpringFacet extends Facet
*/

FileResource<?> getMVCContextFile(String targetDir);

/**
* Get the servlet XML context file for the specified targetDir of the application.
*/

FileResource<?> getSecurityContextFile(String targetDir);

/**
* Get this application's currently configured servlet mappings from the web.xml
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,35 @@ public FileResource<?> getMVCContextFile(String targetDir)
return web.getWebResource(filename);
}
}

@Override
public FileResource<?> getSecurityContextFile(String targetDir)
{
WebResourceFacet web = project.getFacet(WebResourceFacet.class);

if (targetDir.equals("/") || targetDir.isEmpty())
{
MetadataFacet meta = project.getFacet(MetadataFacet.class);

return web.getWebResource("WEB-INF/" + meta.getProjectName().replace(' ', '-').toLowerCase() + "-security-context.xml");
}
else
{
while (targetDir.startsWith("/"))
{
targetDir = targetDir.substring(1);
}

while (targetDir.endsWith("/"))
{
targetDir = targetDir.substring(0, targetDir.length()-1);
}

String filename = "WEB-INF/" + targetDir.replace('/', '-').toLowerCase() + "-security-context.xml";

return web.getWebResource(filename);
}
}

@Override
public List<String> getSpringServletMappings()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
*/
package org.jboss.forge.spec.spring.mvc.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.enterprise.event.Event;
Expand Down Expand Up @@ -139,16 +141,6 @@ public void setup(PipeOut out, @Option(required=false, name="location", defaultV
{
ShellMessages.error(out, "Could not change application context location, no file found at src/main/resources/" + location);
}

if(this.prompt.promptBoolean("Would you like to add spring security?", false)){
MetadataFacet meta = project.getFacet(MetadataFacet.class);

String securityContext = "/WEB-INF/"
+ meta.getProjectName().replace(' ', '-').toLowerCase()
+ "-security-context.xml";
String targetDir = this.prompt.prompt("Target Dir? (Default is: " + securityContext + ")", "");
updateSecurity(targetDir);
}
}
}

Expand Down Expand Up @@ -316,7 +308,7 @@ public void updateMVC( @Option(required=false, name="mvcPackage", description="M

@Command("security")
public void updateSecurity(@Option(required=false, name="targetDir", description="Target Directory") String targetDir)
{
{
SpringFacet spring = project.getFacet(SpringFacet.class);
MetadataFacet meta = project.getFacet(MetadataFacet.class);

Expand Down Expand Up @@ -375,12 +367,52 @@ private void generateSecurity(String securityContext) {
.attribute("access", "ROLE_ADMIN");
http.createChild("remember-me");
}
if(!hasChildNamed(beans, "user-service")){
Node userService = new Node("user-service", beans);
userService.attribute("id", "userService");
userService.createChild("user").attribute("name", "admin").attribute("password", "admin").attribute("authorities", "ROLE_ADMIN");
List<String> possibleAuthenciationTechniques = new ArrayList<String>();
possibleAuthenciationTechniques.add("Embedded");
if (project.hasFacet(PersistenceFacet.class)){
possibleAuthenciationTechniques.add("JDBC");
}
possibleAuthenciationTechniques.add("LDAP");
int authenciationMethod = this.prompt.promptChoice("Type of User Authenciation", possibleAuthenciationTechniques);
switch (authenciationMethod) {
case 0:
if(!hasChildNamed(beans, "user-service")){
Node userService = new Node("user-service", beans);
userService.attribute("id", "userService");
String username = this.prompt.prompt("Admin User Name?", "admin");
String password = this.prompt.promptSecret("Admin Password?", "adminPass");
userService.createChild("user").attribute("name", username).attribute("password", password).attribute("authorities", "ROLE_ADMIN");
}
break;
case 1:
if(!hasChildNamed(beans, "jdbc-user-service")){
Node userService = new Node("jdbc-user-service", beans);
userService.attribute("id", "userService");
String dataSourceBean = this.prompt.prompt("JDBC Data Source Reference Bean?", "dataSource");
userService.attribute("data-source-ref", dataSourceBean);
}
break;
case 2:
if(!hasChildNamed(beans, "ldap-user-service")){
Node userService = new Node("ldap-user-service", beans);
userService.attribute("id", "userService");
userService.attribute("user-search-filter", "(uid={0})");
userService.attribute("group-search-filter", "member={0}");
}
if(!hasChildNamed(beans, "ldap-server")){
Node ldapServer = new Node("ldap-server", beans);
String urlOrLDIF = this.prompt.prompt("Enter url to remote LDAP server or ldif file on classpath");
if (urlOrLDIF.endsWith("ldif")){
ldapServer.attribute("ldif", urlOrLDIF);
}
else{
ldapServer.attribute("url", urlOrLDIF);
}
}
break;
default:
break;
}

if(!hasChildNamed(beans, "authentication-manager")){
Node authentiation = new Node("authentication-manager", beans);
authentiation.createChild("authentication-provider").attribute("user-service-ref", "userService");
Expand Down Expand Up @@ -544,6 +576,7 @@ protected void updateWebXML(String targetDir){
if(targetDir.startsWith("/")){
targetDir = targetDir.substring(1);
}

if(!webXML.getContextParam("contextConfigLocation").contains(targetDir)){
webXML.contextParam("contextConfigLocation", webXML.getContextParam("contextConfigLocation") + ", " + targetDir);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,6 @@ public void testGenerateFromEntity() throws Exception
.append(CRLF);
metawidget.append("\t\t</tr>")
.append(CRLF);

metawidget.append("\t\t<tr>")
.append(CRLF);
metawidget.append("\t\t\t<th class=\"label\">")
Expand Down Expand Up @@ -718,7 +717,6 @@ public void testGenerateFromEntityCamelCase() throws Exception
.append(CRLF);
metawidget.append("\t\t</tr>")
.append(CRLF);

metawidget.append("\t\t<tr>")
.append(CRLF);
metawidget.append("\t\t\t<th class=\"label\">")
Expand Down Expand Up @@ -822,4 +820,4 @@ public void testGenerateFromEntityCamelCase() throws Exception

Assert.assertEquals(metawidget.toString(), contents.toString());
}
}
}
168 changes: 168 additions & 0 deletions src/test/java/org/jboss/forge/spec/spring/mvc/SpringPluginTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -194,4 +194,172 @@ public void testGenerateApplicationContext() throws Exception
Assert.assertEquals("java:jboss/forge-default/persistence", entityManagerFactory.getAttribute("jndi-name"));
}


private Project prepSecurityTest() throws Exception {
getShell().setOutputStream(System.out);
Project project = initializeJavaProject();
queueInputLines("HIBERNATE", "JBOSS_AS7", "", "", "");
getShell().execute("persistence setup");
queueInputLines("", "");
getShell().execute("spring setup");

getShell().execute("spring mvc --mvcContext /WEB-INF/servlet-context.xml --targetDir /admin --mvcPackage test.mvc.package");

MetadataFacet meta = project.getFacet(MetadataFacet.class);
ServletFacet servlet = project.getFacet(ServletFacet.class);
SpringFacet spring = project.getFacet(SpringFacet.class);
WebResourceFacet web = project.getFacet(WebResourceFacet.class);

WebAppDescriptor webXML = servlet.getConfig();

Assert.assertNotNull(webXML);
Assert.assertTrue(webXML.getContextParam("contextConfigLocation").contains("classpath:/" + spring.getContextFileLocation()));
Assert.assertTrue(webXML.getListeners().contains("org.springframework.web.context.ContextLoaderListener"));

Node webapp = XMLParser.parse(servlet.getConfigFile().getResourceInputStream());

Assert.assertTrue(webapp.getSingle("display-name").getText().equals(meta.getProjectName()));
Assert.assertNotNull(webapp.getSingle("persistence-context-ref"));

Node dispatcherServlet = webapp.getSingle("servlet");
Assert.assertTrue(dispatcherServlet.getSingle("servlet-name").getText().equals("admin"));
Assert.assertTrue(dispatcherServlet.getSingle("servlet-class").getText().equals("org.springframework.web.servlet.DispatcherServlet"));

Node param = dispatcherServlet.getSingle("init-param").getSingle("param-value");
Assert.assertTrue(param.getText().equals("/WEB-INF/servlet-context.xml"));

Node servletMapping = webapp.getSingle("servlet-mapping");
Assert.assertTrue(servletMapping.getSingle("url-pattern").getText().equals("/admin/*"));
Assert.assertTrue(servletMapping.getSingle("servlet-name").getText().equals("admin"));

Node beans = XMLParser.parse(web.getWebResource("WEB-INF/servlet-context.xml").getResourceInputStream());

Assert.assertNotNull(beans.getAttribute("xmlns"));
Assert.assertNotNull(beans.getAttribute("xmlns:context"));
Assert.assertNotNull(beans.getAttribute("xmlns:mvc"));
Assert.assertNotNull(beans.getAttribute("xsi:schemaLocation"));

Node mvcScan = beans.getSingle("context:component-scan");
Assert.assertNotNull(mvcScan);
Assert.assertEquals("test.mvc.package", mvcScan.getAttribute("base-package"));
Assert.assertNotNull(beans.getSingle("mvc:annotation-driven"));
Assert.assertNotNull(beans.getSingle("mvc:resources"));
// Should this element be added for non-root servlets?
//Assert.assertNotNull(beans.getSingle("mvc:default-servlet-handler"));

boolean viewResolver = false;

for (Node bean : beans.get("bean"))
{
if (bean.getAttribute("id") != null && bean.getAttribute("id").equals("viewResolver"))
{
viewResolver = true;
}
}

Assert.assertTrue(viewResolver);
return project;
}

private void checkAuthenticationManager(Node security) {
Node authenticationManager = security.getSingle("authentication-manager");
Assert.assertNotNull(authenticationManager);

Node authenticationProvider = authenticationManager.getSingle("authentication-provider");
Assert.assertNotNull(authenticationProvider);
Assert.assertEquals("userService", authenticationProvider.getAttribute("user-service-ref"));
}

private void checkHttpNode(Node security) {
Assert.assertNotNull(security.getAttribute("xmlns"));
Assert.assertNotNull(security.getAttribute("xmlns:beans"));
Assert.assertNotNull(security.getAttribute("xsi:schemaLocation"));

Node http = security.getSingle("http");
Assert.assertNotNull(http);
Assert.assertEquals("true", http.getAttribute("auto-config"));

Node interceptURL = http.getChildren().get(0);
Assert.assertEquals("/**/create*", interceptURL.getAttribute("pattern"));
Assert.assertEquals("ROLE_ADMIN", interceptURL.getAttribute("access"));
interceptURL = http.getChildren().get(1);
Assert.assertEquals("/**/edit*", interceptURL.getAttribute("pattern"));
Assert.assertEquals("ROLE_ADMIN", interceptURL.getAttribute("access"));

Node rememberMe = http.getSingle("remember-me");
Assert.assertNotNull(rememberMe);
}

@Test
public void testSecurityInMemory() throws Exception
{
Project project = prepSecurityTest();
queueInputLines("1", "", "");
getShell().execute("spring security");

SpringFacet spring = project.getFacet(SpringFacet.class);

Node security = XMLParser.parse(spring.getSecurityContextFile("").getResourceInputStream());

checkHttpNode(security);

Node userService = security.getSingle("user-service");
Assert.assertNotNull(userService);
Assert.assertEquals("userService", userService.getAttribute("id"));

Node user = userService.getSingle("user");
Assert.assertNotNull(user);
Assert.assertEquals("admin", user.getAttribute("name"));
Assert.assertEquals("adminPass", user.getAttribute("password"));
Assert.assertEquals("ROLE_ADMIN", user.getAttribute("authorities"));

checkAuthenticationManager(security);
}

@Test
public void testSecurityJDBC() throws Exception
{
Project project = prepSecurityTest();
queueInputLines("2", "testDataSource");
getShell().execute("spring security");

SpringFacet spring = project.getFacet(SpringFacet.class);

Node security = XMLParser.parse(spring.getSecurityContextFile("").getResourceInputStream());

checkHttpNode(security);

Node jdbcUserService = security.getSingle("jdbc-user-service");
Assert.assertNotNull(jdbcUserService);
Assert.assertEquals("userService", jdbcUserService.getAttribute("id"));
Assert.assertEquals("testDataSource", jdbcUserService.getAttribute("data-source-ref"));

checkAuthenticationManager(security);
}

@Test
public void testSecurityLDAP() throws Exception
{
Project project = prepSecurityTest();
queueInputLines("3", "ldap://forgeplugintest.com:389/dc=forge,dc=com");
getShell().execute("spring security");

SpringFacet spring = project.getFacet(SpringFacet.class);

Node security = XMLParser.parse(spring.getSecurityContextFile("").getResourceInputStream());

checkHttpNode(security);

Node userService = security.getSingle("ldap-user-service");
Assert.assertNotNull(userService);
Assert.assertEquals("userService", userService.getAttribute("id"));
Assert.assertEquals("(uid={0})", userService.getAttribute("user-search-filter"));
Assert.assertEquals("member={0}", userService.getAttribute("group-search-filter"));

Node server = security.getSingle("ldap-server");
Assert.assertNotNull(server);
Assert.assertEquals("ldap://forgeplugintest.com:389/dc=forge,dc=com", server.getAttribute("url"));

checkAuthenticationManager(security);
}
}

0 comments on commit fee5ea0

Please sign in to comment.