Starting a (basic) Jetty Server from Java

for information, I used this in a Spring Boot Application for RPC communication between Kafka instances for remote Ktable data retrieval based on Metadata

package net.myjettyserver;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

 * Created by michir on 14/05/2018.
public class RpcEndpoint {

    private static final String context = '/myapi'; // can be passed from command line

    // RPC Endpoint (listening host and port) in the format localhost:3000
    // can be passed from command line "--rpcEndpoint=localhost:3000"
    private String rpcEndpoint;

    private Server server;

    public void start() {
        try {

            this.server = new Server(Integer.parseInt(rpcEndpoint.split(":")[1]));
            server.setHandler(new AbstractHandler() {

                public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {                    
                    String uri = request.getRequestURI(); // in the format '/myapi/'

                    // process if "GET" method
                    if (request.getMethod().equalsIgnoreCase("get") && uri.startsWith(context)) {
                        String id = uri.substring(context.length()+1);
                        if (StringUtils.isEmpty(id)) {
                        } else {
                            // do something with the id


            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                try {
                } catch (Exception e) {
                    e.printStackTrace(); // can be ignored or WARN level logged
        } catch (Exception e) {
            throw new RuntimeException(e);

    public void stop() {
        try {
            if (!server.isStopped()) {
        } catch (Exception e) {

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s