Blankman
Blankman

Reputation: 267120

How can I abort a request if the XML file is too large?

In my servlet, I am currently setting the XML file to a variable like this:

String xmlFileAsString = CharStreams.toString(new   
         InputStreamReader(request.getInputStream(), "UTF-8"));

Now after this line I can check if the file size is too large etc., but that means the entire file has already been stream and loaded into memory.

Is there a way for me to get the input stream, but while this is streaming the file it should abort if the file size is say above 10MB?

Upvotes: 1

Views: 172

Answers (1)

helderdarocha
helderdarocha

Reputation: 23637

You can read the stream sequentially and count the number of characters read. First don't use CharStreams since it already reads the entire file. Create an InputStreamReader object:

InputStreamReader reader;
        reader = new InputStreamReader(request.getInputStream(), "UTF-8");

A variable to keep track of the char count:

long charCount = 0;

And then the code to read the file:

char[] cbuf = new char[10240]; // size of the read buffer
int charsRead = reader.read(cbuf); // read first set of chars
StringBuilder buffer = new StringBuilder(); // accumulate the data read here

while(charsRead > 0) {
    buffer.append(cbuf, 0, charsRead);
    if (charCount > LIMIT) { // define a LIMIT constant with your size limit
        throw new XMLTooLargeException(); // treat the problem with an exception
    }
}
String xmlFileAsString = buffer.toString(); //if not too large, get the string

Upvotes: 1

Related Questions