/**
  * Fill up our buffer from the underlying input stream. Users of this method must ensure that they
  * use all characters in the buffer before calling this method.
  *
  * @exception IOException if an I/O error occurs.
  */
 private void fill() throws IOException {
   int i = in.read(buf, 0, buf.length);
   if (i > 0) {
     pos = 0;
     count = i;
   }
 }
  @Override
  public void onDataAvailable() throws IOException {

    ServletInputStream input = handler.getWebConnection().getInputStream();

    int len = -1;
    byte[] b = new byte[1024];

    if (input.isReady()) {
      // Expected data is "dummy request#"
      len = input.read(b);
      if (len > 0) {
        String data = new String(b, 0, len);
        if (data.endsWith("#")) {
          BufferedWriter writer =
              new BufferedWriter(
                  new OutputStreamWriter(handler.getWebConnection().getOutputStream()));
          writeLine(
              writer,
              "isPostConstructCallbackInvoked: " + handler.isPostConstructCallbackInvoked());
          writeLine(writer, "isInjectionOk: " + handler.isInjectionOk());
          writeLine(writer, "isInterceptorInvoked: " + isInterceptorInvoked());
          writeLine(writer, "END");
          writer.flush();
        }
      } else {
        System.out.println("Data length: " + len);
      }
    }
  }
  public void service(ServletRequest request, ServletResponse response)
      throws ServletException, IOException {

    /**
     * We get the content length using getContentLength and we read from the input stream. if the no
     * of chars read matches the no returned by getContentLength we pass the test
     */
    PrintWriter out = response.getWriter();

    // get the content length
    int contentLength = request.getContentLength();

    int len = 0;
    // getting input stream

    ServletInputStream sin = request.getInputStream();
    // read from the stream

    while (sin.read() != -1) {
      len++;
    }

    // did we get what we wrote
    if ((contentLength == len) || (contentLength == -1)) {
      out.println("GetContentLengthTest test PASSED");
    } else {
      out.println("GetContentLengthTest test FAILED <BR> ");
      out.println("     ServletRequest.getContentLength() method FAILED <BR> ");
      out.println("     Expected Value returned ->" + contentLength + " <BR> ");
      out.println("     Actual Value returned -> " + len);
    }
  }
  private void loadParam() {
    if (!loadParam) {
      try {
        loadParam(queryString);

        String contentType = getContentType();
        if (method.equals("POST")
            && contentType != null
            && contentType.startsWith("application/x-www-form-urlencoded")) {
          int contentLength = getContentLength();
          byte[] data = new byte[contentLength];
          byte[] buf = new byte[1024];
          ServletInputStream input = getInputStream();
          try {
            int readBytes = 0;
            for (int len = 0; (len = input.read(buf)) != -1; ) {
              System.arraycopy(buf, 0, data, readBytes, len);
              readBytes += len;
              if (readBytes >= contentLength) break;
            }
            loadParam(new String(data, characterEncoding));
          } finally {
            input.close();
          }
        }
      } catch (Throwable t) {
        log.error("load param error", t);
      }
      loadParam = true;
    }
  }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ServletInputStream is = request.getInputStream();
    ServletOutputStream os = response.getOutputStream();

    System.out.println(request.getContentLength());
    System.out.println(request.getContentType());
    int clength = request.getContentLength();
    byte[] data = new byte[clength];
    int offset = 0;
    do {
      int rc = is.read(data, offset, data.length - offset);
      if (-1 == rc) {
        break;
      }
      offset += rc;
    } while (offset < data.length);

    // Echo input stream to output stream
    os.println(header);
    os.print(new String(data, 0, offset));
    os.println();
    os.println(footer);

    response.setContentType("text/html");

    is.close();
    os.close();
  }
Beispiel #6
0
  /**
   * Parse the parameters of this request, if it has not already occurred. If parameters are present
   * in both the query string and the request content, they are merged.
   */
  protected void parseParameters() {
    if (parsed) return;
    ParameterMap results = parameters;
    if (results == null) results = new ParameterMap();
    results.setLocked(false);
    String encoding = getCharacterEncoding();
    if (encoding == null) encoding = "ISO-8859-1";

    // Parse any parameters specified in the query string
    String queryString = getQueryString();
    try {
      RequestUtil.parseParameters(results, queryString, encoding);
    } catch (UnsupportedEncodingException e) {;
    }

    // Parse any parameters specified in the input stream
    String contentType = getContentType();
    if (contentType == null) contentType = "";
    int semicolon = contentType.indexOf(';');
    if (semicolon >= 0) {
      contentType = contentType.substring(0, semicolon).trim();
    } else {
      contentType = contentType.trim();
    }
    if ("POST".equals(getMethod())
        && (getContentLength() > 0)
        && "application/x-www-form-urlencoded".equals(contentType)) {
      try {
        int max = getContentLength();
        int len = 0;
        byte buf[] = new byte[getContentLength()];
        ServletInputStream is = getInputStream();
        while (len < max) {
          int next = is.read(buf, len, max - len);
          if (next < 0) {
            break;
          }
          len += next;
        }
        is.close();
        if (len < max) {
          throw new RuntimeException("Content length mismatch");
        }
        RequestUtil.parseParameters(results, buf, encoding);
      } catch (UnsupportedEncodingException ue) {;
      } catch (IOException e) {
        throw new RuntimeException("Content read fail");
      }
    }

    // Store the final results
    results.setLocked(true);
    parsed = true;
    parameters = results;
  }
  /**
   * Implement length limitation on top of the <code>read</code> method of the wrapped <code>
   * ServletInputStream</code>.
   *
   * @return the next byte of data, or <code>-1</code> if the end of the stream is reached.
   * @exception IOException if an I/O error occurs.
   */
  public int read() throws IOException {
    if (totalRead >= totalExpected) {
      return -1;
    }

    int result = in.read();
    if (result != -1) {
      totalRead++;
    }
    return result;
  }
 /**
  * Implement length limitation on top of the <code>read</code> method of the wrapped <code>
  * ServletInputStream</code>.
  *
  * @param b destination buffer.
  * @param off offset at which to start storing bytes.
  * @param len maximum number of bytes to read.
  * @return the number of bytes read, or <code>-1</code> if the end of the stream has been reached.
  * @exception IOException if an I/O error occurs.
  */
 public int read(byte b[], int off, int len) throws IOException {
   int result, left = totalExpected - totalRead;
   if (left <= 0) {
     return -1;
   } else {
     result = in.read(b, off, Math.min(left, len));
   }
   if (result > 0) {
     totalRead += result;
   }
   return result;
 }
Beispiel #9
0
  public boolean execute(
      HttpServletRequest request, HttpServletResponse response, Map<Object, Object> ctx)
      throws Exception {
    if (!"PUT".equals(request.getMethod())) {
      return true;
    }

    File fsFile = fs(request.getPathInfo());

    int code = 200;
    if (!fsFile.exists()) {
      code = 201;
    }

    fsFile.getParentFile().mkdirs();
    fsFile.createNewFile();

    if (!fsFile.canWrite()) {
      code = 405;
      response.sendError(code);
      return false;
    } else {

      ServletInputStream in = request.getInputStream();
      FileOutputStream out = null;
      try {
        out = new FileOutputStream(fsFile);

        byte[] b = new byte[16000];
        int count = -1;
        while ((count = in.read(b)) != -1) {
          out.write(b, 0, count);
        }

      } finally {
        if (in != null) {
          in.close();
        }
        if (out != null) {
          out.close();
        }
      }
    }

    response.setStatus(code);
    return false;
  }
Beispiel #10
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ServletInputStream is = request.getInputStream();
    int len;
    byte b[] = new byte[8096];
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    while ((len = is.read(b)) > 0) {
      baos.write(Arrays.copyOf(b, len));
    }

    StringTokenizer tokenizer = new StringTokenizer(new String(baos.toByteArray()), "\r\n");
    String user = "", marker = "";
    int index = 0;
    while (tokenizer.hasMoreTokens()) {
      String s = tokenizer.nextToken();
      if (s.indexOf("name=\"frame_") != -1) {
        user = s.split(";")[1];
        user = user.split("=")[1];
        user = user.replaceAll("\"", "");
        user = user.split("_")[1];
        break;
      }

      if (index == 0) {
        marker = s;
      }
    }

    Path pCheck = Paths.get(System.getProperty("user.dir"), "app", "frames", user);
    if (!pCheck.toFile().exists()) {
      return;
    }

    byte[] data = baos.toByteArray();
    byte[] image = null;
    for (int i = 0; i < data.length - 4; i++) {
      if (data[i] == 13 && data[i + 1] == 10 && data[i + 2] == 13 && data[i + 3] == 10) {
        image = Arrays.copyOfRange(data, i + 4, data.length - (marker.getBytes().length + 6));
        break;
      }
    }

    Path p = Paths.get("frames", user, "frame.jpg");
    Files.write(rootPath.resolve(p), image);
    Logger.getGlobal().log(Level.INFO, "Write frame {0}", p);
  }
Beispiel #11
0
  private void processSend(String aConnectorId, HttpServletRequest aReq, HttpServletResponse aResp)
      throws IOException {
    final String lData;

    if (aReq.getParameterMap().containsKey("data")) {
      lData = aReq.getParameter("data");
    } else {
      byte[] lBuffer = new byte[mEngine.getConfiguration().getMaxFramesize()];
      ServletInputStream aIS = aReq.getInputStream();

      int lBytesRead = aIS.read(lBuffer);
      lData = new String(lBuffer, 0, lBytesRead);
    }

    if (null == lData || "".equals(lData)) {
      sendMessage(400, "Invalid request parameters!", aResp);
      return;
    }

    send(aConnectorId, lData, aReq, aResp);
  }
 /**
  * Obtain the byte array for this part of the request.
  *
  * <p>It may be necessary to modify this code to handle additional encoding types such as Base64.
  *
  * @param input Object from which data is read
  * @param thisPage Object containing information for this request
  * @param encoding type of character encoding to be used
  * @return Byte array for this part of request
  * @throws IOException if io errors
  */
 protected byte[] readPart(ServletInputStream input, ThisPage thisPage, String encoding)
     throws IOException {
   HttpServletRequest req = thisPage.getRequest();
   String boundary = extractBoundary(req);
   byte buffer[] = new byte[4096];
   int bytesRead = -1;
   ByteArrayOutputStream working = null;
   boolean pendingRN = false;
   working = new ByteArrayOutputStream();
   /*
    * Read body of part
    */
   while (true) {
     bytesRead = input.readLine(buffer, 0, buffer.length);
     if (bytesRead < 0) {
       thisPage.addMessage("readPart method - Section of form not properly ended");
       thisPage.errorMessage();
       return null;
     } else if (bytesRead == 0) {
       thisPage.addMessage("readPart method - Read yielded 0 characters");
       thisPage.errorMessage();
       return null;
     } else if (bytesRead == 1 && buffer[0] == '\n') {
       if (pendingRN) {
         working.write('\r');
         working.write('\n');
         pendingRN = false;
       }
       working.write(buffer[0]);
     } else if (new String(buffer, 0, bytesRead).equals("--" + boundary + "\r\n")) {
       if (!pendingRN) {
         thisPage.addMessage("readPart method - Boundary reached without preceding end of line");
         thisPage.errorMessage();
         return null;
       }
       if (working.size() == 0) {
         return null;
       }
       return working.toByteArray();
     } else if (new String(buffer, 0, bytesRead).equals("--" + boundary + "--\r\n")) {
       thisPage.setEndOfPacket(true);
       if (!pendingRN) {
         thisPage.addMessage(
             "readPart method - Final boundary reached with preceding end of line");
         thisPage.errorMessage();
         return null;
       }
       if (working.size() == 0) {
         return null;
       }
       return working.toByteArray();
     } else if (buffer[bytesRead - 2] == '\r' && buffer[bytesRead - 1] == '\n') {
       if (pendingRN) {
         working.write('\r');
         working.write('\n');
       }
       if (bytesRead > 2) {
         working.write(buffer, 0, bytesRead - 2);
       }
       pendingRN = true;
     } else if (buffer[bytesRead - 1] == '\r') {
       if (pendingRN) {
         working.write('\r');
         working.write('\n');
         pendingRN = false;
       }
       if (bytesRead > 1) {
         working.write(buffer, 0, bytesRead - 1);
       }
       int nextChar = input.read();
       if (nextChar == '\n') {
         pendingRN = true;
       } else {
         working.write('\r');
         working.write(nextChar);
       }
     } else {
       if (pendingRN) {
         working.write('\r');
         working.write('\n');
         pendingRN = false;
       }
       working.write(buffer, 0, bytesRead);
     }
   }
 }
Beispiel #13
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    int len = request.getContentLength();
    if (len > 4096) {
      logger.error("post data too big: " + len);
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "post data too big: " + len);
      return;
    }
    byte[] bufferin = new byte[len];
    ServletInputStream postDataStream = request.getInputStream();

    // Build the POST data string
    ByteArrayOutputStream postDataBuffer = new ByteArrayOutputStream(len);
    int read;
    while ((read = postDataStream.read(bufferin)) > 0) {
      postDataBuffer.write(bufferin, 0, read);
    }
    ;
    String postData = postDataBuffer.toString();
    logger.debug(Util.delayedFormatString("Post data: %s", postData));

    JrdsJSONObject paramsClean;

    try {
      JrdsJSONObject params = new JrdsJSONObject(postData);
      paramsClean = new JrdsJSONObject();
      for (String key : params) {
        if (JSONKEYS.contains(key)) {
          Object value = params.get(key);
          if (value instanceof String && "".equals(((String) value).trim())) {
            value = null;
          }
          if (value != null) paramsClean.put(JSONDICT.get(key).toString(), value);
        }
      }
    } catch (JSONException e) {
      logger.error("Invalid JSON object:" + postData);
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid POST data");
      return;
    }

    ByteArrayOutputStream packedDataBuffer = new ByteArrayOutputStream(len);
    GZIPOutputStream gzipBuffer = new GZIPOutputStream(new OutputStream(packedDataBuffer), len);
    gzipBuffer.write(paramsClean.toString().getBytes());
    gzipBuffer.close();

    char separator = '?';
    String referer = request.getHeader("Referer");
    try {
      URL refererUrl = new URL(referer);
      if (refererUrl.getQuery() != null) separator = '&';
    } catch (Exception e) {
      String host = request.getHeader("Host");
      String contextPath = request.getContextPath();
      referer = "http://" + host + contextPath + "/";
    }

    String packedurl =
        referer
            + separator
            + "p="
            + new String(packedDataBuffer.toByteArray())
                .substring(GZIPHEADER.length())
                .replace('=', '!')
                .replace('/', '$')
                .replace('+', '*');

    response.getOutputStream().print(packedurl);
    response.flushBuffer();
  }
Beispiel #14
0
 public int read() throws IOException {
   if (trans > LIMITE)
     throw new IOException("Limite excedido. Arquivo é muito grande para ser enviado!");
   ++trans;
   return in.read();
 }
  private void chat(HttpServletRequest request, HttpServletResponse response) {
    try {
      ServletInputStream in = request.getInputStream();
      XStream xs = SerializeXmlUtil.createXstream();
      xs.processAnnotations(InputMsg.class);
      xs.processAnnotations(OutputMsg.class);
      // 将流转换为字符串
      StringBuilder xmlMsg = new StringBuilder();
      byte[] b = new byte[4096];
      for (int n; (n = in.read(b)) != -1; ) {
        xmlMsg.append(new String(b, 0, n, "UTF-8"));
      }
      // 将xml内容转换为InputMessage对象
      InputMsg inputMsg = (InputMsg) xs.fromXML(xmlMsg.toString());

      String servername = inputMsg.getToUserName(); // 服务端
      String custermname = inputMsg.getFromUserName(); // 客户端
      long createTime = inputMsg.getCreateTime(); // 接收时间
      Long returnTime = Calendar.getInstance().getTimeInMillis() / 1000; // 返回时间

      // 取得消息类型
      String msgType = inputMsg.getMsgType();
      // 根据消息类型获取对应的消息内容
      if (msgType.equals(MsgType.TEXT.getName())) {
        // 文本消息
        System.out.println("开发者微信号:" + inputMsg.getToUserName());
        System.out.println("发送方帐号:" + inputMsg.getFromUserName());
        System.out.println("消息创建时间:" + inputMsg.getCreateTime() + new Date(createTime * 1000l));
        System.out.println("消息内容:" + inputMsg.getContent());
        System.out.println("消息Id:" + inputMsg.getMsgId());

        StringBuffer str = new StringBuffer();
        str.append("<xml>");
        str.append("<ToUserName><![CDATA[" + custermname + "]]></ToUserName>");
        str.append("<FromUserName><![CDATA[" + servername + "]]></FromUserName>");
        str.append("<CreateTime>" + returnTime + "</CreateTime>");
        str.append("<MsgType><![CDATA[" + msgType + "]]></MsgType>");
        str.append("<Content><![CDATA[你说的是:" + inputMsg.getContent() + ",吗?]]></Content>");
        str.append("</xml>");
        System.out.println(str.toString());
        response.getWriter().write(str.toString());
      }
      // 获取并返回多图片消息
      if (msgType.equals(MsgType.IMAGE.getName())) {
        System.out.println("获取多媒体信息");
        System.out.println("多媒体文件id:" + inputMsg.getMediaId());
        System.out.println("图片链接:" + inputMsg.getPicUrl());
        System.out.println("消息id,64位整型:" + inputMsg.getMsgId());

        OutputMsg outputMsg = new OutputMsg();
        outputMsg.setFromUserName(servername);
        outputMsg.setToUserName(custermname);
        outputMsg.setCreateTime(returnTime);
        outputMsg.setMsgType(msgType);
        ImageMsg images = new ImageMsg();
        images.setMediaId(inputMsg.getMediaId());
        outputMsg.setImage(images);
        System.out.println("xml转换:/n" + xs.toXML(outputMsg));
        response.getWriter().write(xs.toXML(outputMsg));
      }

      if (msgType.equals(MsgType.ENENT.getName())) {
        // 事件消息
        System.out.println("开发者微信号:" + inputMsg.getToUserName());
        System.out.println("发送方帐号:" + inputMsg.getFromUserName());
        System.out.println("消息创建时间:" + inputMsg.getCreateTime() + new Date(createTime * 1000l));
        String event = inputMsg.getEvent();
        System.out.println("事件:" + event);

        if ("subscribe".equals(event)) { // 关注
          StringBuffer str = new StringBuffer();
          str.append("<xml>");
          str.append("<ToUserName><![CDATA[" + custermname + "]]></ToUserName>");
          str.append("<FromUserName><![CDATA[" + servername + "]]></FromUserName>");
          str.append("<CreateTime>" + returnTime + "</CreateTime>");
          str.append("<MsgType><![CDATA[text]]></MsgType>");
          str.append(
              "<Content><![CDATA[谢谢你关注此公众号!\r\n"
                  + "\n请按一下指引操作:"
                  + "\n回复1:免费获取公开课资料 "
                  + "\n回复2:进入报名页面 "
                  + "\n回复3:进入签到页面 "
                  + "\n回复4:获取开发者详细资料\r\n"
                  + "\n郑重声明:以上纯属虚构,用于开发者业余操练,为项目做准备!]]></Content>");
          str.append("</xml>");
          System.out.println(str.toString());
          response.getWriter().write(str.toString());
        } else if ("unsubscribe".equals(event)) { // 取消关注
          System.out.println("取消了关注");
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }