You are viewing a plain text version of this content. The canonical link for it is here.
Posted to users@tomcat.apache.org by trojansnake12 <bo...@swbell.net> on 2009/06/01 21:15:02 UTC

RE: Debian Tomcat Fail

Basically, what I am sending to the server is a byte array that is a picture
taken from a cell-phone camera.  My client-side code looks like this: 

			url = new URL(urlString);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod("POST");
		

			dos = new DataOutputStream(connection.getOutputStream());
			dos.write(Global.rawImage);
			dos.close();

Now what I need the server to do, is to write this image to a file in the
directory /webapps/geosim/DRimages/.  Here is what I have:

doPost:
try {

			DataInputStream is = new DataInputStream(request.getInputStream());
			raw = new byte[800000];
			
			for(i=0; i<800000; i++) 
				raw[i] = '\0';

			i = 0;
			len = 0;
			
			while((i = is.read(raw)) != -1) {
				
			}
			file = new File(filePath + d.getTime() + ".jpg");
			fos = new FileOutputStream(file);
			fos.write(raw);
			fos.close();
			
			file = new File("../webapps/geosim/gen-html/DR.html");
			fos = new FileOutputStream(file, true);
			tag += new String(" \"./DRimages/" " + d.toString() + "::::" + coordsStr
+ "</img><br>\n");
			fos.write(tag.getBytes());
			fos.close();

You can ignore the coordsStr for now, that will be null until I find a way
of dealing with embedding the lat/long in the digital image.  Basically I
just want to write the image to the server-side directory
TOMCAT_HOME/webapps/geosim/DRimages/

Could you guys help show me how to do this using the ServletContext resource
handling?  I'm unfamiliar with how to do this.

mgainty wrote:
> 
> 
> post the code and we'll walk you thru it
> 
> no sweat 
> Martin 
> ______________________________________________ 
> Verzicht und Vertraulichkeitanmerkung/Note de déni et de confidentialité
>  
> Diese Nachricht ist vertraulich. Sollten Sie nicht der vorgesehene
> Empfaenger sein, so bitten wir hoeflich um eine Mitteilung. Jede unbefugte
> Weiterleitung oder Fertigung einer Kopie ist unzulaessig. Diese Nachricht
> dient lediglich dem Austausch von Informationen und entfaltet keine
> rechtliche Bindungswirkung. Aufgrund der leichten Manipulierbarkeit von
> E-Mails koennen wir keine Haftung fuer den Inhalt uebernehmen.
> Ce message est confidentiel et peut être privilégié. Si vous n'êtes pas le
> destinataire prévu, nous te demandons avec bonté que pour satisfaire
> informez l'expéditeur. N'importe quelle diffusion non autorisée ou la
> copie de ceci est interdite. Ce message sert à l'information seulement et
> n'aura pas n'importe quel effet légalement obligatoire. Étant donné que
> les email peuvent facilement être sujets à la manipulation, nous ne
> pouvons accepter aucune responsabilité pour le contenu fourni.
> 
> 
> 
> 
>> Date: Thu, 28 May 2009 14:51:28 -0700
>> From: boppnick@swbell.net
>> To: users@tomcat.apache.org
>> Subject: RE: Debian Tomcat Fail
>> 
>> 
>> Sorry, this code was provided to me by a graduate student (I'm a lowly
>> freshman).  Still very new to all of this, I'll look into that.
>> 
>> 
>> Caldarale, Charles R wrote:
>> > 
>> >> From: trojansnake12 [mailto:boppnick@swbell.net]
>> >> Subject: RE: Debian Tomcat Fail
>> >> 
>> >> File myGifImage = new
>> File("../webapps/geosim/WEB-INF/images/test.jpg");
>> > 
>> > Very bad form.  The servlet container (Tomcat) is under no obligation
>> to
>> > provide *any* access to the underlying file system (if there is one),
>> > other than to a scratch area.  You should be using
>> > ServletContext.getResourceAsStream() rather than expecting File objects
>> to
>> > work.
>> > 
>> >  - Chuck
>> > 
>> > 
>> > THIS COMMUNICATION MAY CONTAIN CONFIDENTIAL AND/OR OTHERWISE
>> PROPRIETARY
>> > MATERIAL and is thus for use only by the intended recipient. If you
>> > received this in error, please contact the sender and delete the e-mail
>> > and its attachments from all computers.
>> > 
>> > 
>> > ---------------------------------------------------------------------
>> > To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
>> > For additional commands, e-mail: users-help@tomcat.apache.org
>> > 
>> > 
>> > 
>> 
>> -- 
>> View this message in context:
>> http://www.nabble.com/Debian-Tomcat-Fail-tp23734947p23770783.html
>> Sent from the Tomcat - User mailing list archive at Nabble.com.
>> 
>> 
>> ---------------------------------------------------------------------
>> To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
>> For additional commands, e-mail: users-help@tomcat.apache.org
>> 
> 
> _________________________________________________________________
> Hotmail® has a new way to see what's up with your friends.
> http://windowslive.com/Tutorial/Hotmail/WhatsNew?ocid=TXT_TAGLM_WL_HM_Tutorial_WhatsNew1_052009
> 

-- 
View this message in context: http://www.nabble.com/Debian-Tomcat-Fail-tp23734947p23820223.html
Sent from the Tomcat - User mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org


Re: Debian Tomcat Fail

Posted by trojansnake12 <bo...@swbell.net>.
Thanks Chris.  I don't doubt this is sloppy, but I was able to change around
some things and get this working properly.  I appreciate the help.
-- 
View this message in context: http://www.nabble.com/Debian-Tomcat-Fail-tp23734947p23823034.html
Sent from the Tomcat - User mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org


RE: Debian Tomcat Fail

Posted by "Caldarale, Charles R" <Ch...@unisys.com>.
> From: Christopher Schultz [mailto:chris@christopherschultz.net]
> Subject: Re: Debian Tomcat Fail
> 
> > 			i = 0;
> > 			len = 0;
> >
> > 			while((i = is.read(raw)) != -1) {
> >
> > 			}
> 
> That's an interesting idiom. I had to read it several times to convince
> myself that it would actually work.

Depends on what you mean by "work"; it's not terribly useful, as written - each pass through the while loop will read the next chunk of data into offset 0 of the array, thereby losing anything that's come before.  If it works at all, it can only be due to something upstream buffering the data first, and then delivering it in one chunk.  What would be useful is this:

			i = 0;
			len = 0;
			while((i = is.read(raw, len, raw.length - len)) != -1) {
			  len += i;
			  if (len == raw.length) throw new TooBigException();
			}

> >               fos.write(raw);

This also isn't terribly effective, since it writes the whole 800000 bytes out, regardless of how many were actually read.  If the modified read sequence above is used, the write should be:

			fos.write(raw, 0, len);

But back to the main point: as Chris implied, writing to the webapps directory is *never* a good idea; you must store the uploaded files outside of Tomcat's directory structure if you ever want this to be reliable.

 - Chuck


THIS COMMUNICATION MAY CONTAIN CONFIDENTIAL AND/OR OTHERWISE PROPRIETARY MATERIAL and is thus for use only by the intended recipient. If you received this in error, please contact the sender and delete the e-mail and its attachments from all computers.



Re: Debian Tomcat Fail

Posted by Christopher Schultz <ch...@christopherschultz.net>.
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

TS,

On 6/1/2009 3:15 PM, trojansnake12 wrote:
> Basically, what I am sending to the server is a byte array that is a picture
> taken from a cell-phone camera.  My client-side code looks like this: 
> 
> 			url = new URL(urlString);
> 			connection = (HttpURLConnection) url.openConnection();
> 			connection.setDoInput(true);
> 			connection.setDoOutput(true);
> 			connection.setUseCaches(false);
> 			connection.setRequestMethod("POST");

Don't forget to set the Content-Type and Content-Length headers like this:

connection.setRequestProperty("Content-Type",
                              "image/jpeg");
connection.setRequestProperty("Content-Length",
                              String.valueOf(filesize));

> 			dos = new DataOutputStream(connection.getOutputStream());
> 			dos.write(Global.rawImage);

I'm not sure what Global.rawImage is, but you might want to stream the
upload with a small buffer so you don't have to keep the entire image in
memory. The use of an object like "Global" leads me to believe that some
sloppy programming is at work, here... a Global image? Hmm...

> 			dos.close();

It can't hurt to flush() this stream before closing it. You didn't post
any of the other code, but error handling is essential on the client.

> Now what I need the server to do, is to write this image to a file in the
> directory /webapps/geosim/DRimages/.

You may be barred from doing this based upon the deployment semantics of
the web application. It's better to plan ahead for that eventuality.
What I like to do is use <init-param> elements in my web.xml to define
things like this:

<servlet>
   <servlet-name>myImageUploaderServlet</servlet-name>
   <servlet-class>[whatever]</servlet-class>
   <init-param>
      <param-name>imageUploadPath</param-name>
      <param-value>/full/path/to/destination/directory</param-value>
   </init-param>
</servlet>

You can get the value of the init-param like this:

super.getInitParameter("imageUploadPath")

> 			DataInputStream is = new DataInputStream(request.getInputStream());

A DataInputStream is not appropriate for this application:
DataInputStream is used to read Java primitives from a byte stream.
Since you aren't reading anything but bytes, you should use a simpler
form of InputStream. BufferedInputStream is a good choice, though the
ServletInputStream returned by request.getInputStream might already be
buffered, so you either get nothing, or get worse performance by having
two differently-sized buffers.

> 			raw = new byte[800000];

Again, I recommend a streaming approach... no need to load the entire
image into memory before writing it to the disk.

> 			for(i=0; i<800000; i++) 
> 				raw[i] = '\0';

Why bother zeroing-out this array? Java will already give you an array
of bytes whose values are '\0' (or just zero, if you prefer).

> 			i = 0;
> 			len = 0;
> 			
> 			while((i = is.read(raw)) != -1) {
> 				
> 			}

That's an interesting idiom. I had to read it several times to convince
myself that it would actually work. I'm still not quite convinced, but I
guess InputStream.read(byte[]) is guaranteed to block until enough bytes
have arrived to full the buffer, or the byte stream ends.

If your image is bigger than 800000 bytes, you'll have a problem, though.

> 			file = new File(filePath + d.getTime() + ".jpg");

Depending on what 'd' is, this might run the risk of overwriting files.

> 			fos = new FileOutputStream(file);
> 			fos.write(raw);
> 			fos.close();

If you stream this, you'll want to buffer the output. Also, flush()ing
never hurt anybody :)

> Could you guys help show me how to do this using the ServletContext resource
> handling?  I'm unfamiliar with how to do this.

Since you're /writing/ files and not reading them, Chuck's suggestion of
using getResourceAsStream isn't going to help, because you need
something like "putResourceAsStream" which doesn't exist.

I recommend my technique shown above using init-params, and putting the
destination directory /outside/ the webapp deployment directory. In the
off change that you re-deploy your web application at some point, you
might end up deleting all the files in the deployment directory. This
technique encourages you to put the files elsewhere, possibly protecting
yourself.

Good luck,
- -chris
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAkokSzUACgkQ9CaO5/Lv0PCaBgCfQSKaHsei1TaaHG/Tdpr9cOYp
s0AAn1Epx3xvpV0ZMk9cV7W6hXeVHzZ6
=dXp0
-----END PGP SIGNATURE-----

---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org