Package com.davfx.ninio.http.util

Source Code of com.davfx.ninio.http.util.DirectoryHttpServerHandler

package com.davfx.ninio.http.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

import com.davfx.ninio.http.Http;
import com.davfx.ninio.http.HttpRequest;
import com.davfx.ninio.http.HttpResponse;
import com.davfx.ninio.http.HttpServerHandler;

public final class DirectoryHttpServerHandler implements HttpServerHandler {
  private final File dir;
  private HttpRequest request;
 
  public DirectoryHttpServerHandler(File dir) {
    this.dir = dir;
  }
 
  @Override
  public void closed() {
  }
  @Override
  public void failed(IOException e) {
  }
  @Override
  public void handle(ByteBuffer buffer) {
  }
  @Override
  public void handle(HttpRequest request) {
    this.request = request;
  }
  @Override
  public void ready(Write write) {
    try {
      File d = new File(dir.getCanonicalPath() + request.getPath());
      if (d.isDirectory()) {
        StringBuilder b = new StringBuilder();
        b.append("<!doctype html>");
        b.append("<html>");
        b.append("<head>");
        b.append("<meta charset=\"utf-8\">");
        b.append("</head>");
        b.append("<body>");

        File[] files = d.listFiles();
        if (files != null) {
          b.append("<ul>");
          for (File f : files) {
            b.append("<li>");
            b.append("<a href=\"").append(request.getPath() + "/" + f.getName()).append("\">");
            b.append(f.getName());
            b.append("</a>");
            b.append("</li>");
          }
          b.append("</ul>");
        }

        b.append("</body>");
        b.append("</html>");
        write.write(new HttpResponse(Http.Status.OK, Http.Message.OK));
        write.write(ByteBuffer.wrap(b.toString().getBytes(Http.UTF8_CHARSET)));
        write.finish();
      } else {
        write.write(new HttpResponse(Http.Status.OK, Http.Message.OK));
        try (InputStream in = new FileInputStream(d)) {
          byte[] b = new byte[10 * 1024];
          while (true) {
            int l = in.read(b);
            if (l < 0) {
              break;
            }
            write.write(ByteBuffer.wrap(b, 0, l));
          }
        }
        write.finish();
      }
    } catch (IOException ioe) {
      write.write(new HttpResponse(Http.Status.INTERNAL_SERVER_ERROR, Http.Message.INTERNAL_SERVER_ERROR));
      write.finish();
    }
  }
}
TOP

Related Classes of com.davfx.ninio.http.util.DirectoryHttpServerHandler

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.