Initial revision
[old-projects.git] / ekit / com / hexidec / ekit / materials / FAQ_Factory / TaggingDriver / TaggingDriverServlet.java
1 //{{SERVLET_IMPORT_STMTS
2 package FAQ_Factory.TaggingDriver;
3 import versata.vfc.html.*;
4 import versata.vfc.html.servlet.*;
5 import versata.vfc.html.common.*;
6 import versata.common.*;
7 import versata.vls.*;
8 import java.util.*;
9 import java.math.BigDecimal;
10 import java.io.*;
11 import javax.servlet.*;
12 import javax.servlet.http.*;
13 import java.rmi.RemoteException;
14
15 //END_SERVLET_IMPORT_STMTS}}
16 import support.*;
17
18 //{{SERVLET_CLASS_DECL
19 public class TaggingDriverServlet extends TaggingDriverBaseServlet
20 //END_SERVLET_CLASS_DECL}}
21 {
22 JustAskConstants constants = new JustAskConstants();
23 //private static final String[] legalImageExtensions =
24 // new String[] { ".bmp", ".emf", ".gif", ".jpg", ".pcx", ".psp", ".tif", ".tiff", ".wmf", ".wpg" };
25 //private static final String[] legalFileExtensions =
26 // new String[] { ".doc", ".htm", ".pdf", ".txt" };
27 // TaggingDriverServlet Class Constructor
28 //{{SERVLET_CLASS_CTOR
29 public TaggingDriverServlet ()
30 //END_SERVLET_CLASS_CTOR}}
31 {
32 super();
33 }
34
35 public void loadLoginPage(boolean failed, HttpServletResponse res, HttpServletRequest req, String msg)
36 throws IOException
37 {
38 //{{SERVLET_LOADLOGINPAGE
39 // Load login page. If previous attempt failed, load page with failed message.
40 // This method will be generated in gen'd servlet and user can
41 // add code for custom login there, or it can be gen'd to supress login
42 super.loadLoginPage(failed, res, req,msg);
43 PrintWriter toClient = res.getWriter();
44 String params = req.getQueryString();
45
46 //END_SERVLET_LOADLOGINPAGE}}
47 }
48
49
50 public String getFileLocation()
51 {
52 return getDefaultFileLocation();
53
54 }
55
56 public String getBaseURL(HttpServletRequest req, String packageName, String clientAppName)
57 {
58 return super.getBaseURL(req, packageName, clientAppName);
59 }
60 public String getServletURL(HttpServletRequest req)
61 {
62 return HttpUtils.getRequestURL(req).toString();
63
64 }
65
66 public PLSORBSession doLogin(HttpServletRequest req)
67 throws TierSessionLimitException, RemoteException
68 {
69 return doDefaultLogin(req);
70 }
71
72 public void loadStartPage()
73 {
74 // Right now, this is done by calling session.start, which calls app.start.
75 // We may want this here for the case when developer wants to customize.
76 }
77
78 ///////////////////////////////////////////////////////////////////
79 // This method handles the POST'ing of form data.
80 // This is for the purpose of allowing users to have INPUT controls
81 // of type FILE. When a form contains such a control, the data must be
82 // posted in multipart format, which Jade does not handle by default.
83 // The strategy is to catch the POST. If it is a regular post, just pass
84 // it to super.
85 // If it is a multipart post, we parse the binary stream and build a new
86 // HttpServletRequest containing all the parameters except of course
87 // the contents of the files, and submit that request to super.
88 //
89 // Remember that this method is invoked for every post, i.e. anytime the
90 // user clicks any button. Since we typically want special action only
91 // for a save, we look at the query_string parameter to determine whether
92 // the query is a save query. If it's not, we ignore all the file-related
93 // fields.
94 //
95 // The form can have any number of FILE inputs. For each such input, this
96 // will read the file into a temporary file. The name of that temporary file
97 // will be put in a field whose is that of the FILE input with "_ServerFileName"
98 // appended. The name of the file on the client will be put in a field whose
99 // name is that of the FILE input with "_ClientFileName" appended.
100 //
101 // Note that there is no way (apparently) to set the value of a FILE input,
102 // which is why the client-side file name is returned in a separate field.
103 public void doPost(javax.servlet.http.HttpServletRequest req,
104 javax.servlet.http.HttpServletResponse res)
105 throws javax.servlet.ServletException,
106 java.io.IOException
107 {
108 String contentType = req.getContentType();
109 //String postedOrgID = "didntgetit";
110 //boolean gotStartOfOrg = false;
111 // If this is a regular POST, let super handle it
112 if(contentType.startsWith("application/x-www-form-urlencoded"))
113 {
114 super.doPost(req, res);
115 return;
116 }
117 // If it's not a regular post, it better be multipart
118 if( ! contentType.startsWith("multipart/form-data"))
119 {
120 throw new ServletException("POST content type was neither "
121 + "application/x-www-form-urlencoded nor "
122 + "multipart/form-data, which is impossible");
123 }
124 // Figure out the directory where the images are placed
125 String tmpDir = constants.getImageDir();
126 // String tmpDir = "C:\\Program Files\\Vision\\Jade4.1\\JWS\\public_html\\FAQ_Factory\\FAQ\\images\\";
127 System.err.println("**Temporary dir is : " + tmpDir);
128 // First read the separator from the contentType, which looks
129 // like "multipart/form-data; boundary=---------------------------7cf3065520250"
130 // Be careful : the number of dashes is not exactly as shown in the
131 // contentType, it actually has two more
132 int sepIndex = contentType.lastIndexOf('=');
133 if(sepIndex == -1)
134 throw new ServletException("Multipart POST does not have " +
135 "a valid contentType");
136 String separator = contentType.substring(sepIndex + 1);
137 if( ! separator.startsWith("----------"))
138 throw new ServletException("Multipart POST contentType "
139 + "does not have a valid separator");
140 separator = "--" + separator;
141 System.out.println("***Separator is : " + separator);
142 // We store the name and value of all the parameters in this
143 // hashtable, which is then given to the FileServletRequest.
144 Hashtable reqHash = new Hashtable();
145 // Read the total length of the binary stream, we'll use that
146 // to make sure we're reading the right amount.
147 // Note : this can be -1 in some cases, in which case
148 // you just have to read 'til you can't read no more
149 int contentLength = req.getContentLength();
150 System.out.println("***getContentLength: " + contentLength);
151 // Now read the parameters. Each parameter has the format :
152 // Separator : -----123456
153 // Parameter name
154 // Blank line
155 // Parameter value (can be multiple lines, ends with next separator)
156 // The last parameter ends with a separator.
157 System.out.println("***InputStream :");
158 ServletInputStream inStr = req.getInputStream();
159 byte buf[] = new byte[1000];
160 int byteCount = 0;
161 int numRead;
162 String currentAttribName;
163 boolean isSaveQuery = false;
164 boolean isUnique = true;
165 boolean isDocManage = false;
166 // Read the first separator
167 numRead = inStr.readLine(buf, 0, 1000);
168 byteCount += numRead;
169 String strLine = new String(buf, 0, numRead);
170 if( ! strLine.startsWith(separator))
171 {
172 throw new ServletException("POST does not "
173 + "start with separator line, byte " + byteCount);
174 }
175 // Now go over the parameters
176 while (numRead > 0)
177 {
178 // Last one ? ContentLength could be -1
179 if(byteCount == contentLength)
180 break;
181 // Read the raw parameter name
182 numRead = inStr.readLine(buf, 0, 1000);
183 if(numRead == -1)
184 break;
185 byteCount += numRead;
186 strLine = new String(buf, 0, numRead);
187 System.out.println("***Raw parameter name : " + strLine);
188 // Figure out if the parameter is a FILE input. The name of
189 // the parameter looks like :
190 // Content-Disposition: form-data; name="txtT1DocName"
191 // or in the case of a file parameter :
192 // Content-Disposition: form-data; name="fileContents"; filename="c:\temp\foo.txt"
193 boolean isFileAttrib = false;
194 int semiColIndex = strLine.lastIndexOf(';');
195 if(semiColIndex == -1)
196 throw new ServletException("POST - bad parameter name");
197 String localFileName = "";
198 String newLocalFileName = "";
199
200 if(strLine.substring(semiColIndex, semiColIndex + 6).compareTo("; file") == 0)
201 {
202 isFileAttrib = true;
203 int filenameIndex = strLine.lastIndexOf("; filename=\"");
204 //if(filenameIndex == -1)
205 // throw new ServletException("POST : no local file name");
206 localFileName = strLine.substring(filenameIndex + 12,
207 strLine.length() - 3);
208 System.out.println("**Param is a file, local file : " + localFileName);
209 if(localFileName.length() == 0)
210 {
211 System.out.println("***There is no file name");
212 // localFileName = "xyz";
213 // isFileAttrib = false;
214 // break;
215 }
216 // JGW
217 // after we have the local file name. Just pull out the filename and append a rnd
218 // value to the file
219 int lastdash = 0;
220 int lfl = localFileName.length();
221 for (int ctr=1; ctr < (lfl - 3); ctr++)
222 {
223 if(localFileName.substring(ctr,ctr+1).compareTo("\\") == 0)
224 {
225 System.out.println("++++lastdash = "+ctr);
226 lastdash = ctr;
227 }
228 System.out.println(ctr + " " +lfl);
229 }
230 int subval = 0;
231 if(lastdash == 0)
232 subval = localFileName.length();
233 else
234 subval = (localFileName.length() - lastdash) - 1;
235
236 if(localFileName.length() > 0)
237 {
238 File fp = null;
239 newLocalFileName = localFileName.substring(lfl - subval, lfl);
240 // end JGW
241 fp = new File(tmpDir + newLocalFileName);
242 if(fp.exists() && !isDocManage)
243 {
244 res.setContentType("text/html");
245
246 PrintWriter toClient = res.getWriter();
247
248 String myJscript ="<h3><center><script language=Javascript>";
249 myJscript = myJscript + " alert('This file already exists.');";
250 myJscript = myJscript + " </script>";
251 myJscript = myJscript + " </center></h3>";
252
253 toClient.println(myJscript);
254
255 isUnique = false;
256 }
257 }
258 }
259 // Extract the name of the parameter from the line
260 int openQuoteIndex = strLine.indexOf('=') + 2;
261 if(openQuoteIndex == -1)
262 throw new ServletException("POST : could not find "
263 + "beginning of name of parameter");
264 int closeQuoteIndex = strLine.indexOf('"', openQuoteIndex);
265 if(closeQuoteIndex == -1)
266 throw new ServletException("POST : could not find "
267 + "end of name of parameter");
268 currentAttribName = strLine.substring(openQuoteIndex, closeQuoteIndex);
269 System.out.println("***New attrib name : " + currentAttribName);
270 // Different behavior between Netscape and IE : IE will
271 // still send a content type descriptor if there is no file,
272 // but Netscape won't.
273 // Our strategy to cope with this is, if the file name is empty,
274 // we just skip over the contents of the file parameter
275 if(isFileAttrib && (localFileName.length() == 0))
276 {
277 while (true)
278 {
279 // Ignore everything until the market
280 byte buf2[] = new byte[1000];
281 int numRead2 = inStr.readLine(buf2, 0, 1000);
282 byteCount += numRead2;
283 String attVal2 = new String(buf2, 0, numRead2);
284 if(attVal2.startsWith(separator))
285 break;
286 }
287 }
288 // Read the value. If it's a file, there could be a
289 // massive amount of data
290 else if(isFileAttrib && (localFileName.length() > 0))
291 {
292 // Read the content type descriptor
293 numRead = inStr.readLine(buf, 0, 1000);
294 byteCount += numRead;
295 strLine = new String(buf, 0, numRead);
296 if( ! strLine.startsWith("Content-Type:"))
297 {
298 throw new ServletException("POST : expected content type "
299 + "descriptor");
300 }
301 // Read the blank line
302 numRead = inStr.readLine(buf, 0, 1000);
303 byteCount += numRead;
304 if(numRead > 2)
305 {
306 throw new ServletException("POST : unexpected data in "
307 + "file parameter line (not blank)");
308 }
309
310 String fullFileName = tmpDir + newLocalFileName;
311 System.out.println("**Reading file attribute into : " + fullFileName);
312 BufferedOutputStream outFile = null;
313 try {
314 if(isSaveQuery && isUnique)
315 {
316 FileOutputStream outStr = new FileOutputStream(fullFileName);
317 outFile = new BufferedOutputStream(outStr);
318 }
319 }
320 catch (IOException e)
321 {
322 throw new ServletException("POST : error while opening data file : " + fullFileName);
323 }
324 numRead = inStr.readLine(buf, 0, 1000);
325 while (true)
326 {
327 //System.out.println("**Reading file value");
328 byteCount += numRead;
329 if(numRead < 0)
330 throw new ServletException("POST : data for file "
331 + "was incomplete");
332 byte buf2[] = new byte[1000];
333 int numRead2 = inStr.readLine(buf2, 0, 1000);
334 String attVal2 = new String(buf2, 0, numRead2);
335 // If this is the last line (because it's followed
336 // by a separator), trim off the last CR/LF
337 if(attVal2.startsWith(separator))
338 {
339 if(isSaveQuery && isUnique)
340 {
341 outFile.write(buf, 0, numRead - 2);
342 outFile.flush();
343 }
344 break;
345 }
346 else
347 {
348 if(isSaveQuery && isUnique)
349 {
350 outFile.write(buf, 0, numRead);
351 outFile.flush();
352 }
353 }
354 buf = buf2; // Thank goodness for garbage collection !
355 numRead = numRead2;
356 }
357 // Save the name of the file into the parameter
358 if(isSaveQuery)
359 {
360 // The value doesn't make it back into the file input
361 reqHash.put(currentAttribName, localFileName);
362 reqHash.put(currentAttribName + "_ClientFileName", localFileName);
363 reqHash.put(currentAttribName + "_ServerFileName", fullFileName);
364 }
365 }
366 else // Not a file : just a regular parameter
367 {
368 System.out.println("***Reading value of parameter");
369 // Read the blank line
370 numRead = inStr.readLine(buf, 0, 1000);
371 byteCount += numRead;
372 String s = new String(buf, 0, numRead);
373 System.out.println("**First param value line : " + s);
374 if(numRead > 2)
375 {
376 throw new ServletException("POST : unexpected data in "
377 + "parameter line (not blank)");
378 }
379 numRead = inStr.readLine(buf, 0, 1000);
380 String attVal = "";
381 // Is this a Save query ? Remember that for processing of files
382 String tmpVal = new String(buf, 0, numRead);
383 if(tmpVal.indexOf("UploadFile=") != -1)
384 {
385 System.out.println("***********************************This is a save query");
386 isSaveQuery = true;
387 }
388 while (true)
389 {
390 System.out.println("**Reading parameter value");
391 byteCount += numRead;
392 if(numRead < 0)
393 throw new ServletException("POST : data for parameter "
394 + "was incomplete");
395 byte buf2[] = new byte[1000];
396 int numRead2 = inStr.readLine(buf2, 0, 1000);
397 String attVal2 = new String(buf2, 0, numRead2);
398 // If this is the last line (because it's followed
399 // by a separator), trim off the last CR/LF
400 if(attVal2.startsWith(separator))
401 {
402 attVal += new String(buf, 0, numRead - 2);
403 break;
404 }
405 else
406 {
407 attVal += new String(buf, 0, numRead);
408 }
409 buf = buf2; // Thank goodness for garbage collection !
410 numRead = numRead2;
411 }
412 // Skip the pseudo-fields that are filled with the
413 // names of the file
414 if(isSaveQuery)
415 {
416 if( ! ((currentAttribName.endsWith("_ClientFileName")) ||
417 (currentAttribName.endsWith("_ServerFileName"))))
418 {
419 reqHash.put(currentAttribName, attVal);
420 }
421 }
422 else
423 {
424 reqHash.put(currentAttribName, attVal);
425 }
426 System.out.println("**New attrib val : " + attVal);
427 if(attVal.length() > 5 && attVal.substring(0,6).equals("sysdir"))
428 {
429 int endIndex = attVal.indexOf('&');
430 System.out.println("sysdir " + attVal.substring(7,endIndex) + "\\");
431 tmpDir = tmpDir + attVal.substring(7,endIndex) + "\\";
432
433 if(attVal.substring(7,endIndex).indexOf("/") != -1)
434 isDocManage = true;
435 System.out.println("dir " + tmpDir);
436 System.out.println("doc management " + isDocManage);
437 File fp = new File(tmpDir);
438 if(!fp.exists())
439 {
440 System.out.println("doesn't exist");
441 fp.mkdirs();
442 System.out.println("created");
443 }
444 }
445 }
446 }
447 if(!isUnique)
448 {
449 reqHash.put("txtT1ImageUpload", "");
450 }
451 System.out.println("***End of InputStream : bytes " + byteCount);
452 System.out.println("***req " + req.toString());
453 System.out.println("***hash " + reqHash.toString());
454 FileServletRequest newRequest = new FileServletRequest(req, reqHash);
455 super.doPost(newRequest, res);
456 }
457
458 public void doGet(javax.servlet.http.HttpServletRequest req,
459 javax.servlet.http.HttpServletResponse res)
460 throws javax.servlet.ServletException,
461 java.io.IOException
462 {
463 if(req.getParameter("GetImages") != null &&
464 req.getParameter("ImageExtensions") != null)
465 {
466 // Get the image extensions from the request
467 Vector legalImageExtensions = new Vector();
468 StringTokenizer tok = new StringTokenizer(req.getParameter("ImageExtensions"), ":");
469 while (tok.hasMoreTokens())
470 {
471 legalImageExtensions.addElement(tok.nextToken());
472 }
473
474 // Return the directory listing
475 String currentSystem = req.getParameter("GetImages");
476 ObjectOutputStream out = new ObjectOutputStream(res.getOutputStream());
477 File dir = new File(constants.getImageDir() + currentSystem);
478 // For some reason implementing a FileNameFilter throws an IO exception
479 // even if it only returns true. So we implement one ourselves.
480 String[] validImageFiles = getValidImageFiles(dir.list(), legalImageExtensions);
481 if(validImageFiles != null)
482 {
483 out.writeObject(validImageFiles);
484 }
485 out.flush();
486 out.close();
487 }
488 else if(req.getParameter("GetFiles") != null &&
489 req.getParameter("FileExtensions") != null)
490 {
491 // Get the file extensions from the request
492 Vector legalFileExtensions = new Vector();
493 StringTokenizer tok = new StringTokenizer(req.getParameter("FileExtensions"), ":");
494 while (tok.hasMoreTokens())
495 {
496 legalFileExtensions.addElement(tok.nextToken());
497 }
498
499 // Return the directory listing
500 String currentSystem = req.getParameter("GetFiles");
501 ObjectOutputStream out = new ObjectOutputStream(res.getOutputStream());
502 File dir = new File(constants.getImageDir() + currentSystem);
503 // For some reason implementing a FileNameFilter throws an IO exception
504 // even if it only returns true. So we implement one ourselves.
505 String[] validFiles = getValidFiles(dir.list(), legalFileExtensions);
506 if(validFiles != null)
507 {
508 out.writeObject(validFiles);
509 }
510 out.flush();
511 out.close();
512 }
513 else
514 {
515 super.doGet(req, res);
516 }
517 }
518
519 private String[] getValidImageFiles(String[] files, Vector legalImageExtensions)
520 {
521
522 Vector validImageVector = new Vector();
523 for ( int fileIndex=0; fileIndex < files.length; fileIndex++)
524 {
525 for ( int i=0; i < legalImageExtensions.size(); i++)
526 {
527 if(files[fileIndex].endsWith((String)legalImageExtensions.elementAt(i)))
528 {
529 validImageVector.addElement(files[fileIndex]);
530 break;
531 }
532 }
533 }
534 if(validImageVector.isEmpty())
535 {
536 return null;
537 }
538 else
539 {
540 String[] result = new String[validImageVector.size()];
541 int i2 = 0;
542 Enumeration theFiles = validImageVector.elements();
543 while (theFiles.hasMoreElements())
544 {
545 result[i2++] = ((String)theFiles.nextElement());
546 }
547 return result;
548 }
549 }
550
551 private String[] getValidFiles(String[] files, Vector legalFileExtensions)
552 {
553
554 Vector validFileVector = new Vector();
555 for ( int fileIndex=0; fileIndex < files.length; fileIndex++)
556 {
557 for ( int i=0; i < legalFileExtensions.size(); i++)
558 {
559 if(files[fileIndex].endsWith((String)legalFileExtensions.elementAt(i)))
560 {
561 validFileVector.addElement(files[fileIndex]);
562 break;
563 }
564 }
565 }
566 if(validFileVector.isEmpty())
567 {
568 return null;
569 }
570 else
571 {
572 String[] result = new String[validFileVector.size()];
573 int i2 = 0;
574 Enumeration theFiles = validFileVector.elements();
575 while (theFiles.hasMoreElements())
576 {
577 result[i2++] = ((String)theFiles.nextElement());
578 }
579 return result;
580 }
581 }
582
583
584 }
585