View Javadoc
1   /*
2    * Copyright 2014 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  
17  package io.netty5.example.file;
18  
19  import io.netty5.channel.ChannelFutureListeners;
20  import io.netty5.channel.ChannelHandlerContext;
21  import io.netty5.channel.DefaultFileRegion;
22  import io.netty5.channel.SimpleChannelInboundHandler;
23  import io.netty5.handler.ssl.SslHandler;
24  import io.netty5.handler.stream.ChunkedFile;
25  
26  import java.io.RandomAccessFile;
27  
28  public class FileServerHandler extends SimpleChannelInboundHandler<String> {
29  
30      @Override
31      public void channelActive(ChannelHandlerContext ctx) {
32          ctx.writeAndFlush("HELLO: Type the path of the file to retrieve.\n");
33      }
34  
35      @Override
36      public void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
37          RandomAccessFile raf = null;
38          long length = -1;
39          try {
40              raf = new RandomAccessFile(msg, "r");
41              length = raf.length();
42          } catch (Exception e) {
43              ctx.writeAndFlush("ERR: " + e.getClass().getSimpleName() + ": " + e.getMessage() + '\n');
44              return;
45          } finally {
46              if (length < 0 && raf != null) {
47                  raf.close();
48              }
49          }
50  
51          ctx.write("OK: " + raf.length() + '\n');
52          if (ctx.pipeline().get(SslHandler.class) == null) {
53              // SSL not enabled - can use zero-copy file transfer.
54              ctx.write(new DefaultFileRegion(raf.getChannel(), 0, length));
55          } else {
56              // SSL enabled - cannot use zero-copy file transfer.
57              ctx.write(new ChunkedFile(raf));
58          }
59          ctx.writeAndFlush("\n");
60      }
61  
62      @Override
63      public void channelExceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
64          cause.printStackTrace();
65  
66          if (ctx.channel().isActive()) {
67              ctx.writeAndFlush("ERR: " +
68                      cause.getClass().getSimpleName() + ": " +
69                      cause.getMessage() + '\n')
70                 .addListener(ctx, ChannelFutureListeners.CLOSE);
71          }
72      }
73  }
74