public Response serve(IHTTPSession session) {
    Map<String, String> header = session.getHeaders();
    Map<String, String> parms = session.getParms();
    String uri = session.getUri();

    if (!quiet) {
      System.out.println(session.getMethod() + " '" + uri + "' ");

      Iterator<String> e = header.keySet().iterator();
      while (e.hasNext()) {
        String value = e.next();
        System.out.println("  HDR: '" + value + "' = '" + header.get(value) + "'");
      }
      e = parms.keySet().iterator();
      while (e.hasNext()) {
        String value = e.next();
        System.out.println("  PRM: '" + value + "' = '" + parms.get(value) + "'");
      }
    }

    for (File homeDir : getRootDirs()) {
      // Make sure we won't die of an exception later
      if (!homeDir.isDirectory()) {
        return createResponse(
            Response.Status.INTERNAL_ERROR,
            NanoHTTPD.MIME_PLAINTEXT,
            "INTERNAL ERRROR: given path is not a directory (" + homeDir + ").");
      }
    }
    return respond(Collections.unmodifiableMap(header), uri);
  }
 private String findIndexFileInDirectory(java.io.File directory) {
   for (String fileName : INDEX_FILE_NAMES) {
     File indexFile = new File(directory, fileName);
     if (indexFile.exists()) {
       return fileName;
     }
   }
   return null;
 }
 private boolean canServeUri(String uri, File homeDir) {
   boolean canServeUri;
   File f = new File(homeDir, uri);
   canServeUri = f.exists();
   if (!canServeUri) {
     String mimeTypeForFile = getMimeTypeForFile(uri);
     WebServerPlugin plugin = mimeTypeHandlers.get(mimeTypeForFile);
     if (plugin != null) {
       canServeUri = plugin.canServeUri(uri, homeDir);
     }
   }
   return canServeUri;
 }
  @Override
  public void setMediaContent(
      MediaContent mediaContent,
      File mediaFile,
      java.io.File mediaFileNonVFS,
      boolean useThisThread) {
    mIsUpdate =
        (mediaContent == mMediaContent && mMediaFile != null && mMediaFile.equals(mediaFile));
    mMediaContent = mediaContent;
    mMediaFile = mediaFile;
    mUseThisThread = useThisThread;
    if (mMediaFile == null) {
      if (LOGGING) Log.v(LOGTAG, "Failed to download media, no file.");
      return;
    }

    int w = getWidth();
    int h = getHeight();
    if (w > 0 && h > 0) {
      setBitmapIfDownloaded();
    }
  }
  // we aren't really going to show any directories, just display our shared media
  private String listDirectory(String strUri, java.io.File f) {

    Uri uri = Uri.parse(strUri);

    int startIdx = 0;
    int length = 10;

    // String heading = "Directory " + uri;
    String heading = "CameraV Web Share";
    StringBuilder msg =
        new StringBuilder(
            "<html><head><title>"
                + heading
                + "</title>"
                + "<link rel=\"stylesheet\" type=\"text/css\" href=\"/style.css\"/>"
                + "</head><body><h2>"
                + heading
                + "</h2>");

    if (mListMedia != null && mListMedia.size() > 0) {

      if (mListMedia.size() > 0) {
        msg.append("<section class=\"files\">");
        for (int i = startIdx; i < (startIdx + length) && i < mListMedia.size(); i++) {

          IMedia media = mListMedia.get(i);

          String pathMedia = media._id;

          StringBuffer desc = new StringBuffer();
          desc.append("<b>").append(media.dcimEntry.fileAsset.name).append("</b><br/><br/>");
          try {
            desc.append("<pre>").append(media.buildSummary(mContext, null)).append("</pre>");

          } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }

          msg.append("<div class=\"thumbnailBorder\">");

          msg.append("<a href=\"")
              .append(encodeUri(pathMedia))
              .append("\"><img src=\"")
              .append(encodeUri(pathMedia + ".thumb"))
              .append("\"/></a><br/>");

          msg.append("<a href=\"").append(encodeUri(pathMedia)).append("\">Download Media</a>");
          msg.append(" | ");
          msg.append("<a href=\"")
              .append(encodeUri(pathMedia + ".j3m"))
              .append("\">Download J3M</a> ");
          msg.append(" | ");
          msg.append("<a href=\"")
              .append(encodeUri(pathMedia + ".csv"))
              .append("\">Download CSV</a>");
          msg.append("<br/><br/>");

          File curFile = new File(pathMedia);
          long len = curFile.length();
          msg.append("<div class=\"desc\">");
          msg.append(desc).append(" (");
          if (len < 1024) {
            msg.append(len).append(" bytes");
          } else if (len < 1024 * 1024) {
            msg.append(len / 1024).append(".").append(len % 1024 / 10 % 100).append(" KB");
          } else {
            msg.append(len / (1024 * 1024))
                .append(".")
                .append(len % (1024 * 1024) / 10 % 100)
                .append(" MB");
          }
          msg.append(")</div></div>");
        }

        msg.append("</section>");
      }
    }

    msg.append("</body></html>");
    return msg.toString();
  }
  /** Starts as a standalone file server and waits for Enter. */
  public static void main(String[] args) {
    // Defaults
    int port = 8080;

    String host = "127.0.0.1";
    List<File> rootDirs = new ArrayList<File>();
    boolean quiet = false;
    Map<String, String> options = new HashMap<String, String>();

    // Parse command-line, with short and long versions of the options.
    for (int i = 0; i < args.length; ++i) {
      if (args[i].equalsIgnoreCase("-h") || args[i].equalsIgnoreCase("--host")) {
        host = args[i + 1];
      } else if (args[i].equalsIgnoreCase("-p") || args[i].equalsIgnoreCase("--port")) {
        port = Integer.parseInt(args[i + 1]);
      } else if (args[i].equalsIgnoreCase("-q") || args[i].equalsIgnoreCase("--quiet")) {
        quiet = true;
      } else if (args[i].equalsIgnoreCase("-d") || args[i].equalsIgnoreCase("--dir")) {
        rootDirs.add(new File(args[i + 1]).getAbsoluteFile());
      } else if (args[i].equalsIgnoreCase("--licence")) {
        System.out.println(LICENCE + "\n");
      } else if (args[i].startsWith("-X:")) {
        int dot = args[i].indexOf('=');
        if (dot > 0) {
          String name = args[i].substring(0, dot);
          String value = args[i].substring(dot + 1, args[i].length());
          options.put(name, value);
        }
      }
    }

    if (rootDirs.isEmpty()) {
      rootDirs.add(new File(".").getAbsoluteFile());
    }

    options.put("host", host);
    options.put("port", "" + port);
    options.put("quiet", String.valueOf(quiet));
    StringBuilder sb = new StringBuilder();
    for (File dir : rootDirs) {
      if (sb.length() > 0) {
        sb.append(":");
      }
      try {
        sb.append(dir.getCanonicalPath());
      } catch (IOException ignored) {
      }
    }
    options.put("home", sb.toString());

    ServiceLoader<WebServerPluginInfo> serviceLoader =
        ServiceLoader.load(WebServerPluginInfo.class);
    for (WebServerPluginInfo info : serviceLoader) {
      String[] mimeTypes = info.getMimeTypes();
      for (String mime : mimeTypes) {
        String[] indexFiles = info.getIndexFilesForMimeType(mime);
        if (!quiet) {
          System.out.print("# Found plugin for Mime type: \"" + mime + "\"");
          if (indexFiles != null) {
            System.out.print(" (serving index files: ");
            for (String indexFile : indexFiles) {
              System.out.print(indexFile + " ");
            }
          }
          System.out.println(").");
        }
        registerPluginForMimeType(indexFiles, mime, info.getWebServerPlugin(mime), options);
      }
    }

    ServerRunner.executeInstance(new SimpleWebServer(host, port, rootDirs, quiet));
  }