org.eclipse.jetty.server.handler.AbstractHandler Java Examples

The following examples show how to use org.eclipse.jetty.server.handler.AbstractHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebhookTest.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
/** Create a Jetty handler that expects a request with a given content body. */
private AbstractHandler createHandlerThatExpectsContent(String expected) {
  return new AbstractHandler() {
    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request,
                       HttpServletResponse response) throws IOException, ServletException {
      String body = request.getReader().lines().collect(Collectors.joining());
      if (validateRequest(request) && body.equals(expected)) {
        response.setStatus(HttpServletResponse.SC_OK);
      } else {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      }
      baseRequest.setHandled(true);
    }
  };
}
 
Example #2
Source File: PlayerRequestJettyEntrance.java    From PeonyFramwork with Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws Exception {
    sessionService = BeanHelper.getServiceBean(SessionService.class);
    requestService = BeanHelper.getServiceBean(RequestService.class);
    accountSysService = BeanHelper.getServiceBean(AccountSysService.class);

    Handler entranceHandler = new AbstractHandler(){
        @Override
        public void handle(String target, Request baseRequest,
                           HttpServletRequest request, HttpServletResponse response) throws IOException {
            fire(request,response,"EntranceJetty");
        }
    };

    server = new Server(this.port);
    server.setHandler(entranceHandler);
    server.start();
}
 
Example #3
Source File: AlternatingRemoteMetaTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void beforeClass() throws Exception {
  final String[] mainArgs = new String[] { FullyRemoteJdbcMetaFactory.class.getName() };

  // Bind to '0' to pluck an ephemeral port instead of expecting a certain one to be free

  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < 2; i++) {
    if (sb.length() > 0) {
      sb.append(",");
    }
    HttpServer jsonServer = Main.start(mainArgs, 0, new HandlerFactory() {
      @Override public AbstractHandler createHandler(Service service) {
        return new AvaticaJsonHandler(service);
      }
    });
    ACTIVE_SERVERS.add(jsonServer);
    sb.append("http://localhost:").append(jsonServer.getPort());
  }

  url = AlternatingDriver.PREFIX + "url=" + sb.toString();
}
 
Example #4
Source File: ProxyServerTest.java    From microprofile-rest-client with Apache License 2.0 6 votes vote down vote up
public static void startDestinationServer(String responseContent) {
    DESTINATION_SERVER.setHandler(
        new AbstractHandler() {
            @Override
            public void handle(String path,
                               Request request,
                               HttpServletRequest httpRequest,
                               HttpServletResponse response) throws IOException {
                response.setHeader("Content-Type", "text/plain");
                response.setHeader("X-Via", request.getHeader("X-Via"));
                try (PrintWriter writer = response.getWriter()) {
                    writer.println(responseContent);
                }
            }
        });
    try {
        DESTINATION_SERVER.start();
    }
    catch (Exception e) {
        throw new RuntimeException("Failed to start destination server", e);
    }
}
 
Example #5
Source File: LegacyHttpServer.java    From grpc-proxy with Apache License 2.0 6 votes vote down vote up
private LegacyHttpServer(int port, int threads) {
  this.server = new Server(new QueuedThreadPool(threads));
  server.setHandler(
      new AbstractHandler() {
        @Override
        public void handle(
            String target,
            Request baseRequest,
            HttpServletRequest request,
            HttpServletResponse response)
            throws IOException {
          final String method = baseRequest.getParameter("method");
          if ("helloworld.Greeter/SayHello".equals(method)) {
            baseRequest.setHandled(true);
            sayHello(baseRequest, response);
          }
        }
      });

  final ServerConnector connector = new ServerConnector(server);
  connector.setPort(port);
  server.addConnector(connector);
}
 
Example #6
Source File: JdbcServer.java    From Quicksql with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    OptionsParser parser = new OptionsParser(args);
    final int port = Integer.parseInt(parser.getOptionValue(SubmitOption.PORT));
    final String[] mainArgs = new String[]{FullyRemoteJdbcMetaFactory.class.getName()};

    HttpServer server = Main.start(mainArgs, port, new HandlerFactory() {
        @Override
        public AbstractHandler createHandler(Service service) {
            return new AvaticaJsonHandler(service);
        }
    });
    InetAddress address = InetAddress.getLocalHost();
    String hostName = "localhost";
    if (address != null) {
         hostName = StringUtils.isNotBlank(address.getHostName()) ? address.getHostName() : address
            .getHostAddress();
    }
    String url = Driver.CONNECT_STRING_PREFIX + "url=http://" + hostName + ":" + server.getPort();
    System.out.println("Quicksql server started, Please connect : " + url);
    server.join();
}
 
Example #7
Source File: ConfigIntegrationTest.java    From apollo with Apache License 2.0 6 votes vote down vote up
private ContextHandler mockConfigServerHandler(final int statusCode, final ApolloConfig result,
    final boolean failedAtFirstTime) {
  ContextHandler context = new ContextHandler("/configs/*");
  context.setHandler(new AbstractHandler() {
    AtomicInteger counter = new AtomicInteger(0);

    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
      if (failedAtFirstTime && counter.incrementAndGet() == 1) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        baseRequest.setHandled(true);
        return;
      }

      response.setContentType("application/json;charset=UTF-8");
      response.setStatus(statusCode);
      response.getWriter().println(gson.toJson(result));
      baseRequest.setHandled(true);
    }
  });
  return context;
}
 
Example #8
Source File: TestDynamicLoadingUrl.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public static Pair<Server, Integer> runHttpServer(Map<String, Object> jars) throws Exception {
  final Server server = new Server();
  final ServerConnector connector = new ServerConnector(server);
  server.setConnectors(new Connector[] { connector });
  server.setHandler(new AbstractHandler() {
    @Override
    public void handle(String s, Request request, HttpServletRequest req, HttpServletResponse rsp)
      throws IOException {
      ByteBuffer b = (ByteBuffer) jars.get(s);
      if (b != null) {
        rsp.getOutputStream().write(b.array(), 0, b.limit());
        rsp.setContentType("application/octet-stream");
        rsp.setStatus(HttpServletResponse.SC_OK);
        request.setHandled(true);
      }
    }
  });
  server.start();
  return new Pair<>(server, connector.getLocalPort());
}
 
Example #9
Source File: HttpResponseStatisticsCollectorTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Before
public void initializeCollector() throws Exception {
    Server server = new Server();
    connector = new AbstractConnector(server, null, null, null, 0) {
        @Override
        protected void accept(int acceptorID) throws IOException, InterruptedException {
        }

        @Override
        public Object getTransport() {
            return null;
        }
    };
    collector.setHandler(new AbstractHandler() {
        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
                throws IOException, ServletException {
            baseRequest.setHandled(true);
            baseRequest.getResponse().setStatus(httpResponseCode);
        }
    });
    server.setHandler(collector);
    server.start();
}
 
Example #10
Source File: Counter.java    From nopol with GNU General Public License v2.0 6 votes vote down vote up
public static void run() throws Exception {
	server.setHandler(new AbstractHandler() {
		@Override
		public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
			target = target.substring(1);
			if (isHandled(target)) {
				count(target);
				response.setContentType("text/html;charset=utf-8");
				response.setStatus(HttpServletResponse.SC_OK);
				baseRequest.setHandled(true);
				response.getWriter().println(target);
			} else {
				response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
				baseRequest.setHandled(true);
			}
		}
	});
	server.start();
}
 
Example #11
Source File: WebDemo.java    From EasySRL with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
              final Server server = new Server(Integer.valueOf(args[0]));
              final SRLParser parser = makeParser(args[1]);

              server.setHandler(new AbstractHandler() {
                      @Override
                      public void handle(final String target, final Request baseRequest, final HttpServletRequest request,
                                         final HttpServletResponse response) throws IOException, ServletException {
                              final String sentence = baseRequest.getParameter("sentence");
                              response.setContentType("text/html; charset=utf-8");
                              response.setStatus(HttpServletResponse.SC_OK);
                              doParse(parser, sentence, response.getWriter());
                              baseRequest.setHandled(true);
                      }
              });
              server.start();
              server.join();
}
 
Example #12
Source File: HttpClientIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@BeforeAll
void startJetty() throws Exception {
    jetty = new org.eclipse.jetty.server.Server(0);
    jetty.setHandler(new AbstractHandler() {
        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                           HttpServletResponse response) throws IOException, ServletException {
            if (Collections.list(request.getHeaders("host")).size() == 1) {
                response.setStatus(HttpStatus.OK.code());
            } else {
                response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.code());
            }
            baseRequest.setHandled(true);
        }
    });
    jetty.start();
}
 
Example #13
Source File: ProxyServletMain.java    From caja with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  // http://docs.codehaus.org/display/JETTY/Embedding+Jetty
  int port = 8887;
  Server server = new Server(port);

  final ProxyServlet servlet = new ProxyServlet();

  server.setHandler(new AbstractHandler() {
    public void handle(
        String target, Request baseRequest, HttpServletRequest req,
        HttpServletResponse resp)
        throws ServletException {
      try {
        servlet.service(req, resp);
      } catch (IOException e) {
        throw (ServletException) new ServletException().initCause(e);
      }
    }
  });
  server.start();
}
 
Example #14
Source File: VRaptorServer.java    From mamute with Apache License 2.0 6 votes vote down vote up
private ContextHandler systemRestart() {
	AbstractHandler system = new AbstractHandler() {
		@Override
		public void handle(String target, Request baseRequest,
				HttpServletRequest request, HttpServletResponse response)
				throws IOException, ServletException {
			restartContexts();
			response.setContentType("text/html;charset=utf-8");
			response.setStatus(HttpServletResponse.SC_OK);
			baseRequest.setHandled(true);
			response.getWriter().println("<h1>Done</h1>");
		}
	};
	ContextHandler context = new ContextHandler();
	context.setContextPath("/vraptor/restart");
	context.setResourceBase(".");
	context.setClassLoader(Thread.currentThread().getContextClassLoader());
	context.setHandler(system);
	return context;
}
 
Example #15
Source File: HttpTestServer.java    From smartsheet-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an {@link AbstractHandler handler} returning an arbitrary String as a response.
 *
 * @return never <code>null</code>.
 */
public Handler getMockHandler() {
    Handler handler = new AbstractHandler() {

        //@Override
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {

            setRequestBody(IOUtils.toString(baseRequest.getInputStream()));

            response.setStatus(getStatus());
            response.setContentType(getContentType());

            byte[] body = getResponseBody();

            response.setContentLength(body.length);
            IOUtils.write(body, response.getOutputStream());

            baseRequest.setHandled(true);
        }
    };
    return handler;
}
 
Example #16
Source File: AdminWebServer.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
private Handler buildSettingsHandler() {
  final String responseTemplate = "var Gobblin = window.Gobblin || {};" + "Gobblin.settings = {restServerUrl:\"%s\", hideJobsWithoutTasksByDefault:%s, refreshInterval:%s}";

  return new AbstractHandler() {
    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
      if (request.getRequestURI().equals("/js/settings.js")) {
        response.setContentType("application/javascript");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().println(String.format(responseTemplate, AdminWebServer.this.restServerUri.toString(),
            AdminWebServer.this.hideJobsWithoutTasksByDefault, AdminWebServer.this.refreshInterval));
        baseRequest.setHandled(true);
      }
    }
  };
}
 
Example #17
Source File: ConfigIntegrationTest.java    From apollo with Apache License 2.0 5 votes vote down vote up
private ContextHandler mockPollNotificationHandler(final long pollResultTimeOutInMS,
    final int statusCode,
    final List<ApolloConfigNotification> result,
    final boolean failedAtFirstTime) {
  ContextHandler context = new ContextHandler("/notifications/v2");
  context.setHandler(new AbstractHandler() {
    AtomicInteger counter = new AtomicInteger(0);

    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
      if (failedAtFirstTime && counter.incrementAndGet() == 1) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        baseRequest.setHandled(true);
        return;
      }

      try {
        TimeUnit.MILLISECONDS.sleep(pollResultTimeOutInMS);
      } catch (InterruptedException e) {
      }

      response.setContentType("application/json;charset=UTF-8");
      response.setStatus(statusCode);
      response.getWriter().println(gson.toJson(result));
      baseRequest.setHandled(true);
    }
  });

  return context;
}
 
Example #18
Source File: WebServer.java    From haxademic with MIT License 5 votes vote down vote up
public WebServer(AbstractHandler handler, boolean debug, String wwwPath, boolean useSSL) {
	WebServer.DEBUG = debug;
	this.handler = handler;
	this.wwwPath = wwwPath;
	this.useSSL = useSSL;
	WWW_PATH = wwwPath;
	IS_SSL = useSSL;
	
	new Thread(new Runnable() { public void run() {
		initWebServer();
	}}).start();
}
 
Example #19
Source File: SlaManagerTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
private AbstractHandler mockCoordinatorResponses(String mockResponse) {
  return new AbstractHandler() {
    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request,
                       HttpServletResponse response) throws IOException {
      createResponse(baseRequest, response, mockResponse);
    }
  };
}
 
Example #20
Source File: SlaManagerTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
private AbstractHandler mockCoordinatorResponse(
    IScheduledTask task,
    String pollResponse,
    Map<String, String> params) {

  return new AbstractHandler() {
    @Override
    public void handle(
        String target,
        Request baseRequest,
        HttpServletRequest request,
        HttpServletResponse response) throws IOException {
      try {
        String taskKey = slaManager.getTaskKey(task);
        String query = Joiner
            .on("=")
            .join(SlaManager.TASK_PARAM, URLEncoder.encode(taskKey, "UTF-8"));

        String taskConfig = new TSerializer(new TSimpleJSONProtocol.Factory())
            .toString(task.newBuilder());
        JsonObject jsonBody = new JsonObject();
        jsonBody.add("taskConfig", new JsonParser().parse(taskConfig));
        jsonBody.addProperty(SlaManager.TASK_PARAM, taskKey);
        params.forEach(jsonBody::addProperty);
        String body = new Gson().toJson(jsonBody);

        if (request.getQueryString().equals(query)
            && request.getReader().lines().collect(Collectors.joining()).equals(body)) {
          createResponse(baseRequest, response, pollResponse);
        }
        coordinatorResponded.countDown();
      } catch (TException e) {
        fail();
      }
    }
  };
}
 
Example #21
Source File: ApiCenter.java    From binlake with Apache License 2.0 5 votes vote down vote up
static void register(String route, AbstractHandler handler) {
    ContextHandler context = new ContextHandler();
    context.setContextPath(route);
    context.setResourceBase(".");
    context.setClassLoader(Thread.currentThread().getContextClassLoader());
    context.setHandler(handler);
    CONTEXTS.add(context);
}
 
Example #22
Source File: DoctorCommandIntegrationTest.java    From buck with Apache License 2.0 5 votes vote down vote up
private AbstractHandler createEndpointHttpdHandler(String expectedMethod, String expectedBody) {
  return new AbstractHandler() {
    @Override
    public void handle(
        String s,
        Request request,
        HttpServletRequest httpRequest,
        HttpServletResponse httpResponse)
        throws IOException {
      httpResponse.setStatus(200);
      request.setHandled(true);

      if (request.getHttpURI().getPath().equals("/status.php")) {
        return;
      }

      httpResponse.setContentType("application/json");
      httpResponse.setCharacterEncoding("utf-8");

      requestPath.set(request.getHttpURI().getPath());
      requestMethod.set(request.getMethod());
      requestBody.set(ByteStreams.toByteArray(httpRequest.getInputStream()));

      assertTrue(requestMethod.get().equalsIgnoreCase(expectedMethod));
      assertThat(
          "Request should contain the uuid.",
          new String(requestBody.get(), Charsets.UTF_8),
          Matchers.containsString(expectedBody));

      try (DataOutputStream out = new DataOutputStream(httpResponse.getOutputStream())) {
        ObjectMappers.WRITER.writeValue((DataOutput) out, doctorResponse);
      }
    }
  };
}
 
Example #23
Source File: HttpServerMock.java    From JavaTutorial with Apache License 2.0 5 votes vote down vote up
private Handler createHandler(final String content, final String contentType, 
        final int statusCode) {
    return new AbstractHandler() {
        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            response.setContentType(contentType);
            response.setStatus(statusCode);
            baseRequest.setHandled(true);
            response.getWriter().print(content);
        }
    };
}
 
Example #24
Source File: SlaManagerTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
private AbstractHandler mockCoordinatorError() {
  return new AbstractHandler() {
    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request,
                       HttpServletResponse response) {
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      baseRequest.setHandled(true);
      coordinatorResponded.countDown();
    }
  };
}
 
Example #25
Source File: ProxySettingTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
private Server createSimpleHttpServer(final String responseHtml) {
  return createServer(new AbstractHandler() {
    @Override
    public void handle(String s, Request baseRequest, HttpServletRequest request,
                       HttpServletResponse response) throws IOException {
      response.setContentType("text/html; charset=utf-8");
      response.setStatus(HttpServletResponse.SC_OK);
      response.getWriter().println(responseHtml);
      baseRequest.setHandled(true);
    }
  });
}
 
Example #26
Source File: ReferrerTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
PacFileServerResource() {
  addHandler(new AbstractHandler() {
    @Override
    public void handle(String s, Request baseRequest, HttpServletRequest request,
                       HttpServletResponse response) throws IOException {
      response.setContentType("application/x-javascript-config; charset=us-ascii");
      response.setStatus(HttpServletResponse.SC_OK);
      response.getWriter().println(getPacFileContents());
      baseRequest.setHandled(true);
    }
  });
}
 
Example #27
Source File: ReporterFactoryTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() throws Exception {
    server = new Server();

    Path keyStorePath = Paths.get(ReporterFactoryTest.class.getResource("/keystore").toURI());
    final SslContextFactory sslContextFactory = new SslContextFactory(keyStorePath.toAbsolutePath().toString());
    sslContextFactory.setKeyStorePassword("password");
    sslContextFactory.getSslContext();

    final HttpConfiguration httpConfiguration = new HttpConfiguration();
    httpConfiguration.setSecureScheme("https");
    httpConfiguration.setSecurePort(0);

    final HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration);
    httpsConfiguration.addCustomizer(new SecureRequestCustomizer());
    final ServerConnector httpsConnector = new ServerConnector(server,
        new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
        new HttpConnectionFactory(httpsConfiguration));
    httpsConnector.setPort(0);
    server.addConnector(httpsConnector);
    server.setHandler(new AbstractHandler() {
        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) {
            baseRequest.setHandled(true);
            requestHandled.set(true);
        }
    });
    server.start();
    configuration = SpyConfiguration.createSpyConfig();
    reporterConfiguration = configuration.getConfig(ReporterConfiguration.class);
    when(reporterConfiguration.getServerUrls()).thenReturn(Collections.singletonList(new URL("https://localhost:" + getPort())));
}
 
Example #28
Source File: RequestJettyPBEntrance.java    From PeonyFramwork with Apache License 2.0 5 votes vote down vote up
@Override
    public void start() throws Exception {
//        log.info(sessionService);
        Handler entranceHandler = new AbstractHandler(){
            @Override
            public void handle(String target, Request baseRequest,
                               HttpServletRequest request, HttpServletResponse response) throws IOException {
                fire(request,response,"RequestJettyPBEntrance");
            }
        };
        server = new Server(this.port);
        server.setHandler(entranceHandler);
        server.start();
    }
 
Example #29
Source File: ServerManager.java    From raccoon4 with Apache License 2.0 5 votes vote down vote up
/**
 * Start the webserver.
 * 
 * @param lm
 *          the {@link Lifecycle} to notify when a client initiates a transfer
 *          the user should know about.
 */
public void startup(LifecycleManager lm) {
	this.appListHandler = new AppListHandler(layout, lm);
	this.focusedAppHandler = new AppListHandler(layout, lm);
	this.fileHandler = new FileHandler(lm);
	this.resourceHandler = new ResourceHandler();

	ContextHandler list = new ContextHandler(APPCOLLECTIONPATH);
	list.setHandler(appListHandler);

	ContextHandler focused = new ContextHandler(APPSINGLEPATH);
	focused.setHandler(focusedAppHandler);

	ContextHandler files = new ContextHandler(FILEPATH);
	files.setHandler(fileHandler);

	ContextHandler rsrc = new ContextHandler(RSRCPATH);
	rsrc.setHandler(resourceHandler);

	AbstractHandler[] tmp = { list, focused, files, rsrc };

	ContextHandlerCollection handlers = new ContextHandlerCollection();
	handlers.setHandlers(tmp);

	server = new Server(0);
	server.setHandler(handlers);

	try {
		server.start();
	}
	catch (Exception e) {
		e.printStackTrace();
	}

	synchronized (lock) {
		lock.notifyAll();
	}
}
 
Example #30
Source File: ProxySettingTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
private Server createPacfileServer(final String pacFileContents) {
  return createServer(new AbstractHandler() {
    @Override
    public void handle(String s, Request baseRequest, HttpServletRequest request,
                       HttpServletResponse response) throws IOException {
      response.setContentType("application/x-javascript-config; charset=us-ascii");
      response.setStatus(HttpServletResponse.SC_OK);
      response.getWriter().println(pacFileContents);
      baseRequest.setHandled(true);
    }
  });
}