private String readLine(ServletInputStream in) throws IOException {
    StringBuilder sbuf = new StringBuilder();
    int result;
    do {
      result = in.readLine(buf, 0, buf.length); // does +=
      if (result != -1) {
        sbuf.append(new String(buf, 0, result, encoding));
      }
    } while (result == buf.length); // loop only if the buffer was filled

    if (sbuf.length() == 0) {
      return null; // nothing read, must be at the end of stream
    }

    // Cut off the trailing \n or \r\n
    // It should always be \r\n but IE5 sometimes does just \n
    // Thanks to Luke Blaikie for helping make this work with \n
    int len = sbuf.length();
    if (len >= 2 && sbuf.charAt(len - 2) == '\r') {
      sbuf.setLength(len - 2); // cut \r\n
    } else if (len >= 1 && sbuf.charAt(len - 1) == '\n') {
      sbuf.setLength(len - 1); // cut \n
    }
    return sbuf.toString();
  }
  /** @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();
  }
  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);
    }
  }
  @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);
      }
    }
  }
Exemple #5
0
  /*
   * protected method to get a job in JsonBean representation
   */
  @Override
  protected JsonBean getJob(HttpServletRequest request, HttpServletResponse response)
      throws XServletException, IOException, BaseEngineException {
    ServletInputStream is = request.getInputStream();
    byte[] b = new byte[101];
    while (is.readLine(b, 0, 100) != -1) {
      XLog.getLog(getClass()).warn("Printing :" + new String(b));
    }

    JsonBean jobBean = null;
    String jobId = getResourceName(request);
    if (jobId.endsWith("-B")) {
      jobBean = getBundleJob(request, response);
    } else {
      if (jobId.endsWith("-W")) {
        jobBean = getWorkflowJob(request, response);
      } else {
        if (jobId.contains("-W@")) {
          jobBean = getWorkflowAction(request, response);
        } else {
          if (jobId.contains("-C@")) {
            jobBean = getCoordinatorAction(request, response);
          } else {
            jobBean = getCoordinatorJob(request, response);
          }
        }
      }
    }

    return jobBean;
  }
  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;
    }
  }
Exemple #7
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;
  }
 /**
  * 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;
   }
 }
  private Document getDocument(ServletInputStream inputStream, int contentLength) {
    int charCount = 0;
    byte[] byteBuffer = new byte[contentLength];

    while (true) {
      try {
        int readLength = inputStream.readLine(byteBuffer, charCount, 1024);
        // LogEvent.logFatal("IndicatorAggregationReportingServlet", String.valueOf(readLength), new
        // String(byteBuffer).trim());

        if (readLength == -1) {
          return DocumentHelper.parseText(new String(byteBuffer).trim());
        } else {
          charCount += readLength;
        }

      } catch (IOException e) {
        e.printStackTrace();
        return null;
      } catch (DocumentException de) {
        de.printStackTrace();
        return null;
      }
    }
  }
Exemple #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);
  }
Exemple #11
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;
  }
  @Override
  public Collection<Part> getParts() throws IOException, ServletException {
    if (multipartFormData == null) {
      ServletInputStream input = null;
      try {
        input = getInputStream();
        PartImpl.tempdir = config.getTempdir();
        multipartFormData =
            new MultipartFormData(
                MultipartFormDataParser.parse(input, getHeader("Content-Type"), characterEncoding));
      } finally {
        input.close();
      }
    }

    return multipartFormData.getParts();
  }
Exemple #13
0
  /**
   * The method reads the next line from the servlet input stream into a byte array and returns a
   * String form of the array.Returns null if it reaches the end of the stream
   *
   * @return String The next line in the stream
   * @throws IOException - If there was a problem reading the stream or
   */
  private String readLine() throws IOException {
    int len = 0;
    String line = null;
    len = in.readLine(buff, 0, buff.length);
    if (len < 0) return null;
    line = new String(buff, 0, len, "ISO-8859-1");

    return line;
  }
Exemple #14
0
 /** Convenience method to read HTTP header lines */
 private synchronized String getLine(ServletInputStream sis) throws IOException {
   byte b[] = new byte[1024];
   int read = sis.readLine(b, 0, b.length), index;
   String line = null;
   if (read != -1) {
     line = new String(b, 0, read);
     if ((index = line.indexOf('\n')) >= 0) line = line.substring(0, index - 1);
   }
   return line;
 }
  /**
   * 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;
  }
Exemple #16
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);
  }
 /**
  * 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;
 }
  @Override
  public void destroy(boolean force) {
    if (!force) return;

    b.localAttributes.clear();
    if (bis != null) {
      try {
        bis.close();
      } catch (IOException e) {
      }
    }

    if (br != null) {
      try {
        br.close();
      } catch (IOException e) {
      }
    }

    b.headers.clear();
    b.queryStrings.clear();
  }
Exemple #19
0
  /**
   * Reads the file content from the stream and writes it to the local file system
   *
   * @throws IOException - If there was a problem reading the stream
   */
  private void writeToFile() throws IOException {
    // Open an o/p stream
    File tmpFile = File.createTempFile(prefix, "upload", new File(dir));
    tmpFile.deleteOnExit();
    log.debug("Setting: " + uploadFileArg + " to: " + tmpFile.getPath());
    map.put(uploadFileArg, tmpFile.getPath());
    // FileOutputStream out = new FileOutputStream (dir+File.separator+fileName);
    FileOutputStream out = new FileOutputStream(tmpFile);

    // this flag checks if \r\n needs to be written to the file
    // the servlet output stream appends these characters at the end of the
    // last line of the content, which should be skipped
    // so in the loop, all \r\n but for the last line are written to the file
    boolean writeCR = false;
    int len = 0;
    String line = null;
    map.put(paramName, fileName);

    // for each line
    while ((len = in.readLine(buff, 0, buff.length)) > -1) {
      line = new String(buff, 0, len);

      // if end of content, break
      if (line.startsWith(boundary)) break;
      if (writeCR) {
        writeCR = false;
        out.write('\r');
        out.write('\n');
      }
      if (len > 2 && buff[len - 2] == '\r' && buff[len - 1] == '\n') {
        writeCR = true;
        out.write(buff, 0, len - 2);
      } else {
        out.write(buff, 0, len);
      }
    }
    out.close();
  }
  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();
    }
  }
 /**
  * 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);
     }
   }
 }
  /**
   * Process the call to the servlet.
   *
   * <p>With regard to reading data from the request, a {@link javax.servlet.ServletInputStream}
   * object for binary data can be obtained by {@link HttpServletRequest#getInputStream()} or a
   * {@link java.io.BufferedReader} can be obtained for character data by using {@link
   * HttpServletRequest#getReader}.
   *
   * <p>With regard to writing data to the response a {@link javax.servlet.ServletOutputStream}
   * object for binary data can be obtained using {@link HttpServletResponse#getOutputStream()}
   * while a {@link java.io.PrintWriter} object can be obtained using {@link
   * HttpServletResponse#getWriter()}.
   *
   * <p>The {@link java.io.ByteArrayOutputStream} class can be used as a means of collecting the
   * bytes contained in the attached file.
   *
   * <p>It would be desirable to have tests for enctype and method.
   *
   * @param req Request object
   * @param res Response object
   * @throws IOException if io problems
   */
  public void service(HttpServletRequest req, HttpServletResponse res) throws IOException {
    ThisPage thisPage = new ThisPage(req, res, config);
    GenericPrinter output = thisPage.getPrinter();
    if (!req.getMethod().equalsIgnoreCase("post")) {
      output.println("<html><head>");
      output.println("<title>Must use POST method</title>");
      output.println("</head><body>");
      output.println("<h1>Must use POST method</h1>");
      output.println("<p>Request used " + req.getMethod() + " method</p>");
      output.println("<p>Must use POST method</p>");
      output.println("</body></html>");
      thisPage.sendContents();
      return;
    } else if (req.getHeader("content-type") == null) {
      output.println("<html><head>");
      output.println("<title>Missing content-type header</title>");
      output.println("</head><body>");
      output.println("<h1>Missing content-type header</h1>");
      output.println(
          "<p>Must use content-type header " + "to specify multipart/form-data encoding</p>");
      output.println("</body></html>");
      thisPage.sendContents();
      return;
    } else if (!req.getHeader("content-type").toLowerCase().startsWith("multipart/form-data")) {
      output.println("<html><head>");
      output.println("<title>Must use multipart/form-data encoding</title>");
      output.println("</head><body>");
      output.println("<h1>Must use multipart/form-data encoding</h1>");
      output.println("<p>content-type is " + req.getHeader("content-type") + " </p>");
      output.println("<p>Must use multipart/form-data encoding</p>");
      output.println("</body></html>");
      thisPage.sendContents();
      return;
    }
    String boundary = extractBoundary(req);
    if (boundary == null) {
      thisPage.addMessage("Unable to extract boundary value");
      thisPage.addMessage(req.getHeader("content-type"));
      thisPage.errorMessage();
      return;
    }
    int counter = 0;
    byte buffer[] = new byte[4096];
    byte extract[];
    int bytesRead = -1;
    ServletInputStream input = req.getInputStream();
    bytesRead = input.readLine(buffer, 0, buffer.length);
    if (!new String(buffer, 0, bytesRead, "ISO8859_1").startsWith("--" + boundary)) {
      thisPage.addMessage(
          "Should be separator "
              + "--"
              + boundary
              + " : "
              + " found "
              + new String(buffer, 0, bytesRead));
      thisPage.errorMessage();
      return;
    }
    while (true) {
      counter++;
      Contents part = new Contents();
      thisPage.addMessage("Starting part " + Integer.toString(counter) + " of form");
      while (true) {

        bytesRead = input.readLine(buffer, 0, buffer.length);
        if (bytesRead < 0) {
          thisPage.addMessage("Unexpected end of packet");
          thisPage.errorMessage();
          return;
        } else {
          String value = new String(buffer, 0, bytesRead, "ISO8859_1");
          if (value.endsWith("\r\n")) {
            value = stripEOL(value);
          }
          if (value.length() == 0) {
            extract = readPart(input, thisPage, part.getTransferEncoding());
            if (thisPage.getTerminateRequest()) {
              return;
            }
            part.setContents(extract);
            thisPage.addElement(part);
            break;
          } else {
            thisPage.addMessage("service method - Parsing line: " + value);
            part.parseLine(value);
          }
        }
      }
      if (thisPage.getEndOfPacket()) {
        break;
      }
    }
    if (thisPage.getTerminateRequest()) {
      return;
    }
    starter(thisPage);
    if (thisPage.getTerminateRequest()) {
      return;
    }
    processor(thisPage);
    if (thisPage.getTerminateRequest()) {
      return;
    }
    ender(thisPage);
    if (thisPage.getTerminateRequest()) {
      return;
    }
    if (thisPage.getRedirectAddress() != null) {
      thisPage
          .getResponse()
          .sendRedirect(thisPage.getResponse().encodeRedirectURL(thisPage.getRedirectAddress()));
    }
  }
Exemple #23
0
 public Hashtable processData(
     ServletInputStream is, String boundary, String saveInDir, int clength)
     throws IllegalArgumentException, IOException {
   if (is == null) throw new IllegalArgumentException("InputStream");
   if (boundary == null || boundary.trim().length() < 1)
     throw new IllegalArgumentException("\"" + boundary + "\" is an illegal boundary indicator");
   boundary = "--" + boundary;
   StringTokenizer stLine = null, stFields = null;
   FileInfo fileInfo = null;
   Hashtable dataTable = new Hashtable(5);
   String line = null, field = null, paramName = null;
   boolean saveFiles = (saveInDir != null && saveInDir.trim().length() > 0);
   boolean isFile = false;
   if (saveFiles) { // Create the required directory (including parent dirs)
     File f = new File(saveInDir);
     f.mkdirs();
   }
   line = getLine(is);
   if (line == null || !line.startsWith(boundary))
     throw new IOException("Boundary not found; boundary = " + boundary + ", line = " + line);
   while (line != null) {
     if (line == null || !line.startsWith(boundary)) return dataTable;
     line = getLine(is);
     if (line == null) return dataTable;
     stLine = new StringTokenizer(line, ";\r\n");
     if (stLine.countTokens() < 2) throw new IllegalArgumentException("Bad data in second line");
     line = stLine.nextToken().toLowerCase();
     if (line.indexOf("form-data") < 0)
       throw new IllegalArgumentException("Bad data in second line");
     stFields = new StringTokenizer(stLine.nextToken(), "=\"");
     if (stFields.countTokens() < 2)
       throw new IllegalArgumentException("Bad data in second line");
     fileInfo = new FileInfo();
     stFields.nextToken();
     paramName = stFields.nextToken();
     isFile = false;
     if (stLine.hasMoreTokens()) {
       field = stLine.nextToken();
       stFields = new StringTokenizer(field, "=\"");
       if (stFields.countTokens() > 1) {
         if (stFields.nextToken().trim().equalsIgnoreCase("filename")) {
           fileInfo.name = paramName;
           String value = stFields.nextToken();
           if (value != null && value.trim().length() > 0) {
             fileInfo.clientFileName = value;
             isFile = true;
           } else {
             line = getLine(is); // Skip "Content-Type:" line
             line = getLine(is); // Skip blank line
             line = getLine(is); // Skip blank line
             line = getLine(is); // Position to boundary line
             continue;
           }
         }
       } else if (field.toLowerCase().indexOf("filename") >= 0) {
         line = getLine(is); // Skip "Content-Type:" line
         line = getLine(is); // Skip blank line
         line = getLine(is); // Skip blank line
         line = getLine(is); // Position to boundary line
         continue;
       }
     }
     boolean skipBlankLine = true;
     if (isFile) {
       line = getLine(is);
       if (line == null) return dataTable;
       if (line.trim().length() < 1) skipBlankLine = false;
       else {
         stLine = new StringTokenizer(line, ": ");
         if (stLine.countTokens() < 2)
           throw new IllegalArgumentException("Bad data in third line");
         stLine.nextToken(); // Content-Type
         fileInfo.fileContentType = stLine.nextToken();
       }
     }
     if (skipBlankLine) {
       line = getLine(is);
       if (line == null) return dataTable;
     }
     if (!isFile) {
       line = getLine(is);
       if (line == null) return dataTable;
       dataTable.put(paramName, line);
       // If parameter is dir, change saveInDir to dir
       if (paramName.equals("dir")) saveInDir = line;
       line = getLine(is);
       continue;
     }
     try {
       UplInfo uplInfo = new UplInfo(clength);
       UploadMonitor.set(fileInfo.clientFileName, uplInfo);
       OutputStream os = null;
       String path = null;
       if (saveFiles)
         os = new FileOutputStream(path = getFileName(saveInDir, fileInfo.clientFileName));
       else os = new ByteArrayOutputStream(ONE_MB);
       boolean readingContent = true;
       byte previousLine[] = new byte[2 * ONE_MB];
       byte temp[] = null;
       byte currentLine[] = new byte[2 * ONE_MB];
       int read, read3;
       if ((read = is.readLine(previousLine, 0, previousLine.length)) == -1) {
         line = null;
         break;
       }
       while (readingContent) {
         if ((read3 = is.readLine(currentLine, 0, currentLine.length)) == -1) {
           line = null;
           uplInfo.aborted = true;
           break;
         }
         if (compareBoundary(boundary, currentLine)) {
           os.write(previousLine, 0, read - 2);
           line = new String(currentLine, 0, read3);
           break;
         } else {
           os.write(previousLine, 0, read);
           uplInfo.currSize += read;
           temp = currentLine;
           currentLine = previousLine;
           previousLine = temp;
           read = read3;
         } // end else
       } // end while
       os.flush();
       os.close();
       if (!saveFiles) {
         ByteArrayOutputStream baos = (ByteArrayOutputStream) os;
         fileInfo.setFileContents(baos.toByteArray());
       } else fileInfo.file = new File(path);
       dataTable.put(paramName, fileInfo);
       uplInfo.currSize = uplInfo.totalSize;
     } // end try
     catch (IOException e) {
       throw e;
     }
   }
   return dataTable;
 }
Exemple #24
0
 public int read() throws IOException {
   if (trans > LIMITE)
     throw new IOException("Limite excedido. Arquivo é muito grande para ser enviado!");
   ++trans;
   return in.read();
 }
Exemple #25
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();
  }
Exemple #26
0
    long readPart(String encoding, String boundary, ServletInputStream sis, ServletAccessDescr sad)
        throws IOException {
      long currentPos = 0;
      byte[] buff = new byte[BUFF_SIZE * 1024];
      int boundaryLen = boundary.length();
      if (boundaryLen >= (buff.length - 2))
        throw new IOException(
            "Boundary length exceeds allowed:" + boundaryLen + "/" + (buff.length - 2));
      String hl;
      int ss;
      // parse part headers
      do {
        int len = sis.readLine(buff, 0, buff.length);
        if (len < 0) throw new IOException("Trying reading parts after EOS");
        currentPos += len;
        if (buff[len - 1] != '\n') throw new IOException("Part header is over " + buff.length);
        hl = new String(buff, 0, len - 2, "US-ASCII");
        // System.err.println("h:" + hl);
        if (hl.length() == 0) break;
        ss = hl.indexOf(boundary);
        if (ss >= 0) {
          if (hl.indexOf("--", boundaryLen + ss) == boundaryLen + ss) return -currentPos; //
          continue; // 1st part starts with it
        }

        hl = new String(buff, 0, len - 2, encoding);
        ss = hl.indexOf(':');
        if (ss < 0)
          throw new IOException("Illegal multipart header, no value separator ':' in " + hl);
        String header = hl.substring(0, ss).toLowerCase();
        String value = hl.substring(ss + 1).trim();
        headers.put(header, value);
        if (header.equals("Content-Disposition".toLowerCase())) {
          // TODO add real parser as for cookies
          if (name != null)
            throw new IOException("Multiple header 'Content-Disposition' for the same part: " + hl);
          int ni = value.toLowerCase().indexOf("name=\"");
          if (ni < 0) throw new IOException("Part name is missed in 'Content-Disposition'" + hl);
          int eq = value.indexOf('"', ni + "name=\"".length());
          // TODO name can be encoded so right approach is decoding it here
          name = value.substring(ni + "name=\"".length(), eq);

          ni = value.toLowerCase().indexOf("filename=\"");
          if (ni >= 0) {
            eq = value.indexOf('"', ni + "filename=\"".length());
            filename = value.substring(ni + "filename=\"".length(), eq);
          }
        }
        // TODO Analyze content-type multipart/mixed defining new boundary, so they need to be
        // stacked
      } while (true);
      // TODO for content type multipart/mixed need another loop for another boundary
      // read part content
      fileSize = 0;
      boolean writingInMem = sad.multipartThreshold > 0;
      OutputStream wos = cos;
      int state = no_rn;

      try {
        read_part:
        do {
          int len = sis.readLine(buff, 0, buff.length);
          if (len < 0) throw new IOException("Unexpected end of multipart data at " + currentPos);
          // System.err.println("" + len + "==" + new String(buff, 0, len));

          switch (state) {
            case no_rn:
              if (buff[len - 1] == '\n') {
                if (len > 1)
                  if (buff[len - 2] == '\r') {
                    wos.write(buff, 0, len - 2);
                    fileSize += len - 2;
                    state = last_rn;
                    break;
                  }
              } else if (buff[len - 1] == '\r') {
                wos.write(buff, 0, len - 1);
                fileSize += len - 1;
                state = last_r;
                break;
              }
              wos.write(buff, 0, len);
              fileSize += len;
              break;
            case last_r:
              if (buff[len - 1] == '\n') {
                if (len == 1) {
                  state = last_rn;
                  break;
                }

                if (buff[len - 2] == '\r') {
                  wos.write('\r');
                  fileSize++;
                  wos.write(buff, 0, len - 2);
                  fileSize += len - 2;
                  state = last_rn;
                  break;
                }
              } else if (buff[len - 1] == '\r') {
                wos.write('\r');
                fileSize++;
                wos.write(buff, 0, len - 1);
                fileSize += len - 1;
                state = last_r;
                break;
              }
              wos.write('\r');
              fileSize++;
              wos.write(buff, 0, len);
              fileSize += len;
              state = no_rn;
              break;
            case last_rn:
              if (buff[len - 1] == '\n') {
                if (len > 1)
                  if (buff[len - 2] == '\r') {
                    hl = new String(buff, 0, len - 2, "US-ASCII");
                    ss = hl.indexOf(boundary);
                    if (ss >= 0) {
                      if (hl.indexOf("--", ss + boundaryLen) == (ss + boundaryLen))
                        return -currentPos - fileSize;
                      else break read_part;
                    } else {
                      wos.write('\r');
                      fileSize++;
                      wos.write('\n');
                      fileSize++;
                      wos.write(buff, 0, len - 2);
                      fileSize += len - 2;
                      break;
                    }
                  }
              } else if (buff[len - 1]
                  == '\r') { // can't be boundary limiter since buffer is bigger than boundary

              }
              wos.write('\r');
              fileSize++;
              wos.write('\n');
              fileSize++;
              wos.write(buff, 0, len);
              fileSize += len;
              state = no_rn;
              break;
            default:
              throw new IllegalStateException();
          }
          if (sad.multipartMaxFile > 0 && sad.multipartMaxFile <= fileSize)
            throw new IOException("File size exceeds limit of " + sad.multipartMaxFile);
          if (writingInMem && sad.multipartThreshold < fileSize) {
            if (sad.multipartLocation == null || sad.multipartLocation.getName().length() == 0)
              partFile = File.createTempFile(name, "multipart");
            else partFile = File.createTempFile(name, "multipart", sad.multipartLocation);
            partFile.deleteOnExit();
            wos = new FileOutputStream(partFile);
            wos.write(cos.toByteArray());
            cos.close();
            cos = null;
            writingInMem = false;
          }
        } while (true); // TODO add condition
      } finally {
        if (wos != null) { // can b e null ?
          try {
            wos.close();
          } catch (Exception e) {
          }
        }
      }
      return currentPos + fileSize;
    }
    @Override
    public void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
      final AsyncContext async = request.startAsync();
      final AtomicInteger complete = new AtomicInteger(2);
      final AtomicBoolean onDataAvailable = new AtomicBoolean(false);

      // Asynchronous Read
      if (request.getContentLength() > 0) {
        // System.err.println("reading "+request.getContentLength());
        final ServletInputStream in = request.getInputStream();
        in.setReadListener(
            new ReadListener() {
              byte[] _buf = new byte[32];

              @Override
              public void onError(Throwable t) {
                if (complete.decrementAndGet() == 0) async.complete();
              }

              @Override
              public void onDataAvailable() throws IOException {
                if (!onDataAvailable.compareAndSet(false, true)) throw new IllegalStateException();

                // System.err.println("ODA");
                while (in.isReady() && !in.isFinished()) {
                  _oda.incrementAndGet();
                  int len = in.read(_buf);
                  // System.err.println("read "+len);
                  if (len > 0) _read.addAndGet(len);
                }

                if (!onDataAvailable.compareAndSet(true, false)) throw new IllegalStateException();
              }

              @Override
              public void onAllDataRead() throws IOException {
                if (onDataAvailable.get()) {
                  LOG.warn("OADR too early!");
                  _read.set(-1);
                }

                // System.err.println("OADR");
                if (complete.decrementAndGet() == 0) async.complete();
              }
            });
      } else complete.decrementAndGet();

      // Asynchronous Write
      final String[] writes = request.getParameterValues("w");
      final ServletOutputStream out = response.getOutputStream();
      out.setWriteListener(
          new WriteListener() {
            int _w = 0;

            @Override
            public void onWritePossible() throws IOException {
              LOG.debug("OWP");
              _owp.incrementAndGet();

              while (writes != null && _w < writes.length) {
                int write = Integer.valueOf(writes[_w++]);

                if (write == 0) out.flush();
                else {
                  byte[] buf = new byte[write + 1];
                  Arrays.fill(buf, (byte) ('0' + ((_w - 1) % 10)));
                  buf[write] = '\n';
                  out.write(buf);
                }

                if (!out.isReady()) return;
              }

              if (complete.decrementAndGet() == 0) async.complete();
            }

            @Override
            public void onError(Throwable t) {
              async.complete();
            }
          });
    }