GlassFish glassfish = new GlassFish(port);
It is not only possible to start glassfish in embedded code, it is even possible to deploy applications on the fly. The following code does exactly that:
ScatteredWar war = new
ScatteredWar(NAME, new File("src/main/resources"), new
File("src/main/resources/WEB-INF/web.xml"), Collections.singleton(new
File("build/classes").toURI().toURL()));
glassfish.deploy(war);
...and the full test code:
import org.glassfish.embed.GlassFish;
import org.glassfish.embed.ScatteredWar;
//and other obvious imports
public class HelloServletTest{
private final String NAME = "AppTest";
public static int port = 9999;
private GlassFish glassFish;
@Before
public void bootGlassfish() throws Exception{
this.glassFish = newGlassFish(port);
assertNotNull(this.glassFish);
}
@Test
public void testServlet() throws Exception {
URL url = new URL("http://localhost:" + port + "/" + NAME + "/HelloServlet");
BufferedReader br = new BufferedReader(
new InputStreamReader(
url.openConnection().getInputStream()));
assertEquals("Hallo from servlet", br.readLine());
}
private GlassFish newGlassFish(int port) throws Exception {
GlassFish glassfish = new GlassFish(port);
ScatteredWar war = new ScatteredWar(NAME,
new File("src/main/resources"),
new File("src/main/resources/WEB-INF/web.xml"),
Collections.singleton(new File("build/classes").toURI().toURL()));
glassfish.deploy(war);
System.out.println("Ready ...");
return glassfish;
}
@After
public void shutdown(){
this.glassFish.stop();
}
The unit test is only a sample, in general I woul start glassfish in the static @BeforeClass method - for one test it is good enough.
Glassfish v3 is not production ready yet - but it becomes more and more interesting for development. Cannot wait for embeddable EJB 3 containers :-).
I checked in the whole project (with servlet, glassfish jars and the unit test) into the p4j5. The project name is: EmbeddedGlassfishWeb. The remaining question is: from where I have this two jars - the answer is simple: from the maven repository :-).
So, and I'm going to present this stuff now - I'm at Jazoon :-).