Tabnine Logo
HttpStaticFileServerHandler
Code IndexAdd Tabnine to your IDE (free)

How to use
HttpStaticFileServerHandler
in
org.atmosphere.nettosphere

Best Java code snippets using org.atmosphere.nettosphere.HttpStaticFileServerHandler (Showing top 14 results out of 315)

origin: Atmosphere/nettosphere

@Override
public void sendError(ChannelHandlerContext ctx, HttpResponseStatus status, FullHttpRequest e) {
  // For websocket, we can't send an error
  logger.trace("Error {} for {}", status, e);
  if (websocketChannels.contains(ctx.channel())) {
    logger.debug("Error {} for {}", status, e);
    ctx.channel().close().addListener(ChannelFutureListener.CLOSE);
  } else if (e != null) {
    if (HttpHeaders.getHeader(e, STATIC_MAPPING, "false").equalsIgnoreCase("false")) {
      super.sendError(ctx, status, e);
    }
  } else {
    super.sendError(ctx, status, e);
  }
}
origin: Atmosphere/nettosphere

/**
 * When file timestamp is the same as what the browser is sending up, send a "304 Not Modified"
 *
 * @param ctx
 *            Context
 */
private static void sendNotModified(ChannelHandlerContext ctx) {
  FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_MODIFIED);
  setDateHeader(response);
  // Close the connection as soon as the error message is sent.
  ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
origin: Atmosphere/nettosphere

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
  if (!request.decoderResult().isSuccess()) {
    sendError(ctx, BAD_REQUEST, request);
    return;
    sendError(ctx, METHOD_NOT_ALLOWED, request);
    return;
  boolean found = true;
  for (String p : paths) {
    String path = p + sanitizeUri(request.getUri());
      break;
    } catch (FileNotFoundException ignore) {
      sendError(ctx, NOT_FOUND, request);
      return;
    sendError(ctx, NOT_FOUND, request);
    return;
    long fileLastModifiedSeconds = file.lastModified() / 1000;
    if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
      sendNotModified(ctx);
      return;
  contentType(request, response, file);
  setDateAndCacheHeaders(response, file);
origin: Atmosphere/nettosphere

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
  super.channelInactive(ctx);
  Object o = ctx.attr(ATTACHMENT).get();
  if (o == null) return;
  if (WebSocket.class.isAssignableFrom(o.getClass())) {
    NettyWebSocket webSocket = NettyWebSocket.class.cast(o);
    logger.trace("Closing {}", webSocket.uuid());
    try {
      if (webSocket.closeFuture() != null) {
        webSocket.closeFuture().cancel(true);
      }
      webSocketProcessor.close(webSocket, 1005);
    } catch (Exception ex) {
      logger.error("{}", webSocket, ex);
    }
  } else if (State.class.isAssignableFrom(o.getClass())) {
    logger.trace("State {}", o);
    State s = State.class.cast(o);
    if (s.action.type() == Action.TYPE.SUSPEND) {
      asynchronousProcessor.endRequest(s.resource(), true);
    }
  } else {
    logger.warn("Invalid state {} and Channel {}", o, ctx.channel());
  }
}
origin: Atmosphere/nettosphere

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e){
  if (config.ioExceptionHandler().of(ctx, e)) {
    try {
      if (e instanceof IOException) {
        logger.trace("Connection closed Exception", e);
      } else if (e.getCause() != null
          && (e.getCause().getClass().equals(ClosedChannelException.class)
          || e.getCause().getClass().equals(IOException.class))) {
        logger.trace("Unexpected I/O Exception", e.getCause());
      } else if (e.getCause() != null && e.getCause().getClass().equals(TooLongFrameException.class)) {
        logger.error("TooLongFrameException. The request will be closed, make sure you increase the Config.maxChunkContentLength() to a higher value.", e.getCause());
        super.exceptionCaught(ctx, e);
      } else {
        logger.error("Unexpected and unhandled I/O Exception", e);
        super.exceptionCaught(ctx, e);
      }
    } finally {
      try {
        ctx.channel().close();
      } catch (Exception ex) {
        logger.trace("", ex);
      }
    }
  }
}
origin: Atmosphere/nettosphere

try {
  hrequest.headers().add(STATIC_MAPPING, "true");
  super.channelRead0(ctx, (FullHttpRequest) messageEvent);
origin: org.atmosphere/nettosphere

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
  if (!request.decoderResult().isSuccess()) {
    sendError(ctx, BAD_REQUEST, request);
    return;
    sendError(ctx, METHOD_NOT_ALLOWED, request);
    return;
  boolean found = true;
  for (String p : paths) {
    String path = p + sanitizeUri(request.getUri());
      break;
    } catch (FileNotFoundException ignore) {
      sendError(ctx, NOT_FOUND, request);
      return;
    sendError(ctx, NOT_FOUND, request);
    return;
    long fileLastModifiedSeconds = file.lastModified() / 1000;
    if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
      sendNotModified(ctx);
      return;
  contentType(request, response, file);
  setDateAndCacheHeaders(response, file);
origin: org.atmosphere/nettosphere

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
  super.channelInactive(ctx);
  Object o = ctx.attr(ATTACHMENT).get();
  if (o == null) return;
  if (WebSocket.class.isAssignableFrom(o.getClass())) {
    NettyWebSocket webSocket = NettyWebSocket.class.cast(o);
    logger.trace("Closing {}", webSocket.uuid());
    try {
      if (webSocket.closeFuture() != null) {
        webSocket.closeFuture().cancel(true);
      }
      webSocketProcessor.close(webSocket, 1005);
    } catch (Exception ex) {
      logger.error("{}", webSocket, ex);
    }
  } else if (State.class.isAssignableFrom(o.getClass())) {
    logger.trace("State {}", o);
    State s = State.class.cast(o);
    if (s.action.type() == Action.TYPE.SUSPEND) {
      asynchronousProcessor.endRequest(s.resource(), true);
    }
  } else {
    logger.warn("Invalid state {} and Channel {}", o, ctx.channel());
  }
}
origin: org.atmosphere/nettosphere

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e){
  if (config.ioExceptionHandler().of(ctx, e)) {
    try {
      if (e instanceof IOException) {
        logger.trace("Connection closed Exception", e);
      } else if (e.getCause() != null
          && (e.getCause().getClass().equals(ClosedChannelException.class)
          || e.getCause().getClass().equals(IOException.class))) {
        logger.trace("Unexpected I/O Exception", e.getCause());
      } else if (e.getCause() != null && e.getCause().getClass().equals(TooLongFrameException.class)) {
        logger.error("TooLongFrameException. The request will be closed, make sure you increase the Config.maxChunkContentLength() to a higher value.", e.getCause());
        super.exceptionCaught(ctx, e);
      } else {
        logger.error("Unexpected and unhandled I/O Exception", e);
        super.exceptionCaught(ctx, e);
      }
    } finally {
      try {
        ctx.channel().close();
      } catch (Exception ex) {
        logger.trace("", ex);
      }
    }
  }
}
origin: org.atmosphere/nettosphere

try {
  hrequest.headers().add(STATIC_MAPPING, "true");
  super.channelRead0(ctx, (FullHttpRequest) messageEvent);
origin: Atmosphere/nettosphere

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) {
  Channel ch = ctx.channel();
  // Prevent recursion when the client close the connection during a write operation. In that
  // scenario the sendError will be invoked, but will fail since the channel has already been closed
  // For an unknown reason,
  if (ch.attr(ATTACHMENT) != null && Error.class.isAssignableFrom(ch.attr(ATTACHMENT).get().getClass())) {
    return;
  }
  Throwable cause = t.getCause();
  if (cause instanceof TooLongFrameException) {
    sendError(ctx, BAD_REQUEST, null);
    return;
  }
  ch.attr(ATTACHMENT).set(new Error());
  if (ch.isOpen()) {
    sendError(ctx, INTERNAL_SERVER_ERROR, null);
  }
  if (ctx.channel().isActive()) {
    sendError(ctx, INTERNAL_SERVER_ERROR, null);
  }
}
origin: org.atmosphere/nettosphere

/**
 * When file timestamp is the same as what the browser is sending up, send a "304 Not Modified"
 *
 * @param ctx
 *            Context
 */
private static void sendNotModified(ChannelHandlerContext ctx) {
  FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_MODIFIED);
  setDateHeader(response);
  // Close the connection as soon as the error message is sent.
  ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
origin: org.atmosphere/nettosphere

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) {
  Channel ch = ctx.channel();
  // Prevent recursion when the client close the connection during a write operation. In that
  // scenario the sendError will be invoked, but will fail since the channel has already been closed
  // For an unknown reason,
  if (ch.attr(ATTACHMENT) != null && Error.class.isAssignableFrom(ch.attr(ATTACHMENT).get().getClass())) {
    return;
  }
  Throwable cause = t.getCause();
  if (cause instanceof TooLongFrameException) {
    sendError(ctx, BAD_REQUEST, null);
    return;
  }
  ch.attr(ATTACHMENT).set(new Error());
  if (ch.isOpen()) {
    sendError(ctx, INTERNAL_SERVER_ERROR, null);
  }
  if (ctx.channel().isActive()) {
    sendError(ctx, INTERNAL_SERVER_ERROR, null);
  }
}
origin: org.atmosphere/nettosphere

@Override
public void sendError(ChannelHandlerContext ctx, HttpResponseStatus status, FullHttpRequest e) {
  // For websocket, we can't send an error
  logger.trace("Error {} for {}", status, e);
  if (websocketChannels.contains(ctx.channel())) {
    logger.debug("Error {} for {}", status, e);
    ctx.channel().close().addListener(ChannelFutureListener.CLOSE);
  } else if (e != null) {
    if (HttpHeaders.getHeader(e, STATIC_MAPPING, "false").equalsIgnoreCase("false")) {
      super.sendError(ctx, status, e);
    }
  } else {
    super.sendError(ctx, status, e);
  }
}
org.atmosphere.nettosphereHttpStaticFileServerHandler

Javadoc

A simple handler that serves incoming HTTP requests to send their respective HTTP responses. It also implements 'If-Modified-Since' header to take advantage of browser cache, as described in RFC 2616.

How Browser Caching Works

Web browser caching works with HTTP headers as illustrated by the following sample:

  1. Request #1 returns the content of /file1.txt.
  2. Contents of /file1.txt is cached by the browser.
  3. Request #2 for /file1.txt does return the contents of the file again. Rather, a 304 Not Modified is returned. This tells the browser to use the contents stored in its cache.
  4. The server knows the file has not been modified because the If-Modified-Since date is the same as the file's last modified date.

 
Request #1 Headers 
=================== 
GET /file1.txt HTTP/1.1 
Response #1 Headers 
=================== 
HTTP/1.1 200 OK 
Date:               Tue, 01 Mar 2011 22:44:26 GMT 
Last-Modified:      Wed, 30 Jun 2010 21:36:48 GMT 
Expires:            Tue, 01 Mar 2012 22:44:26 GMT 
Cache-Control:      private, max-age=31536000 
Request #2 Headers 
=================== 
GET /file1.txt HTTP/1.1 
If-Modified-Since:  Wed, 30 Jun 2010 21:36:48 GMT 
Response #2 Headers 
=================== 
HTTP/1.1 304 Not Modified 
Date:               Tue, 01 Mar 2011 22:44:28 GMT 

Most used methods

  • channelInactive
  • channelRead0
  • contentType
  • exceptionCaught
  • sanitizeUri
  • sendError
  • sendNotModified
    When file timestamp is the same as what the browser is sending up, send a "304 Not Modified"
  • setDateAndCacheHeaders
    Sets the Date and Cache headers for the HTTP Response
  • setDateHeader
    Sets the Date header for the HTTP response

Popular in Java

  • Reading from database using SQL prepared statement
  • notifyDataSetChanged (ArrayAdapter)
  • orElseThrow (Optional)
    Return the contained value, if present, otherwise throw an exception to be created by the provided s
  • findViewById (Activity)
  • SQLException (java.sql)
    An exception that indicates a failed JDBC operation. It provides the following information about pro
  • StringTokenizer (java.util)
    Breaks a string into tokens; new code should probably use String#split.> // Legacy code: StringTo
  • Callable (java.util.concurrent)
    A task that returns a result and may throw an exception. Implementors define a single method with no
  • Annotation (javassist.bytecode.annotation)
    The annotation structure.An instance of this class is returned bygetAnnotations() in AnnotationsAttr
  • IOUtils (org.apache.commons.io)
    General IO stream manipulation utilities. This class provides static utility methods for input/outpu
  • IsNull (org.hamcrest.core)
    Is the value null?
  • Github Copilot alternatives
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now