Example usage for javax.servlet ServletInputStream readLine

List of usage examples for javax.servlet ServletInputStream readLine

Introduction

In this page you can find the example usage for javax.servlet ServletInputStream readLine.

Prototype

public int readLine(byte[] b, int off, int len) throws IOException 

Source Link

Document

Reads the input stream, one line at a time.

Usage

From source file:eionet.gdem.utils.FileUpload.java

/**
 * Reads line from ServletInputStream./*w ww .  ja v a 2  s .  co  m*/
 *
 * @param buf buffer
 * @param i i
 * @param stream InputStream
 * @param charEncoding Encoding
 * @return null, if EOF is reached.
 * @throws IOException If an error occurs.
 */
// +RV020508 removed exception handling and propagated exceptions to caller
private String readLine(byte[] buf, int[] i, ServletInputStream stream, String charEncoding)
        throws IOException {
    i[0] = stream.readLine(buf, 0, buf.length); // may throw IOException
    if (i[0] == -1) {
        return null;
    }

    // +RV020508
    lenRcvd += i[0];
    //
    try {
        if (charEncoding == null) {
            return new String(buf, 0, i[0]);
        } else {
            return new String(buf, 0, i[0], charEncoding); // may throw UnsupportedEncodingException
        }
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}

From source file:com.concursive.connect.web.modules.documents.utils.HttpMultiPartParser.java

/**
 * Convenience method to read HTTP header lines
 *
 * @param sis Description of Parameter// www  . ja v  a 2s  .  c  o  m
 * @return The Line value
 * @throws IOException Description of Exception
 */
private synchronized String getLine(ServletInputStream sis) throws IOException {
    byte b[] = new byte[1024];
    int read = sis.readLine(b, 0, b.length);
    int 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);
        }
    }
    b = null;
    return line;
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.createJobs.CreateJobsMainHandler.java

private List<String> uploadFile(HttpServletRequest p_request, File parentFile)
        throws GlossaryException, IOException {
    byte[] inBuf = new byte[MAX_LINE_LENGTH];
    int bytesRead;
    ServletInputStream in;
    String contentType;//  ww  w. ja  v  a 2  s.com
    String boundary;
    String filePath = "";
    String path = parentFile.getPath() + File.separator;
    List<String> filePaths = new ArrayList<String>();
    File file = new File(path);
    Set<String> uploadedFileNames = new HashSet<String>();
    for (File f : file.listFiles()) {
        uploadedFileNames.add(f.getName());
    }

    // Let's make sure that we have the right type of content
    //
    contentType = p_request.getContentType();
    if (contentType == null || !contentType.toLowerCase().startsWith("multipart/form-data")) {
        String[] arg = { "form did not use ENCTYPE=multipart/form-data but `" + contentType + "'" };

        throw new GlossaryException(GlossaryException.MSG_FAILED_TO_UPLOAD_FILE, arg, null);
    }

    // Extract the boundary string in this request. The
    // boundary string is part of the content type string
    //
    int bi = contentType.indexOf("boundary=");
    if (bi == -1) {
        String[] arg = { "no boundary string found in request" };

        throw new GlossaryException(GlossaryException.MSG_FAILED_TO_UPLOAD_FILE, arg, null);
    } else {
        // 9 := len("boundary=")
        boundary = contentType.substring(bi + 9);

        // The real boundary has additional two dashes in
        // front
        //
        boundary = "--" + boundary;
    }

    in = p_request.getInputStream();
    bytesRead = in.readLine(inBuf, 0, inBuf.length);

    if (bytesRead < 3) {
        String[] arg = { "incomplete request (not enough data)" };

        // Not enough content was send as part of the post
        throw new GlossaryException(GlossaryException.MSG_FAILED_TO_UPLOAD_FILE, arg, null);
    }

    while (bytesRead != -1) {
        String lineRead = new String(inBuf, 0, bytesRead, "utf-8");
        if (lineRead.startsWith("Content-Disposition: form-data; name=\"")) {
            if (lineRead.indexOf("filename=\"") != -1) {
                // Get file name
                String fileName = getFilename(lineRead.substring(0, lineRead.length() - 2));

                // Get content type line
                bytesRead = in.readLine(inBuf, 0, inBuf.length);
                lineRead = new String(inBuf, 0, bytesRead - 2, "utf-8");

                // Read and ignore the blank line
                bytesRead = in.readLine(inBuf, 0, inBuf.length);

                // Create a temporary file to store the
                // contents in it for now. We might not have
                // additional information, such as TUV id for
                // building the complete file path. We will
                // save the contents in this file for now and
                // finally rename it to correct file name.
                //

                // if a file with same name has been uploaded, ignore this
                if (uploadedFileNames.contains(fileName)) {
                    continue;
                }

                filePath = path + fileName;
                filePaths.add(filePath);
                File m_tempFile = new File(filePath);
                FileOutputStream fos = new FileOutputStream(m_tempFile);
                BufferedOutputStream bos = new BufferedOutputStream(fos, MAX_LINE_LENGTH * 4);

                // Read through the file contents and write
                // it out to a local temp file.
                boolean writeRN = false;
                while ((bytesRead = in.readLine(inBuf, 0, inBuf.length)) != -1) {
                    // Let's first check if we are already on
                    // boundary line
                    if (bytesRead > 2 && inBuf[0] == '-' && inBuf[1] == '-') {
                        lineRead = new String(inBuf, 0, bytesRead, "utf-8");
                        if (lineRead.startsWith(boundary)) {
                            break;
                        }
                    }

                    // Write out carriage-return, new-line
                    // pair which might have been left over
                    // from last write.
                    //
                    if (writeRN) {
                        bos.write(new byte[] { (byte) '\r', (byte) '\n' });
                        writeRN = false;
                    }

                    // The ServletInputStream.readline() adds
                    // "\r\n" bytes for the last line of the
                    // file contents. If we find these pair
                    // as the last bytes we need to delay
                    // writing it until the next go, since it
                    // could very well be the last line of
                    // file content.
                    //
                    if (bytesRead > 2 && inBuf[bytesRead - 2] == '\r' && inBuf[bytesRead - 1] == '\n') {
                        bos.write(inBuf, 0, bytesRead - 2);
                        writeRN = true;
                    } else {
                        bos.write(inBuf, 0, bytesRead);
                    }
                }

                bos.flush();
                bos.close();
                fos.close();
            } else {
                // This is the field part

                // First get the field name

                //               int start = lineRead.indexOf("name=\"");
                //               int end = lineRead.indexOf("\"", start + 7);
                //               String fieldName = lineRead.substring(start + 6, end);

                // Read and ignore the blank line
                bytesRead = in.readLine(inBuf, 0, inBuf.length);

                // String Buffer to keep the field value
                //
                StringBuffer fieldValue = new StringBuffer();

                boolean writeRN = false;
                while ((bytesRead = in.readLine(inBuf, 0, inBuf.length)) != -1) {
                    lineRead = new String(inBuf, 0, bytesRead, "utf-8");

                    // Let's first check if we are already on
                    // boundary line
                    //
                    if (bytesRead > 2 && inBuf[0] == '-' && inBuf[1] == '-') {
                        if (lineRead.startsWith(boundary)) {
                            break;
                        }
                    }

                    // Write out carriage-return, new-line
                    // pair which might have been left over
                    // from last write.
                    //
                    if (writeRN) {
                        fieldValue.append("\r\n");
                        writeRN = false;
                    }

                    // The ServletInputStream.readline() adds
                    // "\r\n" bytes for the last line of the
                    // field value. If we find these pair as
                    // the last bytes we need to delay
                    // writing it until the next go, since it
                    // could very well be the last line of
                    // field value.
                    //
                    if (bytesRead > 2 && inBuf[bytesRead - 2] == '\r' && inBuf[bytesRead - 1] == '\n') {
                        fieldValue.append(lineRead.substring(0, lineRead.length() - 2));
                        writeRN = true;
                    } else {
                        fieldValue.append(lineRead);
                    }
                }
            }
        }

        bytesRead = in.readLine(inBuf, 0, inBuf.length);
    }
    return filePaths;
}

From source file:com.concursive.connect.web.modules.documents.utils.HttpMultiPartParser.java

/**
 * Description of the Method/*from   w  w w  .ja va2s  .  c om*/
 *
 * @param saveInDir Description of Parameter
 * @param request   Description of the Parameter
 * @return Description of the Returned Value
 * @throws IllegalArgumentException Description of Exception
 * @throws IOException              Description of Exception
 */
private HashMap processData(HttpServletRequest request, String saveInDir)
        throws IllegalArgumentException, IOException {
    String contentType = request.getHeader("Content-type");
    //TODO: use the contentLength for a progress bar
    int contentLength = request.getContentLength();
    LOG.debug("HttpMultiPartParser Length: " + contentLength);
    if ((contentType == null) || (!contentType.startsWith("multipart/"))) {
        throw new IllegalArgumentException("Not a multipart message");
    }
    int boundaryIndex = contentType.indexOf("boundary=");
    String boundary = contentType.substring(boundaryIndex + 9);
    LOG.debug("Request boundary: " + boundary);
    ServletInputStream is = request.getInputStream();
    if (is == null) {
        throw new IllegalArgumentException("InputStream");
    }
    if (boundary == null || boundary.trim().length() < 1) {
        throw new IllegalArgumentException("boundary");
    }
    //Each content will begin with two dashes "--" plus the actual boundary string
    boundary = "--" + boundary;
    //Prepare to read in from request
    StringTokenizer stLine = null;
    StringTokenizer stFields = null;
    FileInfo fileInfo = null;
    HashMap dataTable = new HashMap(5);
    String line = null;
    String field = null;
    String paramName = null;
    boolean saveFiles = (saveInDir != null && saveInDir.trim().length() > 0);
    boolean isFile = false;
    boolean validFile = false;
    int fileCount = 0;
    //First line should be the boundary
    line = getLine(is);
    if (line == null || !line.startsWith(boundary)) {
        throw new IOException("Boundary not found;" + " boundary = " + boundary + ", line = " + line);
    }
    //Continue with the rest of the lines
    while (line != null) {
        LOG.trace(line);
        // Process boundary line  ----------------------------------------
        if (line == null || !line.startsWith(boundary)) {
            return dataTable;
        }
        // Process "Content-Disposition: " line --------------------------
        line = getLine(is);
        if (line == null) {
            return dataTable;
        }
        // Split line into the following 3 tokens (or 2 if not a file):
        // 1. Content-Disposition: form-data
        // 2. name="LocalFile1"
        // 3. filename="C:\autoexec.bat"  (only present if this is part of a HTML file INPUT tag) */
        stLine = new StringTokenizer(line, ";\r\n");
        if (stLine.countTokens() < 2) {
            throw new IllegalArgumentException("Bad data in second line");
        }
        // Confirm that this is "form-data"
        line = stLine.nextToken().toLowerCase();
        if (line.indexOf("form-data") < 0) {
            throw new IllegalArgumentException("Bad data in second line");
        }
        // Now split token 2 from above into field "name" and it's "value"
        // e.g. name="LocalFile1"
        stFields = new StringTokenizer(stLine.nextToken(), "=\"");
        if (stFields.countTokens() < 2) {
            throw new IllegalArgumentException("Bad data in second line");
        }
        // Get field name
        fileInfo = new FileInfo();
        fileInfo.setVersion(version);
        fileInfo.setExtensionId(extensionId);
        stFields.nextToken();
        paramName = stFields.nextToken();
        // Now split token 3 from above into file "name" and it's "value"
        // e.g. filename="C:\autoexec.bat"
        isFile = false;
        if (stLine.hasMoreTokens()) {
            field = stLine.nextToken();
            stFields = new StringTokenizer(field, "=\"");
            if (stFields.countTokens() > 1) {
                if (stFields.nextToken().trim().equalsIgnoreCase("filename")) {
                    fileInfo.setName(paramName);
                    String value = stFields.nextToken();
                    if (value != null && value.trim().length() > 0) {
                        fileInfo.setClientFileName(value);
                        isFile = true;
                        ++fileCount;
                    } else {
                        // An error condition occurred, skip to next boundary
                        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) {
                // An error condition occurred, skip to next boundary
                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;
            }
        }
        // Process "Content-Type: " line ----------------------------------
        // e.g. Content-Type: text/plain
        boolean skipBlankLine = true;
        if (isFile) {
            line = getLine(is);
            if (line == null) {
                return dataTable;
            }
            // "Content-type" line not guaranteed to be sent by the browser
            if (line.trim().length() < 1) {
                skipBlankLine = false;
            } else {
                // Prevent re-skipping below
                stLine = new StringTokenizer(line, ": ");
                if (stLine.countTokens() < 2) {
                    throw new IllegalArgumentException("Bad data in third line");
                }
                stLine.nextToken();
                // Content-Type
                fileInfo.setFileContentType(stLine.nextToken());
            }
        }
        // Skip blank line  -----------------------------------------------
        if (skipBlankLine) {
            // Blank line already skipped above?
            line = getLine(is);
            if (line == null) {
                return dataTable;
            }
        }
        // Process data: If not a file, add to hashmap and continue
        if (!isFile) {
            line = getLine(is);
            if (line == null) {
                return dataTable;
            }
            StringBuffer sb = new StringBuffer();
            sb.append(line);
            while (line != null && !line.startsWith(boundary)) {
                line = getLine(is);
                if (line != null && !line.startsWith(boundary)) {
                    sb.append(System.getProperty("line.separator"));
                    sb.append(line);
                }
            }
            LOG.debug(" HttpMultiPartParser ->Adding param: " + paramName);
            dataTable.put(paramName, sb.toString());
            continue;
        }
        // Either save contents in memory or to a local file
        OutputStream os = null;
        String path = null;
        try {
            String tmpPath = null;
            String filenameToUse = null;
            if (saveFiles) {
                if (usePathParam) {
                    tmpPath = saveInDir + fileInfo.getName() + fs;
                } else {
                    tmpPath = saveInDir;
                }
                if (useDateForFolder) {
                    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy");
                    String datePathToUse1 = formatter1.format(new java.util.Date());
                    SimpleDateFormat formatter2 = new SimpleDateFormat("MMdd");
                    String datePathToUse2 = formatter2.format(new java.util.Date());
                    tmpPath += datePathToUse1 + fs + datePathToUse2 + fs;
                }
                // Create output directory in case it doesn't exist
                File f = new File(tmpPath);
                f.mkdirs();
                //If specified, store files using a unique name, based on date
                if (useUniqueName) {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
                    filenameToUse = formatter.format(new java.util.Date());
                    if (fileCount > 1) {
                        filenameToUse += String.valueOf(fileCount);
                    }
                } else {
                    filenameToUse = fileInfo.getClientFileName();
                }
                fileInfo.setClientFileName(getFileName(fileInfo.getClientFileName()));
                //Append a version id for record keeping and uniqueness, prevents
                //multiple uploads from overwriting each other
                filenameToUse += (version == -1 ? "" : "^" + version)
                        + (extensionId == -1 ? "" : "-" + extensionId);
                //Create the file to a file
                os = new FileOutputStream(path = getFileName(tmpPath, filenameToUse));
            } else {
                //Store the file in memory
                os = new ByteArrayOutputStream(ONE_MB);
            }
            //Begin reading in the request
            boolean readingContent = true;
            byte previousLine[] = new byte[2 * ONE_MB];
            byte temp[] = null;
            byte currentLine[] = new byte[2 * ONE_MB];
            int read;
            int read3;
            //read in the first line, break out if eof
            if ((read = is.readLine(previousLine, 0, previousLine.length)) == -1) {
                line = null;
                break;
            }
            //read until next boundary and write the contents to OutputStream
            while (readingContent) {
                if ((read3 = is.readLine(currentLine, 0, currentLine.length)) == -1) {
                    line = null;
                    break;
                }
                //check if current line is a boundary
                if (compareBoundary(boundary, currentLine)) {
                    if (read - 2 > 0) {
                        validFile = true;
                    }
                    os.write(previousLine, 0, read - 2);
                    os.flush();
                    line = new String(currentLine, 0, read3);
                    break;
                } else {
                    //current line is not a boundary, write previous line
                    os.write(previousLine, 0, read);
                    validFile = true;
                    os.flush();
                    //reposition previousLine to be currentLine
                    temp = currentLine;
                    currentLine = previousLine;
                    previousLine = temp;
                    read = read3;
                }
            }
            os.close();
            temp = null;
            previousLine = null;
            currentLine = null;
            //Store the completed file somewhere
            if (!saveFiles) {
                ByteArrayOutputStream baos = (ByteArrayOutputStream) os;
                fileInfo.setFileContents(baos.toByteArray());
            } else {
                File thisFile = new File(path);
                if (validFile) {
                    fileInfo.setLocalFile(thisFile);
                    fileInfo.setSize((int) thisFile.length());
                    os = null;
                } else {
                    thisFile.delete();
                }
            }
            if (validFile) {
                LOG.debug("Adding file param: " + fileInfo.getName());
                dataTable.put(paramName, fileInfo);
            }
        } catch (Exception e) {
            LOG.error("HttpMultiPartParser-> error: " + e.getMessage(), e);
            if (os != null) {
                os.close();
            }
            if (saveFiles && path != null) {
                File thisFile = new File(path);
                if (thisFile.exists()) {
                    thisFile.delete();
                    LOG.warn("HttpMultiPartParser-> Temporary file deleted");
                }
            }
        }
    }
    return dataTable;
}

From source file:org.n52.wps.webadmin.ConfigUploadBean.java

public void doUpload(HttpServletRequest request) throws IOException {
    savePath = WPSConfig.getConfigPath();
    // get rid of the filename
    // How is the path on a windows machine? may be better using:
    // savePath = savePath.substring(0, savePath.length() -
    // "wps_config.xml".length());
    savePath = savePath.substring(0, savePath.lastIndexOf(File.separator) + 1);
    ServletInputStream in = request.getInputStream();

    line = new byte[128];
    i = in.readLine(line, 0, 128);
    if (i < 3) {
        return;//from  w ww. j ava 2 s  .com
    }
    boundaryLength = i - 2;

    int classnameupcoming = 4;

    boundary = new String(line, 0, boundaryLength); // -2 discards
    // the newline
    // character

    /*
     * the type of the uploaded file until now only processes (.java/.zip)
     * or R scripts are supported
     */
    String type = "";

    String realSavePath = "";
    while (i != -1) {
        String newLine = new String(line, 0, i);
        System.out.println(newLine);
        if (newLine.contains("processName")) {
            type = "javaProcess";
            // we set a flag to know that the next string is the fully
            // qualified classname
            classnameupcoming--;
        } else if (newLine.contains("rProcessName")) {
            type = "rScript";
            // we set a flag to know that the next string is the fully
            // qualified classname
            classnameupcoming--;

        }
        if (classnameupcoming < 4) {
            classnameupcoming--;
        }
        if (classnameupcoming == 0) {
            // // then parse classname
            // String classname = newLine;
            // String[] classnameArr = classname.replace(".",
            // ",").split(",");
            // String classdir = new String();
            // for (int c = 0; c < classnameArr.length - 1; c++) {
            // if (c == 0) {
            // classdir = classdir + classnameArr[c];
            // } else {
            // classdir = classdir + File.separator + classnameArr[c];
            // }
            //
            // }
            // realSavePath = new File(savePath).getParentFile()
            // + "/WEB-INF/classes/";
            // realSavePath = realSavePath + classdir + File.separator;
            // new File(realSavePath).mkdirs();

            try {
                handleUpload(in, type, newLine);
                break;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (newLine.startsWith("Content-Disposition: form-data; name=\"")) {
            if (newLine.contains("processDescriptionFile")) {
                if (newLine.indexOf("filename=\"") != -1) {
                    setXMLFilename(new String(line, 0, i - 2));
                    if (xmlFilename == null) {
                        return;
                    }

                    if (!xmlFilename.equals("")) {

                        // this is the file content
                        i = in.readLine(line, 0, 128);
                        // next line
                        i = in.readLine(line, 0, 128);
                        // blank line
                        i = in.readLine(line, 0, 128);
                        newLine = new String(line, 0, i);
                        // add the prefix to the filename

                        PrintWriter pw = null;
                        if (realSavePath.length() > 0) {
                            pw = new PrintWriter(new BufferedWriter(
                                    new FileWriter((realSavePath == null ? "" : realSavePath) + xmlFilename)));
                        } else {
                            xmlFilename = filenamePrefix + xmlFilename;
                            pw = new PrintWriter(new BufferedWriter(
                                    new FileWriter((savePath == null ? "" : savePath) + filename)));
                        }

                        while (i != -1 && !newLine.startsWith(boundary)) {
                            // the problem is the last line of the file
                            // content
                            // contains the new line character.
                            // So, we need to check if the current line is
                            // the last line.
                            i = in.readLine(line, 0, 128);
                            if ((i == boundaryLength + 2 || i == boundaryLength + 4) // +
                                    // 4
                                    // is
                                    // eof
                                    && (new String(line, 0, i).startsWith(boundary))) {

                                pw.print(newLine.substring(0, newLine.length() - 2));
                            } else {
                                pw.print(newLine);
                            }

                            newLine = new String(line, 0, i);
                        }
                        pw.close();
                    }

                }

            }

            if (newLine.contains("processFile")) {
                // we upload files not config docuemnts. Therefore store is
                // somewhere else.
                // realSavePath = new
                // File(savePath).getParentFile().getAbsolutePath()+"/WEB-INF/classes/";

                /**
                 * TODO: dir structure according to fully qual classname
                 */

                if (newLine.indexOf("filename=\"") != -1) {
                    setFilename(new String(line, 0, i - 2));
                    if (filename == null) {
                        return;
                    }

                    // this is the file content
                    i = in.readLine(line, 0, 128);
                    // next line
                    i = in.readLine(line, 0, 128);
                    // blank line
                    i = in.readLine(line, 0, 128);
                    newLine = new String(line, 0, i);
                    // add the prefix to the filename

                    PrintWriter pw = null;
                    if (realSavePath.length() > 0) {
                        pw = new PrintWriter(new BufferedWriter(
                                new FileWriter((realSavePath == null ? "" : realSavePath) + filename)));
                    } else {
                        filename = filenamePrefix + filename;
                        pw = new PrintWriter(new BufferedWriter(
                                new FileWriter((savePath == null ? "" : savePath) + filename)));
                    }

                    while (i != -1 && !newLine.startsWith(boundary)) {
                        // the problem is the last line of the file content
                        // contains the new line character.
                        // So, we need to check if the current line is
                        // the last line.
                        i = in.readLine(line, 0, 128);
                        if ((i == boundaryLength + 2 || i == boundaryLength + 4) // +
                                // 4
                                // is
                                // eof
                                && (new String(line, 0, i).startsWith(boundary))) {

                            pw.print(newLine.substring(0, newLine.length() - 2));
                        } else {
                            pw.print(newLine);
                        }

                        newLine = new String(line, 0, i);
                    }
                    pw.close();

                }

            }

        }

        i = in.readLine(line, 0, 128);
    } // end while
      // if (realSavePath.length() > 0) {
      // LOGGER.info("User Configuration file received and saved at: "
      // + realSavePath + filename);
      // } else {
      // LOGGER.info("User Configuration file received and saved at: "
      // + savePath + filename);
      // }
}

From source file:org.n52.wps.webadmin.ConfigUploadBean.java

private void handleUpload(ServletInputStream in, String type, String newLine) throws Exception {

    if (type.equals("javaProcess")) {

        // then parse classname
        String classname = newLine;
        String[] classnameArr = classname.replace(".", ",").split(",");
        String classdir = new String();
        for (int c = 0; c < classnameArr.length - 1; c++) {
            if (c == 0) {
                classdir = classdir + classnameArr[c];
            } else {
                classdir = classdir + File.separator + classnameArr[c];
            }/*from w w w.ja v  a 2 s .  c o  m*/

        }
        realSavePath = new File(savePath).getParentFile() + "/WEB-INF/classes/";
        realSavePath = realSavePath + classdir + File.separator;
        new File(realSavePath).mkdirs();

        while (i != -1) {

            newLine = new String(line, 0, i);
            System.out.println(newLine);

            if (newLine.startsWith("Content-Disposition: form-data; name=\"")) {
                if (newLine.contains("processFile")) {
                    // we upload files not config docuements. Therefore
                    // store is
                    // somewhere else.
                    // realSavePath = new
                    // File(savePath).getParentFile().getAbsolutePath()+"/WEB-INF/classes/";

                    /**
                     * TODO: dir structure according to fully qual classname
                     */

                    if (newLine.indexOf("filename=\"") != -1) {
                        setFilename(new String(line, 0, i - 2));
                        if (filename == null) {
                            return;
                        }

                        // this is the file content
                        i = in.readLine(line, 0, 128);
                        // next line
                        i = in.readLine(line, 0, 128);
                        // blank line
                        i = in.readLine(line, 0, 128);
                        newLine = new String(line, 0, i);
                        // add the prefix to the filename

                        PrintWriter pw = null;
                        if (realSavePath.length() > 0) {
                            pw = new PrintWriter(new BufferedWriter(
                                    new FileWriter((realSavePath == null ? "" : realSavePath) + filename)));
                        } else {
                            filename = filenamePrefix + filename;
                            pw = new PrintWriter(new BufferedWriter(
                                    new FileWriter((savePath == null ? "" : savePath) + filename)));
                        }

                        while (i != -1 && !newLine.startsWith(boundary)) {
                            // the problem is the last line of the file
                            // content
                            // contains the new line character.
                            // So, we need to check if the current line is
                            // the last line.
                            i = in.readLine(line, 0, 128);
                            if ((i == boundaryLength + 2 || i == boundaryLength + 4) // +
                                    // 4
                                    // is
                                    // eof
                                    && (new String(line, 0, i).startsWith(boundary))) {

                                pw.print(newLine.substring(0, newLine.length() - 2));
                            } else {
                                pw.print(newLine);
                            }

                            newLine = new String(line, 0, i);
                        }
                        pw.close();
                    }

                }

            }

            i = in.readLine(line, 0, 128);
        } // end while
        if (realSavePath.length() > 0) {
            LOGGER.info("User Configuration file received and saved at: " + realSavePath + filename);
        } else {
            LOGGER.info("User Configuration file received and saved at: " + savePath + filename);
        }
        if (realSavePath.length() > 0) {
            compile(realSavePath + filename);
        }

    } else if (type.equals("rScript")) {
        // if processName the filename is used as ID, otherwise the script will be
        // renamed because r process IDs are derived from the filenames
        String processName = newLine.trim();

        /*
         * FIXME This is very dirty. Changed from staticly referencing the
         * 52n-wps-r module (!!) to generic string property resolving.
         * Nevertheless, this is sort of hard-coded. The webadmin module
         * should be completely separated from others.
         */
        String scriptDir = "";
        Property[] rConfig = WPSConfig.getInstance()
                .getPropertiesForRepositoryClass("org.n52.wps.server.r.LocalRAlgorithmRepository");
        for (Property property : rConfig) {
            if (property.getName().equalsIgnoreCase("R_scriptDirectory")) {
                scriptDir = property.getStringValue();
            }
        }

        File basedir = new File(savePath).getParentFile();
        realSavePath = new File(basedir, scriptDir).getAbsolutePath() + File.separator;
        new File(realSavePath).mkdirs();

        while (i != -1) {

            newLine = new String(line, 0, i);
            System.out.println(newLine);

            if (newLine.startsWith("Content-Disposition: form-data; name=\"")) {
                if (newLine.contains("rProcessFile")) {

                    if (newLine.indexOf("filename=\"") != -1) {

                        // filename is either the process name or the
                        // original file name
                        if (processName != null && !processName.isEmpty()) {
                            filename = processName + ".R";
                        } else
                            setFilename(new String(line, 0, i - 2));

                        if (filename == null) {
                            return;
                        }

                        // this is the file content
                        i = in.readLine(line, 0, 128);
                        // next line
                        i = in.readLine(line, 0, 128);
                        // blank line
                        i = in.readLine(line, 0, 128);
                        newLine = new String(line, 0, i);
                        // add the prefix to the filename

                        PrintWriter pw = null;
                        File destFile = null;
                        if (realSavePath.length() > 0) {
                            destFile = new File((realSavePath == null ? "" : realSavePath) + filename);
                            pw = new PrintWriter(new BufferedWriter(new FileWriter(destFile)));
                        } else {
                            filename = filenamePrefix + filename;
                            destFile = new File((savePath == null ? "" : savePath) + filename);
                            pw = new PrintWriter(new BufferedWriter(new FileWriter(destFile)));
                        }

                        while (i != -1 && !newLine.startsWith(boundary)) {
                            // the problem is the last line of the file
                            // content
                            // contains the new line character.
                            // So, we need to check if the current line is
                            // the last line.
                            i = in.readLine(line, 0, 128);
                            if ((i == boundaryLength + 2 || i == boundaryLength + 4) // +
                                    // 4
                                    // is
                                    // eof
                                    && (new String(line, 0, i).startsWith(boundary))) {

                                pw.print(newLine.substring(0, newLine.length() - 2));
                            } else {
                                pw.print(newLine);
                            }

                            newLine = new String(line, 0, i);
                        }
                        pw.close();

                    }

                    /*
                     * FIXME This is very dirty. The webadmin module should
                     * be completely separated from others. This one points
                     * out the need for a generic
                     * "reload your configuration" convenience method.
                     * Changed to java Reflections to remove the static
                     * 52n-wps-r module reference (though, very hardcoded).
                     */
                    {
                        LOGGER.info("R script uploaded, call to RPropertyChangeManager");
                        Class<?> clazz = Class.forName("org.n52.wps.server.r.RPropertyChangeManager");
                        Method method = clazz.getMethod("getInstance", null);
                        Object instance = method.invoke(null, null);
                        Method method2 = instance.getClass().getMethod("updateRepositoryConfiguration", null);
                        method2.invoke(instance, null);
                        // RPropertyChangeManager rmanager =
                        // RPropertyChangeManager.getInstance();
                        // LOGGER.info("R script uploaded, call to RPropertyChangeManager");
                        // rmanager.addUnregisteredScripts();
                    }

                }

            }

            i = in.readLine(line, 0, 128);
        } // end while
        if (realSavePath.length() > 0) {
            LOGGER.info("User Configuration file received and saved at: " + realSavePath + filename);
        } else {
            LOGGER.info("User Configuration file received and saved at: " + savePath + filename);
        }
        if (realSavePath.length() > 0) {
        }
    }

}