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.*; name="l2">
import class="s1">javax.naming.InitialContext;

name="l5">public class GlassFishEmbedded {
name="l6">
public static void class="s1">main(String... args) {
GlassFishProperties props = class="s0">new GlassFishProperties();
name="l9"> props.setPort("http-listener"class="s1">, 8080);
name="l10"> GlassFish glassfish = GlassFishRuntime.bootstrap().newGlassFish(props);
name="l11"> glassfish.start();

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

class="s3">// Deploy your web-app containg RunAdminCommandsServlet using glassfish.getDeployer().deploy(...) method.class="s1">
} name="l17">
}


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

 
class="s2">import org.glassfish.embeddable.*; name="l44">
import class="s1">javax.annotation.Resource; class="s1">
import ...class="s1">;

class="s0">@WebServlet(name = "RunAdminCommandsServlet"class="s1">,
urlPatterns = class="s4">"/RunAdminCommandsServlet")
name="l59">public class RunAdminCommandsServlet class="s2">extends HttpServlet {
name="l60">
@Resource(mappedName = class="s4">"org.glassfish.embeddable.CommandRunner"class="s1">)
CommandRunner commandRunner;
name="l63">
@Override
class="s2">protected void doGet(HttpServletRequest httpServletRequest,
name="l66"> HttpServletResponse httpServletResponse) class="s2">throws ServletException, IOException {
name="l67"> if (commandRunner != class="s2">null) {
CommandResult result = commandRunner.run(class="s4">"create-jdbc-connection-pool",
name="l69"> "--datasourceclassname=org.apache.derby.jdbc.ClientDataSource"class="s1">,
class="s4">"--restype=javax.sql.XADataSource",
name="l71"> "--property=portNumber=1527:password=APP:user=APP:serverName=localhost:databaseName=sun-appserv-samples:connectionAttributes=createclass="s5">\\=true",
name="l72"> "sample_derby_pool"class="s1">);
}
name="l74"> }
}

name="l77">






Related Topics >>

Comments

Thank you very much for this explanation.

Thank you very much for this explanation.