/** * 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); } } }