Search in sources :

Example 1 with WebApplicationContext

use of cn.taketoday.web.WebApplicationContext in project today-infrastructure by TAKETODAY.

the class CorsFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    RequestContext context = RequestContextHolder.get();
    if (context == null) {
        WebApplicationContext webApplicationContext = ServletUtils.findWebApplicationContext(request);
        context = new ServletRequestContext(webApplicationContext, request, response);
        RequestContextHolder.set(context);
    }
    try {
        CorsConfiguration corsConfiguration = this.configSource.getCorsConfiguration(context);
        if (!processor.process(corsConfiguration, context) || CorsUtils.isPreFlightRequest(context)) {
            return;
        }
        // handle next
        filterChain.doFilter(request, response);
    } finally {
        RequestContextHolder.remove();
    }
}
Also used : CorsConfiguration(cn.taketoday.web.cors.CorsConfiguration) ServletRequestContext(cn.taketoday.web.servlet.ServletRequestContext) RequestContext(cn.taketoday.web.RequestContext) ServletRequestContext(cn.taketoday.web.servlet.ServletRequestContext) WebApplicationContext(cn.taketoday.web.WebApplicationContext)

Example 2 with WebApplicationContext

use of cn.taketoday.web.WebApplicationContext in project today-infrastructure by TAKETODAY.

the class RootWacEarTests method verifyRootWacConfig.

@Test
void verifyRootWacConfig() {
    ApplicationContext parent = wac.getParent();
    assertThat(parent).isNotNull();
    boolean condition = parent instanceof WebApplicationContext;
    assertThat(condition).isFalse();
    assertThat(ear).isEqualTo("ear");
    assertThat(root).isEqualTo("root");
}
Also used : WebApplicationContext(cn.taketoday.web.WebApplicationContext) ApplicationContext(cn.taketoday.context.ApplicationContext) WebApplicationContext(cn.taketoday.web.WebApplicationContext) Test(org.junit.jupiter.api.Test)

Example 3 with WebApplicationContext

use of cn.taketoday.web.WebApplicationContext in project today-framework by TAKETODAY.

the class HTTPServer method handleConnection.

/**
 * Handles communications for a single connection over the given streams.
 * Multiple subsequent transactions are handled on the connection,
 * until the streams are closed, an error occurs, or the request
 * contains a "Connection: close" header which explicitly requests
 * the connection be closed after the transaction ends.
 *
 * @throws IOException if an error occurs
 */
protected void handleConnection(Socket socket) throws IOException {
    // BufferedInputStream in = new BufferedInputStream(socket.getInputStream(), 4096);
    final ByteArrayOutputStream inString = new ByteArrayOutputStream();
    BufferedInputStream in = new BufferedInputStream(socket.getInputStream(), 4096) {

        @Override
        public synchronized int read() throws IOException {
            final int read = super.read();
            inString.write(read);
            return read;
        }

        @Override
        public synchronized int read(@NonNull byte[] b, int off, int len) throws IOException {
            final int read = super.read(b, off, len);
            inString.write(b, off, len);
            return read;
        }
    };
    final OutputStream socketOutputStream = socket.getOutputStream();
    BufferedOutputStream out = new BufferedOutputStream(socketOutputStream, 4096);
    // final ByteArrayOutputStream out = new ByteArrayOutputStream() {
    // @Override
    // public synchronized void write(byte[] b, int off, int len) {
    // super.write(b, off, len);
    // try {
    // socketOutputStream.write(b, off, len);
    // }
    // catch (IOException e) {
    // e.printStackTrace();
    // }
    // }
    // };
    HttpRequest req = null;
    HttpResponse resp = new HttpResponse(out);
    InetAddress localAddress = socket.getLocalAddress();
    // create request and response and handle transaction
    try {
        req = new HttpRequest(in, socket, config);
        resp.setClientCapabilities(req);
        if (preprocessTransaction(req, resp)) {
            String method = req.getMethod();
            if ("TRACE".equals(method)) {
                // default TRACE handler
                handleTrace(req, resp);
            } else {
                WebApplicationContext webApplicationContext = httpHandler.getWebApplicationContext();
                final LightRequestContext context = new LightRequestContext(webApplicationContext, req, resp, config, localAddress);
                httpHandler.dispatch(context);
                context.sendIfNotCommitted();
            }
        }
    } catch (Throwable t) {
        log.error("Catch throwable", t);
        // unhandled errors (not normal error responses like 404)
        if (req == null) {
            // error reading request
            if (t instanceof IOException && t.getMessage().contains("missing request line"))
                // we're not in the middle of a transaction - so just disconnect
                return;
            // about to close connection
            resp.getHeaders().add("Connection", "close");
            if (// e.g. SocketTimeoutException
            t instanceof InterruptedIOException)
                resp.sendError(HttpStatus.REQUEST_TIMEOUT, "Timeout waiting for client request");
            else
                resp.sendError(HttpStatus.BAD_REQUEST, "Invalid request: " + t.getMessage());
        } else if (!resp.committed()) {
            // if headers or status line were not already sent, we can send an error response
            // ignore whatever headers may have already been set
            resp = new HttpResponse(out);
            // about to close connection
            resp.getHeaders().add("Connection", "close");
            resp.sendError(HttpStatus.INTERNAL_SERVER_ERROR, "Error processing request: " + t.getMessage());
        }
        // proceed to close connection
        return;
    } finally {
        // System.out.println(out);
        // final String name = StandardCharsets.ISO_8859_1.name();
        // System.out.println(inString.toString(name));
        System.out.println(inString);
        // close response and flush output
        resp.close();
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) WebApplicationContext(cn.taketoday.web.WebApplicationContext) BufferedInputStream(java.io.BufferedInputStream) NonNull(cn.taketoday.lang.NonNull) BufferedOutputStream(java.io.BufferedOutputStream) InetAddress(java.net.InetAddress)

Example 4 with WebApplicationContext

use of cn.taketoday.web.WebApplicationContext in project today-framework by TAKETODAY.

the class WebApplicationLoader method configureHandlerAdapter.

/**
 * Configure {@link HandlerAdapter}
 *
 * @param adapters {@link HandlerAdapter}s
 * @param mvcConfiguration {@link WebMvcConfiguration}
 */
protected void configureHandlerAdapter(List<HandlerAdapter> adapters, WebMvcConfiguration mvcConfiguration) {
    // 先看有的
    DispatcherHandler obtainDispatcher = obtainDispatcher();
    HandlerAdapter[] handlerAdapters = obtainDispatcher.getHandlerAdapters();
    if (handlerAdapters != null) {
        Collections.addAll(adapters, handlerAdapters);
    }
    // 添加默认的
    adapters.add(new RequestHandlerAdapter(Ordered.HIGHEST_PRECEDENCE));
    WebApplicationContext context = obtainApplicationContext();
    // ViewControllerHandlerRegistry must configured
    ViewControllerHandlerRegistry viewControllerRegistry = context.getBean(ViewControllerHandlerRegistry.class);
    if (viewControllerRegistry != null) {
        ViewControllerHandlerAdapter bean = context.getBean(ViewControllerHandlerAdapter.class);
        if (bean == null) {
            ViewControllerHandlerAdapter viewControllerHandlerAdapter = null;
            for (HandlerAdapter adapter : adapters) {
                if (adapter instanceof ViewControllerHandlerAdapter) {
                    viewControllerHandlerAdapter = (ViewControllerHandlerAdapter) adapter;
                    break;
                }
            }
            if (viewControllerHandlerAdapter == null) {
                adapters.add(new ViewControllerHandlerAdapter(Ordered.HIGHEST_PRECEDENCE));
            }
        }
    }
    // 排序
    sort(adapters);
    // apply request handler
    obtainDispatcher.setHandlerAdapters(adapters.toArray(new HandlerAdapter[adapters.size()]));
}
Also used : DispatcherHandler(cn.taketoday.web.handler.DispatcherHandler) ViewControllerHandlerAdapter(cn.taketoday.web.handler.ViewControllerHandlerAdapter) RequestHandlerAdapter(cn.taketoday.web.handler.RequestHandlerAdapter) HandlerAdapter(cn.taketoday.web.handler.HandlerAdapter) ViewControllerHandlerRegistry(cn.taketoday.web.registry.ViewControllerHandlerRegistry) RequestHandlerAdapter(cn.taketoday.web.handler.RequestHandlerAdapter) WebApplicationContext(cn.taketoday.web.WebApplicationContext) ViewControllerHandlerAdapter(cn.taketoday.web.handler.ViewControllerHandlerAdapter)

Example 5 with WebApplicationContext

use of cn.taketoday.web.WebApplicationContext in project today-framework by TAKETODAY.

the class WebApplicationLoader method configViewControllerHandlerRegistry.

/**
 * Initialize framework.
 *
 * @throws Throwable if any Throwable occurred
 */
protected ViewControllerHandlerRegistry configViewControllerHandlerRegistry(@Nullable ViewControllerHandlerRegistry registry) throws Throwable {
    // find the configure file
    log.info("TODAY WEB Framework Is Looking For ViewController Configuration File.");
    String webMvcConfigLocation = getWebMvcConfigLocation();
    if (StringUtils.isEmpty(webMvcConfigLocation)) {
        log.info("Configuration File does not exist.");
        return registry;
    }
    if (registry == null) {
        WebApplicationContext context = obtainApplicationContext();
        context.unwrap(BeanDefinitionRegistrar.class).registerBean(ViewControllerHandlerRegistry.DEFAULT_BEAN_NAME, ViewControllerHandlerRegistry.class);
        registry = context.getBean(ViewControllerHandlerRegistry.DEFAULT_BEAN_NAME, ViewControllerHandlerRegistry.class);
    }
    registry.configure(webMvcConfigLocation);
    return registry;
}
Also used : ViewControllerHandlerRegistry(cn.taketoday.web.registry.ViewControllerHandlerRegistry) BeanDefinitionRegistrar(cn.taketoday.context.loader.BeanDefinitionRegistrar) WebApplicationContext(cn.taketoday.web.WebApplicationContext)

Aggregations

WebApplicationContext (cn.taketoday.web.WebApplicationContext)15 ApplicationContext (cn.taketoday.context.ApplicationContext)4 Test (org.junit.jupiter.api.Test)4 DispatcherHandler (cn.taketoday.web.handler.DispatcherHandler)3 BeanDefinitionRegistrar (cn.taketoday.context.loader.BeanDefinitionRegistrar)2 ContextExposingRequestContext (cn.taketoday.web.ContextExposingRequestContext)2 RequestContext (cn.taketoday.web.RequestContext)2 CorsConfiguration (cn.taketoday.web.cors.CorsConfiguration)2 ViewControllerHandlerRegistry (cn.taketoday.web.registry.ViewControllerHandlerRegistry)2 ServletRequestContext (cn.taketoday.web.servlet.ServletRequestContext)2 WebServletApplicationContext (cn.taketoday.web.servlet.WebServletApplicationContext)2 ServletContext (jakarta.servlet.ServletContext)2 AnnotationConfigServletWebApplicationContext (cn.taketoday.framework.web.servlet.context.AnnotationConfigServletWebApplicationContext)1 NonNull (cn.taketoday.lang.NonNull)1 ParameterResolvingRegistry (cn.taketoday.web.bind.resolver.ParameterResolvingRegistry)1 HandlerAdapter (cn.taketoday.web.handler.HandlerAdapter)1 RequestHandlerAdapter (cn.taketoday.web.handler.RequestHandlerAdapter)1 ReturnValueHandlerManager (cn.taketoday.web.handler.ReturnValueHandlerManager)1 SelectableReturnValueHandler (cn.taketoday.web.handler.SelectableReturnValueHandler)1 ViewControllerHandlerAdapter (cn.taketoday.web.handler.ViewControllerHandlerAdapter)1