Skip to main content

Embedded GlassFish : Programatically running asadmin commands from a servlet.

Posted by bhavanishankar on September 11, 2011 at 10:03 PM PDT



GlassFishEmbedded.java





Recently there has been lot of requests in GlassFish community asking
for programmatic interface to run asadmin commands from within a
servlet. This is very easy when the servlet is deployed on Embedded
GlassFish.



When you embed GlassFish, you just need to bind the embeddable command
runner in JNDI, like this:

import org.glassfish.embeddable.*;
import javax.naming.InitialContext;

public class GlassFishEmbedded {

public static void main(String... args) {
   GlassFishProperties props = new GlassFishProperties();
   props.setPort("http-listener", 8080);
   GlassFish glassfish = GlassFishRuntime.bootstrap().newGlassFish(props);
   glassfish.start();

   // Bind the command runner in JNDI tree with your own mapped-name
   CommandRunner commandRunner = glassfish.getCommandRunner();
   new InitialContext().bind("org.glassfish.embeddable.CommandRunner", commandRunner);

   // Deploy your web-app containg RunAdminCommandsServlet using glassfish.getDeployer().deploy(...) method
}
}

Thats it, now from your RunAdminCommandsServlet you can inject the
command runner like this:

import org.glassfish.embeddable.*;
import javax.annotation.Resource;

@WebServlet(name = "RunAdminCommandsServlet",
urlPatterns = "/RunAdminCommandsServlet")
public class RunAdminCommandsServlet extends HttpServlet {

@Resource(mappedName = "org.glassfish.embeddable.CommandRunner")
CommandRunner commandRunner;

@Override
protected void doGet(HttpServletRequest httpServletRequest,
   HttpServletResponse httpServletResponse) throws ServletException, IOException {
     if (commandRunner != null) {
       CommandResult result = commandRunner.run("create-jdbc-connection-pool",
                                            "--datasourceclassname=org.apache.derby.jdbc.ClientDataSource",
                                            "--restype=javax.sql.XADataSource",
                                            "--property=portNumber=1527:password=APP:user=APP:serverName=localhost:databaseName=sun-appserv-samples:connectionAttributes=create\\=true",
                                            "sample_derby_pool");
    }
  }
}






Related Topics >>

Comments

Thank you very much for this explanation.

Thank you very much for this explanation.