benashby
8/4/2017 - 4:34 PM

TomcatUberExample.java

package com.ximasoftware;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;

import org.apache.catalina.startup.Tomcat;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.Context;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import java.io.File;
import java.net.MalformedURLException;

/**
 * Hello world!
 *
 */
public class App {
	public static void main(String[] args) throws Exception {
		new App().start();
	}

	public void start() throws Exception {

		Tomcat tomcat = new Tomcat();

		// Bind the port to Tomcat server
		tomcat.setPort(8082);

		// Define a web application context.
		Context context = tomcat.addWebapp("/tomcatembedded", "C:/tmp");

		// Add servlet that will register Jersey REST resources
		Tomcat.addServlet(context, "jersey-container-servlet", resourceConfig());
		context.addServletMapping("/rest/*", "jersey-container-servlet");

		tomcat.start();
		tomcat.getServer().await();

	}

	private ServletContainer resourceConfig() {
		return new ServletContainer(new ResourceConfig(new ResourceLoader().getClasses()));
	}

	public static class ResourceLoader extends Application {

		@Override
		public Set<Class<?>> getClasses() {
			final Set<Class<?>> classes = new HashSet<Class<?>>();

			classes.add(EndpointOne.class);
			return classes;
		}

	}

	@Path("/helloworld")
	public static class EndpointOne {

		@GET
		@Produces(MediaType.TEXT_PLAIN)
		public String sayHello() {
			return "Hello World from Tomcat Embedded with Jersey!";
		}

	}
}