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); }
@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(); }
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; }
public static Server getFileServer(ApplicationContext context) { Resource resource = context.getResource("classpath:templates"); Server server = new Server(UrlTestingUtils.TEST_FILE_SERVER_PORT); server.setHandler(new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String uri = baseRequest.getRequestURI(); LOGGER.info(uri); File file = new File(resource.getFile().getAbsolutePath() + uri); MultipartFileSender fileSender = MultipartFileSender.fromFile(file); try { fileSender.with(request).with(response).serveResource(); } catch (IOException e) { e.printStackTrace(); } } }); return server; }
@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(); }
@Override public AbstractHandler configureHandler() throws Exception { return new AbstractHandler() { public void handle(String target, Request baseRequest, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { ServletInputStream in = req.getInputStream(); byte[] b = new byte[8192]; int count = -1; int total = 0; while ((count = in.read(b)) != -1) { b = new byte[8192]; total += count; } resp.setStatus(200); resp.addHeader("X-TRANFERED", String.valueOf(total)); resp.getOutputStream().flush(); resp.getOutputStream().close(); baseRequest.setHandled(true); } }; }
@BeforeClass @Override public void setUpGlobal() throws Exception { port1 = findFreePort(); port2 = findFreePort(); server = newJettyHttpServer(port1); addHttpConnector(server, port2); HandlerList list = new HandlerList(); list.addHandler(new AbstractHandler() { @Override public void handle(String s, Request request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { if (request.getLocalPort() == port2) { httpServletResponse.sendRedirect(getTargetUrl()); } } }); list.addHandler(getWebSocketHandler()); server.setHandler(list); server.start(); logger.info("Local HTTP server started successfully"); }
TestServer() throws Exception { jettyServer = new Server(0); jettyServer.setHandler(new AbstractHandler() { public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (target.equals("/test-app")) { response.sendRedirect("/test-app/"); } else if (target.equalsIgnoreCase("/test-app/slow")) { try { Thread.sleep(Long.parseLong(request.getParameter("millis"))); } catch (InterruptedException e) { Thread.interrupted(); } response.getWriter().append("This was slow"); } else { response.setHeader("Server", "Test-Server"); response.getWriter().append("Hello from test server").close(); } baseRequest.setHandled(true); } }); jettyServer.start(); int port = ((ServerConnector) jettyServer.getConnectors()[0]).getLocalPort(); url = new URL("http://localhost:" + port + "/test-app"); }
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(); }
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(); }
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(); }
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; }
/** * 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; }
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); } } }; }
private Handler getHandler(){ AbstractHandler handler = new AbstractHandler() { @Override public void handle(String target, Request request, HttpServletRequest servletRequest, HttpServletResponse response) throws IOException, ServletException { //String url = request.getRequestURI(); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("application/json;charset=utf-8"); try { BaseMessage message = MAPPER.readValue(request.getInputStream(), BaseMessage.class); MAPPER.writeValue(response.getOutputStream(), coordinator.handle(message)); } catch (Exception ex){ ex.printStackTrace(); LOGGER.debug(ex); Response r = new Response(); r.put("exception", ex.getMessage()); MAPPER.writeValue(response.getOutputStream(), r); } response.getOutputStream().close(); request.setHandled(true); } }; return handler; }
@Before public void startHttpServer() throws Exception { jettyServer = new Server(7000); jettyServer.setHandler(new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setStatus(httpStatus); response.setContentType("text/plain"); try(PrintWriter writer = response.getWriter()) { writer.println("Hello, world!"); } } }); jettyServer.start(); }
public static void main(String[] args) throws Exception { logger.info("KevoreeKernel sample HTTP server, browse to http://localhost:8080/"); Server server = new Server(8080); server.setHandler(new AbstractHandler() { @Override public void handle(String s, Request request, HttpServletRequest httpServletRequest, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); request.setHandled(true); response.getWriter().println("<h1>Hello World</h1>"); } }); server.start(); server.join(); }
protected ContextHandler mockMetaServerHandler(final boolean failedAtFirstTime) { final ServiceDTO someServiceDTO = new ServiceDTO(); someServiceDTO.setAppName(someAppName); someServiceDTO.setInstanceId(someInstanceId); someServiceDTO.setHomepageUrl(configServiceURL); final AtomicInteger counter = new AtomicInteger(0); ContextHandler context = new ContextHandler("/services/config"); context.setHandler(new AbstractHandler() { @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(HttpServletResponse.SC_OK); response.getWriter().println(gson.toJson(Lists.newArrayList(someServiceDTO))); baseRequest.setHandled(true); } }); return context; }
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; }
private void attachNoContentHandler() { AbstractHandler noContentHandler = new NoContentOutputErrorHandler(); // This part is needed to avoid WARN while starting container. noContentHandler.setServer(server); server.addBean(noContentHandler); }
@Override public void start() throws Exception { // System.out.println(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(); }
@Override public void start() throws Exception{ Handler entranceHandler = new AbstractHandler(){ @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException{ } }; server = new Server(this.port); server.setHandler(entranceHandler); server.start(); }
@Override public AbstractHandler configureHandler() throws Exception { return new AbstractHandler() { @Override public void handle(String pathInContext, Request request, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException { String redirectHeader = httpRequest.getHeader("X-REDIRECT"); if (redirectHeader != null) { httpResponse.setStatus(Integer.valueOf(redirectHeader)); httpResponse.setContentLength(0); httpResponse.setHeader("Location", getTargetUrl()); } else { httpResponse.setStatus(200); int len = request.getContentLength(); httpResponse.setContentLength(len); if (len > 0) { byte[] buffer = new byte[len]; IOUtils.read(request.getInputStream(), buffer); httpResponse.getOutputStream().write(buffer); } receivedContentType = request.getContentType(); } httpResponse.getOutputStream().flush(); httpResponse.getOutputStream().close(); } }; }
@Override public AbstractHandler configureHandler() throws Exception { return new AbstractHandler() { public void handle(String target, Request baseRequest, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { resp.setStatus(401); resp.getOutputStream().flush(); resp.getOutputStream().close(); baseRequest.setHandled(true); } }; }
@Override public AbstractHandler configureHandler() throws Exception { return new AbstractHandler() { public void handle(String arg0, Request arg1, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { resp.setStatus(200); resp.getOutputStream().flush(); resp.getOutputStream().close(); arg1.setHandled(true); } }; }
@Override public AbstractHandler configureHandler() throws Exception { return new AbstractHandler() { public void handle(String s, Request r, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { resp.setContentType("text/pain"); String arg = s.substring(1); resp.setHeader(ARG_HEADER, arg); resp.setStatus(200); resp.getOutputStream().print(arg); resp.getOutputStream().flush(); resp.getOutputStream().close(); } }; }
@BeforeClass(alwaysRun = true) public void setUpGlobal() throws Exception { port1 = findFreePort(); server = newJettyHttpServer(port1); server.setHandler(new AbstractHandler() { public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { int MAX_BODY_SIZE = 1024; // Can only handle bodies of up to 1024 bytes. byte[] b = new byte[MAX_BODY_SIZE]; int offset = 0; int numBytesRead; try (ServletInputStream is = request.getInputStream()) { while ((numBytesRead = is.read(b, offset, MAX_BODY_SIZE - offset)) != -1) { offset += numBytesRead; } } assertEquals(request.getContentLength(), offset); response.setStatus(200); response.setCharacterEncoding(request.getCharacterEncoding()); response.setContentLength(request.getContentLength()); try (ServletOutputStream os = response.getOutputStream()) { os.write(b, 0, offset); } } }); server.start(); }
private Handler createHomeRedirect() { return new AbstractHandler() { public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if ("/".equals(target)) { if (StringUtils.isNotEmpty(defaultAppName)) { response.sendRedirect("/" + defaultAppName); } else { response.sendError(404, "You can set a default app by setting the " + Config.DEFAULT_APP_NAME + " property."); } baseRequest.setHandled(true); } } }; }
private Handler createHomeRedirect() { return new AbstractHandler() { public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if ("/".equals(target)) { if (StringUtils.isNotEmpty(defaultAppName)) { response.sendRedirect("/" + defaultAppName); } else { response.sendError(400, "You can set a default app by setting the " + Config.DEFAULT_APP_NAME + " property."); } baseRequest.setHandled(true); } } }; }
public Server(AbstractHandler handler, int port) { this.server = new org.eclipse.jetty.server.Server(port); server.setHandler(handler); try { server.start(); assert(server.isStarted()); } catch (Exception e) { throw new RuntimeException(e); } }
@Before public void setUp() throws Exception { /* * We start a Jetty for the service in order to have better control over * the response The response must contain only a Content-Type and a * Content-Length but no other header */ log.info("Starting jetty server at port {}", JETTY_PORT); server = new Server(); // Do not send a Server header HttpConfiguration httpconf = new HttpConfiguration(); httpconf.setSendServerVersion(false); ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpconf)); http.setPort(JETTY_PORT); server.addConnector(http); server.setHandler(new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/xml"); // the Content-Length is correct for this response message response.setContentLength(RESPONSE_MESSAGE.length()); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); PrintWriter pw = response.getWriter(); pw.write(RESPONSE_MESSAGE); pw.close(); } }); server.start(); // Load the CXF endpoints for the route log.info("Start Routing Scenario at port {}", CXFTestSupport.getPort1()); applicationContext = new ClassPathXmlApplicationContext("org/apache/camel/component/cxf/CxfPayloadRouterContentLengthBeans.xml"); super.setUp(); assertNotNull("Should have created a valid spring context", applicationContext); }
@Override protected void doStart() throws Exception { AbstractHandler noContentHandler = new NoContentOutputErrorHandler(); // This part is needed to avoid WARN while starting container. noContentHandler.setServer(server); server.addBean(noContentHandler); // Create the servlet context final ServletContextHandler context = new ServletContextHandler(server, "/management/*", ServletContextHandler.SESSIONS); // REST configuration final ServletHolder servletHolder = new ServletHolder(ServletContainer.class); servletHolder.setInitParameter("javax.ws.rs.Application", GraviteeApplication.class.getName()); servletHolder.setInitOrder(0); context.addServlet(servletHolder, "/*"); // Spring configuration System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "basic"); AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext(); webApplicationContext.register(SecurityConfiguration.class); webApplicationContext.setEnvironment((ConfigurableEnvironment) applicationContext.getEnvironment()); webApplicationContext.setParent(applicationContext); context.addEventListener(new ContextLoaderListener(webApplicationContext)); // Spring Security filter context.addFilter(new FilterHolder(new DelegatingFilterProxy("springSecurityFilterChain")),"/*", EnumSet.allOf(DispatcherType.class)); // start the server server.start(); }
private void addHandlers(HandlerCollection parentHandler, Collection<? extends AbstractHandler> childHandlers) { if (!childHandlers.isEmpty()) { for (AbstractHandler h : childHandlers) { parentHandler.addHandler(h); } } }
/** * Creates an {@link AbstractHandler handler} returning an arbitrary String as a response. * * @return never <code>null</code>. */ public Handler getMockHandler() { Handler handler = new AbstractHandler() { public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { setResponseBody(getMockResponseData()); setRequestBody(IOUtils.toString(baseRequest.getInputStream())); response.setStatus(SC_OK); response.setContentType("application/json"); response.getWriter().write(getResponseBody()); baseRequest.setHandled(true); } }; return handler; }