コード例 #1
0
  private void streamResponse(Response resp, ResponseParams rp) throws IOException {
    OutputStream body = null;
    try {
      if (rp.staticFile) {
        String fileName = rp.message;

        body = resp.getOutputStream();

        byte[] buffer = new byte[32 * 1024];
        InputStream input = configReader.getStaticFile(fileName);
        int bytesRead;
        while ((bytesRead = input.read(buffer, 0, buffer.length)) > 0) {
          body.write(buffer, 0, bytesRead);
        }

      } else {
        body = resp.getPrintStream();
        if (body != null) {
          ((PrintStream) body).print(rp.message);
        }
      }
    } finally {
      if (body != null) {
        try {
          body.close();
        } catch (IOException e) {
          LOGGER.log(Level.SEVERE, "Exception on MockServer close", e);
        }
      }
    }
  }
コード例 #2
0
 public void handle(Request request, Response response) {
   String targetClean = request.getTarget().toLowerCase();
   if (targetClean.indexOf('?') >= 0) {
     targetClean = targetClean.substring(0, targetClean.indexOf('?'));
   }
   if (targetClean.startsWith("/")) {
     targetClean = targetClean.substring(1);
   }
   if (targetClean.endsWith("/")) {
     targetClean = targetClean.substring(0, targetClean.length() - 1);
   }
   Container obj;
   try {
     obj = containers.get(URLDecoder.decode(targetClean.trim(), "UTF-8").toLowerCase());
     if (obj == null) {
       String tmp = targetClean;
       while (tmp.contains("/") && obj == null) {
         tmp = tmp.substring(0, tmp.lastIndexOf('/'));
         obj = containers.get(URLDecoder.decode(tmp.trim(), "UTF-8").toLowerCase() + "/*");
       }
       if (obj != null) {
         targetClean = tmp;
       }
     }
     System.out.println(
         "Request: "
             + request.getTarget()
             + " ("
             + URLDecoder.decode(targetClean.trim(), "UTF-8").toLowerCase()
             + ") -> "
             + (obj != null ? obj.getClass().getSimpleName() : "null"));
     if (obj != null) {
       obj.handle(request, response);
       return;
     } else {
       try {
         PrintStream body = response.getPrintStream();
         response.setCode(404);
         body.println(
             "Not found: " + URLDecoder.decode(targetClean.trim(), "UTF-8").toLowerCase());
       } catch (Exception e2) {
       }
     }
   } catch (Exception e) {
     try {
       PrintStream body = response.getPrintStream();
       response.setCode(503);
       e.printStackTrace(body);
     } catch (Exception e2) {
     }
   }
   try {
     response.getPrintStream().close();
   } catch (Exception e) {
   }
 }
コード例 #3
0
  @Override
  public void handle(Request request, Response response, SubscribeRequest message)
      throws Exception {
    String key = message.getKey();
    StatusResponse status = new StatusResponse(key, true);
    manager.subscribe(message);
    String content = gson.toJson(status);
    OutputStream output = response.getOutputStream();
    byte[] data = content.getBytes("UTF-8");

    response.setContentType("text/json");
    response.setContentLength(data.length);
    output.write(data);
    output.flush();
    response.close();
  }
コード例 #4
0
    public void handle(Request request, Response response) {
      try {
        PrintStream body = response.getPrintStream();
        long time = System.currentTimeMillis();

        Thread.sleep(responseDelay);

        response.setValue("Content-Type", "text/plain");
        response.setValue("Server", "StubHttpServer/1.0 (Simple 4.0)");
        response.setDate("Date", time);
        response.setDate("Last-Modified", time);

        body.println(responseText);
        body.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
コード例 #5
0
  /**
   * handle a http request and serve a file
   *
   * @param request the http request
   * @param response the http response
   */
  @Override
  public void handle(Request request, Response response) {
    try {
      PrintStream body = response.getPrintStream();
      long time = System.currentTimeMillis();
      String msg = "";
      String home = System.getProperty("user.dir");
      String contentType = "text/plain";
      Path path = request.getPath();
      if (path.getPath().substring(path.getPath().length() - 3).equals(".js"))
        contentType = "application/javascript";
      if (path.getPath().substring(path.getPath().length() - 3).equals("css"))
        contentType = "text/css";

      response.set("Content-Type", contentType);
      response.set("Server", "ServerLyzer/1.0 (Simple 4.0)");
      response.setDate("Date", time);
      response.setDate("Last-Modified", time);
      String filename = wwwroot + path.getPath();

      String content;
      if (ServerLyzer.wwwroot == null) {
        content = new Scanner(new File(filename)).useDelimiter("\\Z").next();
        /*
        * UPdated because the code below gives :/home/pehlivanz/workspace/Pagelyzer/target/Pagelyzer-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/js/bomlib.js
        * for the jars
         URL resourceUrl = getClass().getResource(filename);
         content = new Scanner(new File(resourceUrl.toURI().getPath().toString())).useDelimiter("\\Z").next();
         */
      } else {
        content = new Scanner(new File(filename)).useDelimiter("\\Z").next();
      }
      body.print(content);

      body.println(msg);
      body.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #6
0
 private void setResponseFields(Response resp, ResponseParams rp) {
   final long time = System.currentTimeMillis();
   String contentType = getContentType(rp.staticFile, rp.message);
   resp.setContentType(contentType);
   resp.setValue("Server", "Mock");
   resp.setDate("Date", time);
   resp.setDate("Last-Modified", time);
   resp.setCode(rp.responseCode);
   for (Map.Entry<String, String> header : rp.headers.entrySet()) {
     resp.setValue(header.getKey(), header.getValue());
   }
 }
コード例 #7
0
  @Override
  public void handle(Request req, Response resp) {
    try {
      PrintStream body = resp.getPrintStream();
      try {
        long time = System.currentTimeMillis();

        resp.setValue("Content-Type", "application/javascript");
        resp.setValue("Server", "HelloWorld/1.0 (Simple 4.0)");
        resp.setDate("Date", time);
        resp.setDate("Last-Modified", time);

        generateJavascript(req, resp, body);
      } finally {
        body.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
      resp.setStatus(Status.INTERNAL_SERVER_ERROR);
      return;
    }
  }
コード例 #8
0
  @Override
  public void handle(Request req, Response res) {
    try {
      Path p = req.getPath();
      Query qry = req.getQuery();
      PrintStream ps = res.getPrintStream();
      long time = System.currentTimeMillis();
      String service;

      if (p.getSegments().length >= 1) {
        service = p.getSegments()[0];
      } else {
        service = "";
      }

      res.setValue("Content-Type", "text/html");
      res.setValue("Server", "SLPeripherals/1.0 (Simple 4.0)");
      res.setDate("Date", time);
      res.setDate("Last-Modified", time);

      // System.out.println("request" + url);

      try {
        if (Integer.valueOf(service) != null) {
          int i = Integer.valueOf(service);

          if (services.get(i) != null) {
            // put an event and wait for response

            IComputerAccess ica = (IComputerAccess) ((Object[]) services.get(i))[0];
            TileEntityHTTPD hd = (TileEntityHTTPD) ((Object[]) services.get(i))[1];

            hd.reqsw.add(ps);
            int idx = hd.reqsw.lastIndexOf(ps);

            // reqs.add("{bl}");
            // int idx=reqs.lastIndexOf("{bl}");

            Map<String, String> cookies = new HashMap<String, String>();

            for (Cookie c : res.getCookies()) {
              cookies.put(c.getName(), c.getValue());
            }

            ica.queueEvent("http_server_request", new Object[] {idx, p.getPath(1), qry, cookies});

            return;

            /*
             *
             * for (int ij = 1; ij <= 10; ij++) { Thread.sleep(100);
             *
             * if (! reqs.get(idx).equals("{bl}")) { // request
             * done. ps.print(reqs.get(idx)); ps.close(); return; }
             *
             * }
             *
             * // request timed out
             *
             * reqs.remove(idx);
             *
             *
             *
             * ps.print(
             * "<hr>The computer did not respond after 1 second, request timed out."
             * ); ps.close(); return;
             */

          } else {
            ps.print(
                "SLP HTTP Server (based on the Simple Framework)<br>"
                    + "The service "
                    + i
                    + " is not online.");
          }
        }
      } catch (Exception e) {
        ps.print(
            "SLP HTTP Server (based on the Simple Framework)<br>"
                + "Please go to a service by typing the computer id then a slash, example:<br>"
                + "http://localhost/4/<br>"
                + "would go to Computer ID 4's service. - The IDs are assigned by ComputerCraft.<br>"
                + "(please note 'localhost' depends on your setup. You may have to use a port number too. See the current URL.).<br>(exception encountered)");
      }

      ps.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }