title: Java: Run HTTP server on demand from my app?
body: <p>I want to write a <strong>simple P2P</strong> test app which uses HTTP as
  underlying protocol.<br>
  The app has to <strong>decide on demand</strong>, if it should
  act as a <strong>HTTP server</strong>, or as a <strong>HTTP client</strong>.</p>
  
  <p>The classic way which I am aware of, would be to deploy the app on
  some <strong>existing</strong> HTTP server. But this is the wrong way for my intention.
  It has to be the other way: the server is started by the app (and only
  if it decides to).</p>
  
  <p>Is there a way to execute the HTTP server part <strong>on demand</strong>
  (without deploying the app itself on a server)?</p>
  
  <p>Can I do it by linking Glassfish or Tomcat libraries
  and call some "main" method?</p>
  
  <p><strong>Edit: IT WORKS!!!</strong><br>
  I now tried <strong>Jetty</strong> along with <strong>JAX-RS (Jersey)</strong> successfully!<br>
  Thank you all.</p>
  
  <p>(the REST class is trivial and left out)</p>
  
  <p>package my.p2p;</p>
  
  <pre><code>import com.sun.jersey.spi.container.servlet.*;
  import org.mortbay.jetty.*;
  import org.mortbay.jetty.servlet.*;
  
  public class Main {
    public static void main(String[] args)
        throws Exception {
  
      ServletHolder holder = new ServletHolder(ServletContainer.class);
  
      holder.setInitParameter("com.sun.jersey.config.property.resourceConfigClass",
        "com.sun.jersey.api.core.PackagesResourceConfig");
      holder.setInitParameter("com.sun.jersey.config.property.packages", "my.p2p.rest");
  
      Server server = new Server(8000);
  
      Context context = new Context(server, "/", Context.SESSIONS);
      context.addServlet(holder, "/*");
      server.start();
    }
  }
  </code></pre>