Java Code Examples for io.undertow.Handlers

The following examples show how to use io.undertow.Handlers. These examples are extracted from open source projects. 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 Project: quarkus-http   Source File: TestMessagesReceivedInOrder.java    License: Apache License 2.0 9 votes vote down vote up
@BeforeClass
public static void setup() throws ServletException {

    final ServletContainer container = ServletContainer.Factory.newInstance();

    DeploymentInfo builder = new DeploymentInfo()
            .setClassLoader(TestMessagesReceivedInOrder.class.getClassLoader())
            .setContextPath("/")
            .setResourceManager(new TestResourceLoader(TestMessagesReceivedInOrder.class))
            .setClassIntrospecter(TestClassIntrospector.INSTANCE)
            .addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME,
                    new WebSocketDeploymentInfo()
                            .setDispatchToWorkerThread(true)
                            .addEndpoint(EchoSocket.class)
            )
            .setDeploymentName("servletContext.war");


    DeploymentManager manager = container.addDeployment(builder);
    manager.deploy();


    DefaultServer.setRootHandler(Handlers.path().addPrefixPath("/", manager.start()));
}
 
Example 2
@BeforeClass
public static void setup() {
    DefaultServer.setRootHandler(new BlockingHandler(Handlers.requestLimitingHandler(2, N_THREADS, new HttpHandler() {
        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            int res = count.incrementAndGet();
            try {
                if (!latch.await(20, TimeUnit.SECONDS)) {
                    exchange.setStatusCode(500);
                } else {
                    exchange.getOutputStream().write(("" + res).getBytes("US-ASCII"));
                }
            } finally {
                count.decrementAndGet();
            }
        }
    })));

}
 
Example 3
Source Project: quarkus-http   Source File: ExceptionHandlerTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testReThrowUnmatchedException() throws IOException {
    HttpHandler pathHandler = Handlers.path()
            .addExactPath("/", new HttpHandler() {
                @Override
                public void handleRequest(HttpServerExchange exchange) throws Exception {
                    throw new IllegalArgumentException();
                }
            });

    // intentionally not adding any exception handlers
    final HttpHandler exceptionHandler = Handlers.exceptionHandler(pathHandler);
    DefaultServer.setRootHandler(exceptionHandler);

    TestHttpClient client = new TestHttpClient();
    try {
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.INTERNAL_SERVER_ERROR, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example 4
Source Project: quarkus-http   Source File: RangeRequestTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setup() throws URISyntaxException {
    Path rootPath = Paths.get(RangeRequestTestCase.class.getResource("range.txt").toURI()).getParent();
    PathHandler path = Handlers.path();
    path.addPrefixPath("/path", new ByteRangeHandler(new HttpHandler() {
        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            exchange.setResponseHeader(HttpHeaderNames.LAST_MODIFIED, DateUtils.toDateString(new Date(10000)));
            exchange.setResponseHeader(HttpHeaderNames.ETAG, "\"someetag\"");
            exchange.setResponseContentLength("0123456789".length());
            exchange.writeAsync(Unpooled.copiedBuffer("0123456789", StandardCharsets.UTF_8), true, IoCallback.END_EXCHANGE, null);
        }
    }, true));
    path.addPrefixPath("/resource",  new ResourceHandler( new PathResourceManager(rootPath, 10485760))
            .setDirectoryListingEnabled(true));
    path.addPrefixPath("/cachedresource",  new ResourceHandler(new CachingResourceManager(1000, 1000000, new DirectBufferCache(1000, 10, 10000), new PathResourceManager(rootPath, 10485760), -1))
            .setDirectoryListingEnabled(true));
    path.addPrefixPath("/resource-blocking",  new BlockingHandler(new ResourceHandler( new PathResourceManager(rootPath, 10485760))
            .setDirectoryListingEnabled(true)));
    path.addPrefixPath("/cachedresource-blocking",  new BlockingHandler(new ResourceHandler(new CachingResourceManager(1000, 1000000, new DirectBufferCache(1000, 10, 10000), new PathResourceManager(rootPath, 10485760), -1))
            .setDirectoryListingEnabled(true)));
    DefaultServer.setRootHandler(path);
}
 
Example 5
Source Project: SikuliX1   Source File: SikulixServer.java    License: MIT License 6 votes vote down vote up
private static Undertow createServer(int port, String ipAddr) {
  ControllerCommand controller = new ControllerCommand();
  TasksCommand tasks = new TasksCommand();
  ScriptsCommand scripts = new ScriptsCommand(tasks);
  GroupsCommand groups = new GroupsCommand(scripts);

  ResourceManager resourceManager = new ClassPathResourceManager(RunTime.class.getClassLoader(), "htdocs");
  ResourceHandler resource = new ResourceHandler(resourceManager, AbstractCommand.getFallbackHandler());
  resource.addWelcomeFiles("ControlBox.html");

  RoutingHandler commands = Handlers.routing()
          .addAll(controller.getRouting())
          .addAll(tasks.getRouting())
          .addAll(scripts.getRouting())
          .addAll(groups.getRouting())
          .setFallbackHandler(resource);
  CommandRootHttpHandler cmdRoot = new CommandRootHttpHandler(commands);
  cmdRoot.addExceptionHandler(Throwable.class, AbstractCommand.getExceptionHttpHandler());

  Undertow server = Undertow.builder()
          .addHttpListener(port, ipAddr)
          .setServerOption(UndertowOptions.RECORD_REQUEST_START_TIME, true)
          .setHandler(cmdRoot)
          .build();
  return server;
}
 
Example 6
Source Project: greycat   Source File: WSServerWithWorkers.java    License: Apache License 2.0 6 votes vote down vote up
public void start() {

        logger.debug("WSServer starting");
        PathHandler pathHandler;
        if (this.defaultHandler != null) {
            pathHandler = Handlers.path(defaultHandler);
        } else {
            pathHandler = Handlers.path();
        }
        for (String name : handlers.keySet()) {
            pathHandler.addPrefixPath(name, handlers.get(name));
        }

        String serverPath = "ws://" + SERVER_IP + ":" + port + SERVER_PREFIX;
        this.server = Undertow.builder()
                .addHttpListener(port, SERVER_IP, pathHandler)
                .setServerOption(UndertowOptions.NO_REQUEST_TIMEOUT, wsMaxIdle)
                .setServerOption(UndertowOptions.IDLE_TIMEOUT, wsMaxIdle)
                .setServerOption(UndertowOptions.ALWAYS_SET_KEEP_ALIVE, true)
                .build();

        server.start();
        logger.info("WSServer started on " + serverPath);
    }
 
Example 7
Source Project: greycat   Source File: WSServer.java    License: Apache License 2.0 6 votes vote down vote up
public void start() {
    PathHandler pathHandler;
    if (this.defaultHandler != null) {
        pathHandler = Handlers.path(defaultHandler);
    } else {
        pathHandler = Handlers.path();
    }
    for (String name : handlers.keySet()) {
        pathHandler.addPrefixPath(name, handlers.get(name));
    }
    this.server = Undertow.builder().addHttpListener(port, "0.0.0.0", pathHandler).build();
    DeferCounterSync deferCounterSync = new CoreDeferCounterSync(1);
    executorService = Executors.newFixedThreadPool(Math.max(1, thread));
    this.resolver = new ResolverWorker(resultsToResolve, peers);
    this.graphExec = new GraphExecutor(builder, graphInput, deferCounterSync, resultsToResolve);
    server.start();
    resolver.start();
    graphExec.start();
    deferCounterSync.waitResult();
}
 
Example 8
Source Project: syndesis   Source File: EventBusToWebSocket.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void customize(DeploymentInfo deploymentInfo) {
    deploymentInfo.addInitialHandlerChainWrapper(handler -> {
            return Handlers.path()
                .addPrefixPath("/", handler)
                .addPrefixPath(path, new WebSocketProtocolHandshakeHandler(new WSHandler()) {
                    @Override
                    @SuppressWarnings("PMD.SignatureDeclareThrowsException")
                    public void handleRequest(HttpServerExchange exchange) throws Exception {
                        if (reservationCheck(exchange)) {
                            super.handleRequest(exchange);
                        }
                    }
                });
        }
    );
}
 
Example 9
Source Project: syndesis   Source File: EventBusToServerSentEvents.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void customize(DeploymentInfo deploymentInfo) {
    deploymentInfo.addInitialHandlerChainWrapper(handler -> {
            return Handlers.path()
                .addPrefixPath("/", handler)
                .addPrefixPath(path, new ServerSentEventHandler(new EventBusHandler()){
                    @Override
                    @SuppressWarnings("PMD.SignatureDeclareThrowsException")
                    public void handleRequest(HttpServerExchange exchange) throws Exception {
                        if( reservationCheck(exchange) ) {
                            super.handleRequest(exchange);
                        }
                    }
                });
        }
    );
}
 
Example 10
Source Project: light-rest-4j   Source File: ResponseValidatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    if(server == null) {
        logger.info("starting server");
        TestValidateResponseHandler testValidateResponseHandler = new TestValidateResponseHandler();
        HttpHandler handler = Handlers.routing()
                .add(Methods.GET, "/v1/todoItems", testValidateResponseHandler);
        ValidatorHandler validatorHandler = new ValidatorHandler();
        validatorHandler.setNext(handler);
        handler = validatorHandler;

        BodyHandler bodyHandler = new BodyHandler();
        bodyHandler.setNext(handler);
        handler = bodyHandler;

        OpenApiHandler openApiHandler = new OpenApiHandler();
        openApiHandler.setNext(handler);
        handler = openApiHandler;

        server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(handler)
                .build();
        server.start();
    }
}
 
Example 11
Source Project: light-4j   Source File: DerefMiddlewareHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
static PathHandler getTestHandler() {
    return Handlers.path()
            .addPrefixPath("/api", (exchange) -> {
                // check if the Authorization header contains JWT token here.
                String authHeader = exchange.getRequestHeaders().getFirst(Headers.AUTHORIZATION);
                Assert.assertEquals("Bearer " + token, authHeader);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
                exchange.getResponseSender().send("OK");
            });
}
 
Example 12
Source Project: quarkus-http   Source File: Http2Server.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    String version = System.getProperty("java.version");
    System.out.println("Java version " + version);
    if(version.charAt(0) == '1' && Integer.parseInt(version.charAt(2) + "") < 8 ) {
        System.out.println("This example requires Java 1.8 or later");
        System.out.println("The HTTP2 spec requires certain cyphers that are not present in older JVM's");
        System.out.println("See section 9.2.2 of the HTTP2 specification for details");
        System.exit(1);
    }
    String bindAddress = System.getProperty("bind.address", "localhost");
    SSLContext sslContext = createSSLContext(loadKeyStore("server.keystore"), loadKeyStore("server.truststore"));
    Undertow server = Undertow.builder()
            .setServerOption(UndertowOptions.ENABLE_HTTP2, true)
            .addHttpListener(8080, bindAddress)
            .addHttpsListener(8443, bindAddress, sslContext)
            .setHandler(new SessionAttachmentHandler(new LearningPushHandler(100, -1, Handlers.header(predicate(secure(), resource(new PathResourceManager(Paths.get(System.getProperty("example.directory", System.getProperty("user.home"))), 100))
                    .setDirectoryListingEnabled(true), new HttpHandler() {
                @Override
                public void handleRequest(HttpServerExchange exchange) throws Exception {
                    exchange.getResponseHeaders().add(Headers.LOCATION, "https://" + exchange.getHostName() + ":" + (exchange.getHostPort() + 363) + exchange.getRelativePath());
                    exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
                }
            }), "x-undertow-transport", ExchangeAttributes.transportProtocol())), new InMemorySessionManager("test"), new SessionCookieConfig())).build();

    server.start();

    SSLContext clientSslContext = createSSLContext(loadKeyStore("client.keystore"), loadKeyStore("client.truststore"));
    LoadBalancingProxyClient proxy = new LoadBalancingProxyClient()
            .addHost(new URI("https://localhost:8443"), null, new UndertowXnioSsl(Xnio.getInstance(), OptionMap.EMPTY, clientSslContext), UndertowOptionMap.create(UndertowOptions.ENABLE_HTTP2, true))
            .setConnectionsPerThread(20);

    Undertow reverseProxy = Undertow.builder()
            .setServerOption(UndertowOptions.ENABLE_HTTP2, true)
            .addHttpListener(8081, bindAddress)
            .addHttpsListener(8444, bindAddress, sslContext)
            .setHandler(ProxyHandler.builder().setProxyClient(proxy).setMaxRequestTime( 30000).build())
            .build();
    reverseProxy.start();

}
 
Example 13
Source Project: light-oauth2   Source File: PathHandlerProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public HttpHandler getHandler() {
    return Handlers.routing()


        .add(Methods.POST, "/oauth2/provider", new Oauth2ProviderPostHandler())
        .add(Methods.GET, "/oauth2/provider", new Oauth2ProviderGetHandler())
       .add(Methods.DELETE, "/oauth2/provider/{providerId}", new Oauth2ProviderProviderIdDeleteHandler())
            .add(Methods.GET, "/health", new HealthGetHandler())
        .add(Methods.GET, "/server/info", new ServerInfoGetHandler())
            .add(Methods.PUT, "/oauth2/provider", new Oauth2ProviderPutHandler())

            ;
}
 
Example 14
Source Project: light-eventuate-4j   Source File: CdcServer.java    License: Apache License 2.0 5 votes vote down vote up
public HttpHandler getHandler() {
    return Handlers.path()
            .addPrefixPath("/", new HttpHandler() {
                        public void handleRequest(HttpServerExchange exchange) {
                            exchange.getResponseSender().send("OK!");
                        }
                    }
            );
}
 
Example 15
Source Project: mangooio   Source File: Application.java    License: Apache License 2.0 5 votes vote down vote up
private static void prepareUndertow() {
    Config config = getInstance(Config.class);
    
    HttpHandler httpHandler;
    if (config.isMetricsEnable()) {
        httpHandler = MetricsHandler.HANDLER_WRAPPER.wrap(Handlers.exceptionHandler(pathHandler)
                .addExceptionHandler(Throwable.class, Application.getInstance(ExceptionHandler.class)));
    } else {
        httpHandler = Handlers.exceptionHandler(pathHandler)
                .addExceptionHandler(Throwable.class, Application.getInstance(ExceptionHandler.class));
    }
    
    Builder builder = Undertow.builder()
            .setServerOption(UndertowOptions.MAX_ENTITY_SIZE, config.getUndertowMaxEntitySize())
            .setHandler(httpHandler);

    httpHost = config.getConnectorHttpHost();
    httpPort = config.getConnectorHttpPort();
    ajpHost = config.getConnectorAjpHost();
    ajpPort = config.getConnectorAjpPort();

    boolean hasConnector = false;
    if (httpPort > 0 && StringUtils.isNotBlank(httpHost)) {
        builder.addHttpListener(httpPort, httpHost);
        hasConnector = true;
    }
    
    if (ajpPort > 0 && StringUtils.isNotBlank(ajpHost)) {
        builder.addAjpListener(ajpPort, ajpHost);
        hasConnector = true;
    }
            
    if (hasConnector) {
        undertow = builder.build();
        undertow.start();
    } else {
        LOG.error("No connector found! Please configure a HTTP and/or AJP connector in your config.props");
        failsafe();
    }
}
 
Example 16
Source Project: light-4j   Source File: WhitelistHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
static RoutingHandler getTestHandler() {
    return Handlers.routing()
            .add(Methods.GET, "/data", exchange -> {
                exchange.getResponseSender().send("OK");
            })
            .add(Methods.GET, "/default", exchange -> {
                exchange.getResponseSender().send("OK");
            })
            .add(Methods.GET, "/health/com.networknt.petstore-1.0.0", exchange -> {
                exchange.getResponseSender().send("OK");
            });
}
 
Example 17
Source Project: keycloak   Source File: TestClassProvider.java    License: Apache License 2.0 5 votes vote down vote up
public void start() {
    server = Undertow.builder()
            .addHttpListener(8500, "localhost")
            .setHandler(Handlers.resource(new ClassPathResourceManager()))
            .build();
    server.start();

    LOGGER.infov("Started test class provider on http://localhost:8500");
}
 
Example 18
Source Project: greycat   Source File: WSSharedServer.java    License: Apache License 2.0 5 votes vote down vote up
public WSSharedServer(Graph p_graph, int p_port) {
    this.graph = p_graph;
    this.port = p_port;
    peers = new HashSet<WebSocketChannel>();
    handlers = new HashMap<String, HttpHandler>();
    handlers.put(PREFIX, Handlers.websocket(this));
}
 
Example 19
Source Project: light-oauth2   Source File: PathHandlerProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public HttpHandler getHandler() {
    IMap<String, User> users = CacheStartupHookProvider.hz.getMap("users");
    final IdentityManager identityManager = new MapIdentityManager(users);

    HttpHandler handler = Handlers.routing()
        .add(Methods.GET, "/health", new HealthGetHandler())
        .add(Methods.GET, "/server/info", new ServerInfoGetHandler())
        .add(Methods.GET, "/oauth2/authorize", addBasicSecurity(new Oauth2AuthorizeGetHandler(), identityManager))
        .add(Methods.POST, "/oauth2/authorize", addFormSecurity(new Oauth2AuthorizePostHandler(), identityManager))
    ;
    return handler;
}
 
Example 20
Source Project: light-4j   Source File: ContentHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
static RoutingHandler getTestHandler() {
  return Handlers.routing()
    .add(Methods.GET, "/", exchange -> {
      exchange.getResponseSender().send("This is just a proof");
    })
    .add(Methods.GET, "/xml", exchange -> {
      exchange
        .getResponseSender()
        .send("<bookstore><book><title>The best of Light-4j</title>" +
          "<author>Steve Hu</author><year>2018</year></book></bookstore>");
    })
    .add(Methods.GET, "/json", exchange -> {
      exchange.getResponseSender().send("{\"bookstore\":{\"book\":{\"title\":\"The best of Light-4j\",\"author\":\"Steve Hu\"}}}");
    });
}
 
Example 21
Source Project: greycat   Source File: Server.java    License: Apache License 2.0 5 votes vote down vote up
public Server() {
    Undertow server = Undertow.builder().addHttpListener(port, "0.0.0.0",
            Handlers.path()
                    .addPrefixPath("rpc", this)
                    .addPrefixPath("/", new ResourceHandler(new ClassPathResourceManager(Server.class.getClassLoader(), "static")).addWelcomeFiles("index.html").setDirectoryListingEnabled(false))
    ).build();
    server.start();
    System.out.println("Server running at : 9077");
}
 
Example 22
Source Project: light-4j   Source File: BodyStringCachingTest.java    License: Apache License 2.0 5 votes vote down vote up
static RoutingHandler getTestHandler() {
    return Handlers.routing()
            .add(Methods.POST, "/post", exchange -> {
                String bodyString = (String) exchange.getAttachment(BodyHandler.REQUEST_BODY_STRING);
                if (bodyString == null) {
                    exchange.getResponseSender().send("nobody");
                } else {
                    exchange.getResponseSender().send(bodyString);
                }
            });
}
 
Example 23
Source Project: zooadmin   Source File: Main.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DeploymentInfo servletBuilder = Servlets.deployment()
            .setContextPath("/")
            .setClassLoader(Main.class.getClassLoader())
            .setDeploymentName("zooadmin.war")
            ;
    Integer port= PropUtil.getInt("port");
    String host=PropUtil.getString("host");
    String resource=PropUtil.getString("resource");
    FilterInfo jfinalFilter=new FilterInfo("jfinal",JFinalFilter.class);
    jfinalFilter.addInitParam("configClass","com.baicai.core.Config");
    servletBuilder.addFilter(jfinalFilter);
    servletBuilder.addFilterUrlMapping("jfinal","/*", DispatcherType.REQUEST);
    servletBuilder.addFilterUrlMapping("jfinal","/*", DispatcherType.FORWARD);
    servletBuilder.setResourceManager(new FileResourceManager(new File(resource), 1024));


    DeploymentManager manager = Servlets.defaultContainer().addDeployment(servletBuilder);
    manager.deploy();
    PathHandler path = Handlers.path(Handlers.redirect("/"))
           .addPrefixPath("/", manager.start());
    Undertow server = Undertow.builder()
            .addHttpListener(port, host)
            .setHandler(path)
            .build();
    // start server
    server.start();
    log.info("http://"+host+":"+port);
}
 
Example 24
Source Project: griffin   Source File: Server.java    License: Apache License 2.0 5 votes vote down vote up
/**
    * Creates and starts the server to serve the contents of OUTPUT_DIRECTORY on port
9090.
    */
   protected void startPreview() {
       ResourceHandler resourceHandler = resource(new PathResourceManager(Paths.get(OUTPUT_DIRECTORY), 100, true, true))
               .setDirectoryListingEnabled(false);
       FileErrorPageHandler errorHandler = new FileErrorPageHandler(Paths.get(OUTPUT_DIRECTORY).resolve("404.html"), StatusCodes.NOT_FOUND);
       errorHandler.setNext(resourceHandler);
       GracefulShutdownHandler shutdown = Handlers.gracefulShutdown(errorHandler);
       Undertow server = Undertow.builder().addHttpListener(port, "localhost")
               .setHandler(shutdown)
               .build();
       server.start();
   }
 
Example 25
Source Project: light-4j   Source File: MetricsHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public MiddlewareHandler setNext(final HttpHandler next) {
    Handlers.handlerNotNull(next);
    this.next = next;
    return this;

}
 
Example 26
Source Project: cxf   Source File: UndertowHTTPServerEngine.java    License: Apache License 2.0 5 votes vote down vote up
private Undertow createServer(URL url, UndertowHTTPHandler undertowHTTPHandler) throws Exception {
    Undertow.Builder result = Undertow.builder();
    result.setServerOption(UndertowOptions.IDLE_TIMEOUT, getMaxIdleTime());
    if (this.shouldEnableHttp2(undertowHTTPHandler.getBus())) {
        result.setServerOption(UndertowOptions.ENABLE_HTTP2, Boolean.TRUE);
    }
    if (tlsServerParameters != null) {
        if (this.sslContext == null) {
            this.sslContext = createSSLContext();
        }
        result = result.addHttpsListener(getPort(), getHost(), this.sslContext);
    } else {
        result = result.addHttpListener(getPort(), getHost());
    }
    path = Handlers.path(new NotFoundHandler());

    if (url.getPath().length() == 0) {
        result = result.setHandler(Handlers.trace(undertowHTTPHandler));
    } else {
        if (undertowHTTPHandler.isContextMatchExact()) {
            path.addExactPath(url.getPath(), undertowHTTPHandler);
        } else {
            path.addPrefixPath(url.getPath(), undertowHTTPHandler);
        }

        result = result.setHandler(wrapHandler(new HttpContinueReadHandler(path)));
    }

    result = decorateUndertowSocketConnection(result);
    result = disableSSLv3(result);
    result = configureThreads(result);
    return result.build();
}
 
Example 27
Source Project: light-rest-4j   Source File: JwtVerifyHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
static RoutingHandler getTestHandler() {
    return Handlers.routing()
            .add(Methods.GET, "/v1/pets/{petId}", exchange -> {
                Map<String, Object> examples = new HashMap<>();
                examples.put("application/xml", StringEscapeUtils.unescapeHtml4("&lt;Pet&gt;  &lt;id&gt;123456&lt;/id&gt;  &lt;name&gt;doggie&lt;/name&gt;  &lt;photoUrls&gt;    &lt;photoUrls&gt;string&lt;/photoUrls&gt;  &lt;/photoUrls&gt;  &lt;tags&gt;  &lt;/tags&gt;  &lt;status&gt;string&lt;/status&gt;&lt;/Pet&gt;"));
                examples.put("application/json", StringEscapeUtils.unescapeHtml4("{  &quot;photoUrls&quot; : [ &quot;aeiou&quot; ],  &quot;name&quot; : &quot;doggie&quot;,  &quot;id&quot; : 123456789,  &quot;category&quot; : {    &quot;name&quot; : &quot;aeiou&quot;,    &quot;id&quot; : 123456789  },  &quot;tags&quot; : [ {    &quot;name&quot; : &quot;aeiou&quot;,    &quot;id&quot; : 123456789  } ],  &quot;status&quot; : &quot;aeiou&quot;}"));
                if(examples.size() > 0) {
                    exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
                    exchange.getResponseSender().send((String)examples.get("application/json"));
                } else {
                    exchange.endExchange();
                }
            })
            .add(Methods.GET, "/v1/pets", exchange -> exchange.getResponseSender().send("get"));
}
 
Example 28
Source Project: light-rest-4j   Source File: JwtVerifyHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
static RoutingHandler getTestHandler() {
    return Handlers.routing()
            .add(Methods.GET, "/v2/pet/{petId}", exchange -> {
                Map<String, Object> examples = new HashMap<>();
                examples.put("application/xml", StringEscapeUtils.unescapeHtml4("&lt;Pet&gt;  &lt;id&gt;123456&lt;/id&gt;  &lt;name&gt;doggie&lt;/name&gt;  &lt;photoUrls&gt;    &lt;photoUrls&gt;string&lt;/photoUrls&gt;  &lt;/photoUrls&gt;  &lt;tags&gt;  &lt;/tags&gt;  &lt;status&gt;string&lt;/status&gt;&lt;/Pet&gt;"));
                examples.put("application/json", StringEscapeUtils.unescapeHtml4("{  &quot;photoUrls&quot; : [ &quot;aeiou&quot; ],  &quot;name&quot; : &quot;doggie&quot;,  &quot;id&quot; : 123456789,  &quot;category&quot; : {    &quot;name&quot; : &quot;aeiou&quot;,    &quot;id&quot; : 123456789  },  &quot;tags&quot; : [ {    &quot;name&quot; : &quot;aeiou&quot;,    &quot;id&quot; : 123456789  } ],  &quot;status&quot; : &quot;aeiou&quot;}"));
                if(examples.size() > 0) {
                    exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
                    exchange.getResponseSender().send((String)examples.get("application/json"));
                } else {
                    exchange.endExchange();
                }
            })
            .add(Methods.GET, "/v2/pet", exchange -> exchange.getResponseSender().send("get"));
}
 
Example 29
Source Project: light-rest-4j   Source File: OpenApiHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
static RoutingHandler getTestHandler() {
    return Handlers.routing()
            .add(Methods.GET, "/pets", exchange -> exchange.getResponseSender().send("get"))
            .add(Methods.POST, "/v1/pets", exchange -> {
                Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO);
                if(auditInfo != null) {
                    exchange.getResponseSender().send("withAuditInfo");
                } else {
                    exchange.getResponseSender().send("withoutAuditInfo");
                }
            })
            .add(Methods.DELETE, "/v1/pets", exchange -> exchange.getResponseSender().send("deleted"));
}
 
Example 30
Source Project: light-eventuate-4j   Source File: CdcServer.java    License: Apache License 2.0 5 votes vote down vote up
public HttpHandler getHandler() {
    return Handlers.path()
            .addPrefixPath("/", new HttpHandler() {
                        public void handleRequest(HttpServerExchange exchange) {
                            exchange.getResponseSender().send("OK!");
                        }
                    }
            );
}