Search in sources :

Example 41 with Undertow

use of io.undertow.Undertow in project undertow by undertow-io.

the class BasicAuthServer method main.

public static void main(final String[] args) {
    System.out.println("You can login with the following credentials:");
    System.out.println("User: userOne Password: passwordOne");
    System.out.println("User: userTwo Password: passwordTwo");
    final Map<String, char[]> users = new HashMap<>(2);
    users.put("userOne", "passwordOne".toCharArray());
    users.put("userTwo", "passwordTwo".toCharArray());
    final IdentityManager identityManager = new MapIdentityManager(users);
    Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(addSecurity(new HttpHandler() {

        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            final SecurityContext context = exchange.getSecurityContext();
            exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(), IoCallback.END_EXCHANGE);
        }
    }, identityManager)).build();
    server.start();
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) HttpHandler(io.undertow.server.HttpHandler) IdentityManager(io.undertow.security.idm.IdentityManager) HashMap(java.util.HashMap) SecurityContext(io.undertow.security.api.SecurityContext) Undertow(io.undertow.Undertow)

Example 42 with Undertow

use of io.undertow.Undertow in project undertow by undertow-io.

the class SessionServer method main.

public static void main(String[] args) {
    PathHandler pathHandler = new PathHandler();
    pathHandler.addPrefixPath("/", new HttpHandler() {

        public void handleRequest(HttpServerExchange exchange) throws Exception {
            StringBuilder sb = new StringBuilder();
            sb.append("<form action='addToSession' >");
            sb.append("<label>Attribute Name</label>");
            sb.append("<input name='attrName' />");
            sb.append("<label>Attribute Value</label>");
            sb.append("<input name='value' />");
            sb.append("<button>Save to Session</button>");
            // To retrive the SessionManager use the attachmentKey
            SessionManager sm = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
            // same goes to SessionConfig
            SessionConfig sessionConfig = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
            sb.append("</form>");
            sb.append("<a href='/destroySession'>Destroy Session</a>");
            sb.append("<br/>");
            Session session = sm.getSession(exchange, sessionConfig);
            if (session == null)
                session = sm.createSession(exchange, sessionConfig);
            sb.append("<ul>");
            for (String string : session.getAttributeNames()) {
                sb.append("<li>" + string + " : " + session.getAttribute(string) + "</li>");
            }
            sb.append("</ul>");
            exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "text/html;");
            exchange.getResponseSender().send(sb.toString());
        }
    });
    pathHandler.addPrefixPath("/addToSession", new HttpHandler() {

        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            SessionManager sm = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
            SessionConfig sessionConfig = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
            Map<String, Deque<String>> reqParams = exchange.getQueryParameters();
            Session session = sm.getSession(exchange, sessionConfig);
            if (session == null)
                session = sm.createSession(exchange, sessionConfig);
            Deque<String> deque = reqParams.get("attrName");
            Deque<String> dequeVal = reqParams.get("value");
            session.setAttribute(deque.getLast(), dequeVal.getLast());
            exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
            exchange.getResponseHeaders().put(Headers.LOCATION, "/");
            exchange.getResponseSender().close();
        }
    });
    pathHandler.addPrefixPath("/destroySession", new HttpHandler() {

        public void handleRequest(HttpServerExchange exchange) throws Exception {
            SessionManager sm = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
            SessionConfig sessionConfig = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
            Session session = sm.getSession(exchange, sessionConfig);
            if (session == null)
                session = sm.createSession(exchange, sessionConfig);
            session.invalidate(exchange);
            exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
            exchange.getResponseHeaders().put(Headers.LOCATION, "/");
            exchange.getResponseSender().close();
        }
    });
    SessionManager sessionManager = new InMemorySessionManager("SESSION_MANAGER");
    SessionCookieConfig sessionConfig = new SessionCookieConfig();
    /*
         * Use the sessionAttachmentHandler to add the sessionManager and
         * sessionCofing to the exchange of every request
         */
    SessionAttachmentHandler sessionAttachmentHandler = new SessionAttachmentHandler(sessionManager, sessionConfig);
    // set as next handler your root handler
    sessionAttachmentHandler.setNext(pathHandler);
    System.out.println("Open the url and fill the form to add attributes into the session");
    Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(sessionAttachmentHandler).build();
    server.start();
}
Also used : HttpHandler(io.undertow.server.HttpHandler) SessionManager(io.undertow.server.session.SessionManager) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager) PathHandler(io.undertow.server.handlers.PathHandler) SessionConfig(io.undertow.server.session.SessionConfig) Deque(java.util.Deque) HttpServerExchange(io.undertow.server.HttpServerExchange) SessionAttachmentHandler(io.undertow.server.session.SessionAttachmentHandler) SessionCookieConfig(io.undertow.server.session.SessionCookieConfig) Map(java.util.Map) Undertow(io.undertow.Undertow) Session(io.undertow.server.session.Session) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager)

Example 43 with Undertow

use of io.undertow.Undertow in project undertow by undertow-io.

the class FileServer method main.

public static void main(final String[] args) {
    Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(resource(new PathResourceManager(Paths.get(System.getProperty("user.home")), 100)).setDirectoryListingEnabled(true)).build();
    server.start();
}
Also used : Undertow(io.undertow.Undertow) PathResourceManager(io.undertow.server.handlers.resource.PathResourceManager)

Example 44 with Undertow

use of io.undertow.Undertow in project undertow by undertow-io.

the class ModClusterTestSetup method main.

public static void main(final String[] args) throws IOException {
    final Undertow server;
    final XnioWorker worker = Xnio.getInstance().createWorker(OptionMap.EMPTY);
    final ModCluster modCluster = ModCluster.builder(worker).setHealthCheckInterval(TimeUnit.SECONDS.toMillis(3)).setRemoveBrokenNodes(TimeUnit.SECONDS.toMillis(30)).build();
    try {
        if (chost == null) {
            // We are going to guess it.
            chost = java.net.InetAddress.getLocalHost().getHostName();
            System.out.println("Using: " + chost + ":" + cport);
        }
        modCluster.start();
        // Create the proxy and mgmt handler
        final HttpHandler proxy = modCluster.createProxyHandler();
        final MCMPConfig config = MCMPConfig.builder().setManagementHost(chost).setManagementPort(cport).enableAdvertise().setSecurityKey("secret").getParent().build();
        final MCMPConfig webConfig = MCMPConfig.webBuilder().setManagementHost(chost).setManagementPort(cport).build();
        // Setup specific rewrite rules for the mod_cluster tests.
        final HttpHandler root = Handlers.predicates(PredicatedHandlersParser.parse("regex[pattern='cluster.domain.com', value='%{i,Host}'] and equals[%R, '/'] -> rewrite['/myapp/MyCount']\n" + "regex[pattern='cluster.domain.org', value='%{i,Host}'] and regex['/(.*)'] -> rewrite['/myapp/${1}']\n" + "regex[pattern='cluster.domain.net', value='%{i,Host}'] and regex['/test/(.*)'] -> rewrite['/myapp/${1}']\n" + "regex[pattern='cluster.domain.info', value='%{i,Host}'] and path-template['/{one}/{two}'] -> rewrite['/test/${two}?partnerpath=/${one}&%q']\n", ModClusterTestSetup.class.getClassLoader()), proxy);
        final HttpHandler mcmp = config.create(modCluster, root);
        final HttpHandler web = webConfig.create(modCluster, ResponseCodeHandler.HANDLE_404);
        server = Undertow.builder().addHttpListener(cport, chost).addHttpListener(pport, phost).setHandler(Handlers.path(mcmp).addPrefixPath("/mod_cluster_manager", web)).build();
        server.start();
        // Start advertising the mcmp handler
        modCluster.advertise(config);
        final Runnable r = new Runnable() {

            @Override
            public void run() {
                modCluster.stop();
                server.stop();
            }
        };
        Runtime.getRuntime().addShutdownHook(new Thread(r));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : HttpHandler(io.undertow.server.HttpHandler) XnioWorker(org.xnio.XnioWorker) Undertow(io.undertow.Undertow) IOException(java.io.IOException)

Example 45 with Undertow

use of io.undertow.Undertow in project undertow by undertow-io.

the class AjpCharacterEncodingTestCase method setup.

@BeforeClass
public static void setup() throws Exception {
    undertow = Undertow.builder().setServerOption(UndertowOptions.URL_CHARSET, "MS949").setServerOption(UndertowOptions.ALLOW_UNESCAPED_CHARACTERS_IN_URL, true).addListener(new Undertow.ListenerBuilder().setType(Undertow.ListenerType.AJP).setHost(DefaultServer.getHostAddress()).setPort(PORT)).setHandler(new HttpHandler() {

        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            exchange.getResponseSender().send("RESULT:" + exchange.getQueryParameters().get("p").getFirst());
        }
    }).build();
    undertow.start();
    DefaultServer.setRootHandler(ProxyHandler.builder().setProxyClient(new LoadBalancingProxyClient().addHost(new URI("ajp://" + DefaultServer.getHostAddress() + ":" + PORT))).build());
    old = DefaultServer.getUndertowOptions();
    DefaultServer.setUndertowOptions(OptionMap.create(UndertowOptions.ALLOW_UNESCAPED_CHARACTERS_IN_URL, true, UndertowOptions.URL_CHARSET, "MS949"));
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) HttpHandler(io.undertow.server.HttpHandler) URI(java.net.URI) Undertow(io.undertow.Undertow) IOException(java.io.IOException) LoadBalancingProxyClient(io.undertow.server.handlers.proxy.LoadBalancingProxyClient) BeforeClass(org.junit.BeforeClass)

Aggregations

Undertow (io.undertow.Undertow)55 HttpHandler (io.undertow.server.HttpHandler)27 HttpServerExchange (io.undertow.server.HttpServerExchange)22 PathHandler (io.undertow.server.handlers.PathHandler)16 IOException (java.io.IOException)13 Test (org.junit.Test)11 ClassPathResourceManager (io.undertow.server.handlers.resource.ClassPathResourceManager)10 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)10 DeploymentManager (io.undertow.servlet.api.DeploymentManager)9 URI (java.net.URI)9 TestHttpClient (io.undertow.testutils.TestHttpClient)6 ServletException (javax.servlet.ServletException)6 HttpGet (org.apache.http.client.methods.HttpGet)6 LoadBalancingProxyClient (io.undertow.server.handlers.proxy.LoadBalancingProxyClient)5 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)5 XnioWorker (org.xnio.XnioWorker)5 PathResourceManager (io.undertow.server.handlers.resource.PathResourceManager)4 InMemorySessionManager (io.undertow.server.session.InMemorySessionManager)4 SessionAttachmentHandler (io.undertow.server.session.SessionAttachmentHandler)4 SessionCookieConfig (io.undertow.server.session.SessionCookieConfig)4