Skip to content

Commit

Permalink
Merge pull request #562 from agoncal/FORGE-2323
Browse files Browse the repository at this point in the history
FORGE-2323 : Being able to create a new servlet
  • Loading branch information
gastaldi committed May 11, 2015
2 parents 8a8c94c + af03270 commit ad80388
Show file tree
Hide file tree
Showing 5 changed files with 388 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public interface JavaEEFacet extends ProjectFacet
String DEFAULT_ENTITY_PACKAGE = "model";
String DEFAULT_CONSTRAINT_PACKAGE = "constraints";
String DEFAULT_CDI_PACKAGE = "beans";
String DEFAULT_SERVLET_PACKAGE = "web";
String DEFAULT_CDI_EXTENSIONS_PACKAGE = "beans.extensions";

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package org.jboss.forge.addon.javaee.servlet.ui;

import static org.jboss.forge.addon.javaee.JavaEEFacet.DEFAULT_SERVLET_PACKAGE;

import org.jboss.forge.addon.javaee.servlet.ServletFacet;
import org.jboss.forge.addon.parser.java.facets.JavaSourceFacet;
import org.jboss.forge.addon.parser.java.ui.AbstractJavaSourceCommand;
import org.jboss.forge.addon.projects.Project;
import org.jboss.forge.addon.ui.command.PrerequisiteCommandsProvider;
import org.jboss.forge.addon.ui.context.UIContext;
import org.jboss.forge.addon.ui.result.NavigationResult;
import org.jboss.forge.addon.ui.result.navigation.NavigationResultBuilder;
import org.jboss.forge.addon.ui.util.Categories;
import org.jboss.forge.addon.ui.util.Metadata;
import org.jboss.forge.roaster.model.source.JavaSource;

/**
* @author <a href="antonio.goncalves@gmail.com">Antonio Goncalves</a>
*/
public abstract class AbstractServletNewCommand<T extends JavaSource<?>> extends AbstractJavaSourceCommand<T>
implements PrerequisiteCommandsProvider
{

@Override
public Metadata getMetadata(UIContext context)
{
return Metadata.from(super.getMetadata(context), getClass())
.category(Categories.create(Categories.create("Java EE"), "Servlet"));
}

@Override
protected boolean isProjectRequired()
{
return true;
}

@Override
protected String calculateDefaultPackage(UIContext context)
{
return getSelectedProject(context).getFacet(JavaSourceFacet.class).getBasePackage() + "."
+ DEFAULT_SERVLET_PACKAGE;
}

@Override
public NavigationResult getPrerequisiteCommands(UIContext context)
{
NavigationResultBuilder builder = NavigationResultBuilder.create();
Project project = getSelectedProject(context);
if (project != null)
{
if (!project.hasFacet(ServletFacet.class))
{
builder.add(ServletSetupWizard.class);
}
}
return builder.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.addon.javaee.servlet.ui;

/**
* @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*/
public enum ServletMethod
{
GET("doGet"),
POST("doPost"),
PUT("doPut"),
DELETE("doDelete");

private String methodName;

private ServletMethod(String methodName)
{
this.methodName = methodName;
}

public String getMethodName()
{
return methodName;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/**
* Copyright 2014 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/

package org.jboss.forge.addon.javaee.servlet.ui;

import java.io.IOException;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jboss.forge.addon.projects.Project;
import org.jboss.forge.addon.text.Inflector;
import org.jboss.forge.addon.ui.context.UIBuilder;
import org.jboss.forge.addon.ui.context.UIContext;
import org.jboss.forge.addon.ui.context.UIExecutionContext;
import org.jboss.forge.addon.ui.input.UIInputMany;
import org.jboss.forge.addon.ui.input.UISelectMany;
import org.jboss.forge.addon.ui.metadata.WithAttributes;
import org.jboss.forge.addon.ui.util.Metadata;
import org.jboss.forge.furnace.util.Lists;
import org.jboss.forge.roaster.model.source.JavaClassSource;
import org.jboss.forge.roaster.model.source.MethodSource;

/**
* Creates a new Servlet
*
* @author <a href="mailto:antonio.goncalves@gmail.com">Antonio Goncalves</a>
*/
public class ServletNewServletCommand extends AbstractServletNewCommand<JavaClassSource>
{
@Inject
@WithAttributes(label = "Methods", description = "Servlet methods to be overridden")
private UISelectMany<ServletMethod> methods;

@Inject
@WithAttributes(label = "Url patterns", description = "List of URL patterns the servlet will be mapped to")
private UIInputMany<String> urlPatterns;

@Inject
private Inflector inflector;

@Override
public Metadata getMetadata(UIContext context)
{
return Metadata.from(super.getMetadata(context), getClass())
.name("Servlet: New Servlet")
.description("Creates a new Servlet");
}

@Override
protected String getType()
{
return "Servlet";
}

@Override
protected Class<JavaClassSource> getSourceType()
{
return JavaClassSource.class;
}

@Override
public void initializeUI(UIBuilder builder) throws Exception
{
super.initializeUI(builder);
builder.add(methods).add(urlPatterns);
}

@Override
public JavaClassSource decorateSource(UIExecutionContext context, Project project, JavaClassSource source)
throws Exception
{
source.setSuperType(HttpServlet.class);

if (urlPatterns.hasValue())
{
List<String> list = Lists.toList(urlPatterns.getValue());
String[] urlPatternsArray = list.toArray(new String[list.size()]);
source.addAnnotation(WebServlet.class).setStringArrayValue("urlPatterns", urlPatternsArray);
}
else
{
source.addAnnotation(WebServlet.class).setStringArrayValue("urlPatterns",
new String[] { inflector.lowerCamelCase(getNamed().getValue()) });
}

for (ServletMethod method : methods.getValue())
{
MethodSource<?> doGet = source.addMethod().setProtected().setName(method.getMethodName()).setReturnTypeVoid();
doGet.addParameter(HttpServletRequest.class, "request");
doGet.addParameter(HttpServletResponse.class, "response");
doGet.addThrows(ServletException.class).addThrows(IOException.class);
doGet.setBody("response.getWriter().println(\"Method " + method.getMethodName() + "\" invoked);").addAnnotation(
Override.class);
}

return source;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
/**
* Copyright 2014 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/

package org.jboss.forge.addon.javaee.servlet.ui;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.jboss.forge.addon.javaee.JavaEEFacet.DEFAULT_SERVLET_PACKAGE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;
import javax.servlet.annotation.WebServlet;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.forge.addon.javaee.ProjectHelper;
import org.jboss.forge.addon.javaee.servlet.ServletFacet;
import org.jboss.forge.addon.parser.java.facets.JavaSourceFacet;
import org.jboss.forge.addon.parser.java.resources.JavaResource;
import org.jboss.forge.addon.projects.Project;
import org.jboss.forge.addon.shell.test.ShellTest;
import org.jboss.forge.addon.ui.controller.CommandController;
import org.jboss.forge.addon.ui.metadata.UICommandMetadata;
import org.jboss.forge.addon.ui.result.Failed;
import org.jboss.forge.addon.ui.result.Result;
import org.jboss.forge.addon.ui.test.UITestHarness;
import org.jboss.forge.arquillian.AddonDependencies;
import org.jboss.forge.arquillian.archive.AddonArchive;
import org.jboss.forge.roaster.model.JavaClass;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
*
* @author <a href="antonio.goncalves@gmail.com">Antonio Goncalves</a>
*/
@RunWith(Arquillian.class)
public class ServletNewServletCommandTest
{
@Deployment
@AddonDependencies
public static AddonArchive getDeployment()
{
return ShrinkWrap.create(AddonArchive.class).addBeansXML().addClass(ProjectHelper.class);
}

@Inject
private UITestHarness uiTestHarness;

@Inject
private ShellTest shellTest;

@Inject
private ProjectHelper projectHelper;

private Project project;

@Before
public void setUp()
{
project = projectHelper.createJavaLibraryProject();
projectHelper.installServlet_3_1(project);
}

@Test
public void checkCommandMetadata() throws Exception
{
try (CommandController controller = uiTestHarness.createCommandController(ServletNewServletCommand.class,
project.getRoot()))
{
controller.initialize();
// Checks the command metadata
assertTrue(controller.getCommand() instanceof ServletNewServletCommand);
assertTrue(controller.getCommand() instanceof AbstractServletNewCommand);
UICommandMetadata metadata = controller.getMetadata();
assertEquals("Servlet: New Servlet", metadata.getName());
assertEquals("Java EE", metadata.getCategory().getName());
assertEquals("Servlet", metadata.getCategory().getSubCategory().getName());
assertEquals(5, controller.getInputs().size());
assertFalse("Project is created, shouldn't have targetLocation", controller.hasInput("targetLocation"));
assertTrue(controller.hasInput("named"));
assertTrue(controller.hasInput("targetPackage"));
assertTrue(controller.hasInput("overwrite"));
assertTrue(controller.hasInput("methods"));
assertTrue(controller.hasInput("urlPatterns"));
assertTrue(controller.getValueFor("targetPackage").toString().endsWith(DEFAULT_SERVLET_PACKAGE));
}
}

@Test
public void checkCommandShell() throws Exception
{
shellTest.getShell().setCurrentResource(project.getRoot());
Result result = shellTest.execute("servlet-new-servlet --named Dummy", 10, TimeUnit.SECONDS);

Assert.assertThat(result, not(instanceOf(Failed.class)));
Assert.assertTrue(project.hasFacet(ServletFacet.class));
}

@Test
public void testCreateNewServlet() throws Exception
{
try (CommandController controller = uiTestHarness.createCommandController(ServletNewServletCommand.class,
project.getRoot()))
{
controller.initialize();
controller.setValueFor("named", "MyServlet");
controller.setValueFor("targetPackage", "org.jboss.forge.test");
assertTrue(controller.isValid());
assertTrue(controller.canExecute());
Result result = controller.execute();
Assert.assertThat(result, is(not(instanceOf(Failed.class))));
}

JavaSourceFacet facet = project.getFacet(JavaSourceFacet.class);
JavaResource javaResource = facet.getJavaResource("org.jboss.forge.test.MyServlet");
Assert.assertNotNull(javaResource);
Assert.assertThat(javaResource.getJavaType(), is(instanceOf(JavaClass.class)));
assertEquals(0, javaResource.getJavaType().getSyntaxErrors().size());
assertTrue(javaResource.getJavaType().hasAnnotation(WebServlet.class));
assertEquals(1,
javaResource.getJavaType().getAnnotation(WebServlet.class).getStringArrayValue("urlPatterns").length);
assertEquals("myServlet",
javaResource.getJavaType().getAnnotation(WebServlet.class).getStringArrayValue("urlPatterns")[0]);
}

@Test
public void testCreateNewServletWithURLPatterns() throws Exception
{
try (CommandController controller = uiTestHarness.createCommandController(ServletNewServletCommand.class,
project.getRoot()))
{
controller.initialize();
controller.setValueFor("named", "MyServlet");
controller.setValueFor("targetPackage", "org.jboss.forge.test");
controller.setValueFor("urlPatterns", Arrays.asList("pattern1", "pattern2"));
assertTrue(controller.isValid());
assertTrue(controller.canExecute());
Result result = controller.execute();
Assert.assertThat(result, is(not(instanceOf(Failed.class))));
}

JavaSourceFacet facet = project.getFacet(JavaSourceFacet.class);
JavaResource javaResource = facet.getJavaResource("org.jboss.forge.test.MyServlet");
Assert.assertNotNull(javaResource);
Assert.assertThat(javaResource.getJavaType(), is(instanceOf(JavaClass.class)));
assertEquals(0, javaResource.getJavaType().getSyntaxErrors().size());
assertTrue(javaResource.getJavaType().hasAnnotation(WebServlet.class));
assertEquals(2,
javaResource.getJavaType().getAnnotation(WebServlet.class).getStringArrayValue("urlPatterns").length);
}

@Test
public void testCreateNewServletWithMethods() throws Exception
{
try (CommandController controller = uiTestHarness.createCommandController(ServletNewServletCommand.class,
project.getRoot()))
{
controller.initialize();
controller.setValueFor("named", "MyServlet");
controller.setValueFor("targetPackage", "org.jboss.forge.test");
controller.setValueFor("methods", Arrays.asList(ServletMethod.GET, ServletMethod.POST));
assertTrue(controller.isValid());
assertTrue(controller.canExecute());
Result result = controller.execute();
Assert.assertThat(result, is(not(instanceOf(Failed.class))));
}

JavaSourceFacet facet = project.getFacet(JavaSourceFacet.class);
JavaResource javaResource = facet.getJavaResource("org.jboss.forge.test.MyServlet");
Assert.assertNotNull(javaResource);
Assert.assertThat(javaResource.getJavaType(), is(instanceOf(JavaClass.class)));
assertEquals(0, javaResource.getJavaType().getSyntaxErrors().size());
assertTrue(javaResource.getJavaType().hasAnnotation(WebServlet.class));
JavaClass javaClass = javaResource.getJavaType();
assertEquals(2, javaClass.getMethods().size());
}
}

0 comments on commit ad80388

Please sign in to comment.