001: package net.homeip.donaldm.testng;
002:
003: import java.io.BufferedInputStream;
004: import java.io.BufferedOutputStream;
005: import java.io.BufferedReader;
006: import java.io.ByteArrayInputStream;
007: import java.io.FileNotFoundException;
008: import java.io.IOException;
009: import java.io.InputStream;
010: import java.io.InputStreamReader;
011: import java.io.PrintWriter;
012: import java.lang.reflect.Method;
013: import java.net.URL;
014: import java.net.URLClassLoader;
015: import java.net.URLConnection;
016: import java.net.URLEncoder;
017: import java.security.KeyManagementException;
018: import java.security.KeyStoreException;
019: import java.security.NoSuchAlgorithmException;
020: import java.security.UnrecoverableKeyException;
021: import java.security.cert.CertificateException;
022: import java.util.jar.JarEntry;
023: import java.util.jar.JarOutputStream;
024:
025: import net.homeip.donaldm.httpdbase4j.FileHttpd;
026: import net.homeip.donaldm.httpdbase4j.FileStringTemplateHandler;
027: import net.homeip.donaldm.httpdbase4j.Http;
028: import net.homeip.donaldm.httpdbase4j.HttpResponse;
029: import net.homeip.donaldm.httpdbase4j.Httpd;
030: import net.homeip.donaldm.httpdbase4j.ArchiveHttpd;
031: import net.homeip.donaldm.httpdbase4j.ArchiveStringTemplateHandler;
032: import net.homeip.donaldm.httpdbase4j.Postable;
033: import net.homeip.donaldm.httpdbase4j.Request;
034: import net.homeip.donaldm.httpdbase4j.TemplatableAdapter;
035: import net.homeip.donaldm.testng.templates.SelItem;
036:
037: import org.antlr.stringtemplate.StringTemplate;
038: import org.antlr.stringtemplate.StringTemplateGroup;
039: import org.testng.annotations.Test;
040:
041: import com.sun.net.httpserver.Headers;
042: import com.sun.net.httpserver.HttpExchange;
043:
044: import de.schlichtherle.io.File;
045:
046: public class TestHttpd
047: //====================
048: {
049: private java.io.File m_homeDir = new File("test/htdocs");
050: private String m_homeArchiveDirName = "test/htdocs";
051: private int m_port = 8088;
052: private Httpd m_httpd = null;
053:
054: private static final String LF = System
055: .getProperty("line.separator");
056:
057: @Test(groups={"static","All"})
058: public void startStatic() throws IOException, NoSuchFieldException
059: //----------------------------------------------------
060: {
061: m_httpd = new FileHttpd(m_homeDir, 10);
062: m_httpd.setVerbose(true);
063: m_httpd.setLogger(System.err);
064: m_httpd.start(m_port, "/");
065:
066: setupStaticFiles(m_homeDir);
067: }
068:
069: // Also tests combined css/js requests
070: private void setupStaticFiles(java.io.File homeDir)
071: throws FileNotFoundException
072: //-----------------------------------------------------------------------
073: {
074: deleteDir(homeDir);
075: homeDir.mkdirs();
076: java.io.File f = new File(homeDir, "basic.html");
077: f.delete();
078: PrintWriter ps = new PrintWriter(f);
079: ps.print(getBasicHTML());
080: ps.close();
081:
082: f = new File(m_homeDir, "style.css");
083: f.delete();
084: ps = new PrintWriter(f);
085: ps.print(getPageCSS(0));
086: ps.close();
087:
088: f = new File(m_homeDir, "style2.css");
089: f.delete();
090: ps = new PrintWriter(f);
091: ps.print(getPageCSS(1));
092: ps.close();
093:
094: f = new File(m_homeDir, "page.html");
095: f.delete();
096: ps = new PrintWriter(f);
097: ps.print(getPageHTML());
098: ps.close();
099:
100: }
101:
102: @Test(groups={"static","All"},dependsOnMethods={"startStatic"})
103: public void testStatic() throws IOException, NoSuchFieldException
104: //----------------------
105: {
106: testBasic(m_port, "http");
107: testPage(m_port, "http");
108: stopServer();
109: }
110:
111: @Test(groups={"staticssl","All"})
112: public void startSSL() throws IOException, NoSuchFieldException,
113: UnrecoverableKeyException, KeyManagementException,
114: KeyStoreException, NoSuchAlgorithmException,
115: CertificateException
116: //----------------------------------------------------
117: {
118: m_httpd = new FileHttpd(m_homeDir, 10);
119: m_httpd.setVerbose(true);
120: m_httpd.setLogger(System.err);
121: m_httpd.start(m_port, "/", null, null);
122:
123: setupStaticFiles(m_homeDir);
124: }
125:
126: // Won't work until TODO: HttpdLite-00001 is resolved
127: @Test(groups={"staticssl","All"},dependsOnMethods={"startSSL"})
128: public void testStaticSSL() throws IOException,
129: NoSuchFieldException
130: //------------------------------------------------------------------
131: {
132: testBasic(m_port, "https");
133: testPage(m_port, "https");
134: stopServer();
135: }
136:
137: @Test(groups={"overide","All"})
138: public void startOveride() throws IOException, NoSuchFieldException
139: //----------------------------------------------------
140: {
141: m_httpd = new TestOverideHttpd(m_homeDir, 10);
142: m_httpd.setVerbose(true);
143: m_httpd.setLogger(System.err);
144: m_httpd.start(m_port, "/");
145:
146: deleteDir(m_homeDir);
147: m_homeDir.mkdirs();
148: java.io.File f = new File(m_homeDir, "test-overide.txt");
149: PrintWriter ps = new PrintWriter(f);
150: ps.print("Overide test success");
151: ps.close();
152: f = new File(m_homeDir, "no.such.file");
153: f.delete();
154: }
155:
156: class TestOverideHttpd extends FileHttpd
157: //==================================
158: {
159: private String content = null;
160:
161: public TestOverideHttpd(java.io.File homeDir, int poolSize) {
162: super (homeDir, poolSize);
163: }
164:
165: public Request onFileNotFound(long id, HttpExchange ex,
166: Request request) {
167: if (request.getName().compareTo("no.such.file") == 0) {
168: java.io.File f = new File(m_homeDir, "no.such.file");
169: try {
170: PrintWriter ps = new PrintWriter(f);
171: ps.print("I think therefore I am.");
172: ps.close();
173: } catch (Exception e) {
174: return null;
175: }
176: return request;
177: }
178: return null;
179: }
180:
181: public HttpResponse onServeHeaders(long id, HttpExchange ex,
182: Request request) {
183: if (request.getName().compareTo("test-overide.txt") == 0) {
184: BufferedReader br = new BufferedReader(
185: new InputStreamReader(request.getStream()));
186: content = "<HTML><HEAD></HEAD><BODY><P>";
187: try {
188: content += br.readLine() + "</P></BODY></HTML>";
189: } catch (Exception e) {
190: System.err.println("Error reading stream: "
191: + e.getMessage());
192: return null;
193: }
194: content += "</P></BODY></HTML>";
195: HttpResponse r = new HttpResponse(ex, Http.HTTP_OK);
196: r.addHeader("Content-Type", Http.MIME_HTML);
197: r.addHeader("Content-Length", Integer.toString(content
198: .length()));
199: return r;
200: }
201: return super .onServeHeaders(id, ex, request);
202: }
203:
204: public InputStream onServeBody(long id, HttpExchange ex,
205: Request request) {
206: if (request.getName().compareTo("test-overide.txt") == 0)
207: return new BufferedInputStream(
208: new ByteArrayInputStream(content.getBytes()));
209: return super .onServeBody(id, ex, request);
210: }
211:
212: public String getContent() {
213: return content;
214: }
215: }
216:
217: @Test(groups={"overide","All"},dependsOnMethods={"startOveride"})
218: public void testOveride() throws IOException, NoSuchFieldException
219: //------------------------------------------------------------------
220: {
221: testOveride(m_port);
222: testNotFound(m_port);
223: stopServer();
224: }
225:
226: /* Tests
227: * 1. templates (using class per template)
228: * 2. Content within jar
229: */
230: @Test(groups={"templatemultijar","All"})
231: public void startTemplateMulti() throws IOException,
232: NoSuchFieldException
233: //----------------------------------------------------
234: {
235: setupTemplateJarFiles();
236: File jar = new File("test/htdocs.jar");
237: assert (jar.exists() && (jar.isArchive())) : "test/htdocs.jar is not a valid archive";
238: java.io.File jarFile = new java.io.File("test/htdocs.jar");
239: //m_httpd = new ArchiveHttpd(jarFile, m_homeArchiveDirName, 10, 10);
240: m_httpd = new ArchiveHttpd(m_homeArchiveDirName, 10, 10);
241: m_httpd.setVerbose(true);
242: m_httpd.setLogger(System.err);
243: // Java handlers for the template files are in testng/templeates
244: ArchiveStringTemplateHandler stHandler = new ArchiveStringTemplateHandler(
245: m_httpd, "net.homeip.donaldm.testng.templates", jar);
246: stHandler.setDebug(true);
247: m_httpd.addHandler(".st", stHandler);
248: m_httpd.start(m_port, "/");
249: }
250:
251: /* For testing purposes create a jar with the content and add it to the
252: classpath. Normally you would just create the content in a directory
253: that would be added to the jar eg in Netbeans src/resources/htdocs */
254: private void setupTemplateJarFiles() throws IOException
255: //-----------------------------------------------------------------------
256: {
257: java.io.File f = new File("test/htdocs.jar");
258: f.delete();
259: JarOutputStream jar = new JarOutputStream(
260: new BufferedOutputStream(
261: new java.io.FileOutputStream(f)));
262: JarEntry jarEntry = new JarEntry("test/htdocs/pagetemplate.st");
263: jar.putNextEntry(jarEntry);
264: String s = getPageTemplateHtml(true);
265: jar.write(s.getBytes());
266:
267: jarEntry = new JarEntry("test/htdocs/options.st");
268: jar.putNextEntry(jarEntry);
269: s = getPageTemplateMacro();
270: jar.write(s.getBytes());
271: jar.close();
272:
273: // Load jar into classpath
274: add2Cp(f);
275: displayClasspath();
276: //System.out.println("Path = " + getPathForResource("test/htdocs/options.st"));
277: }
278:
279: @SuppressWarnings("unchecked")
280: private boolean add2Cp(java.io.File f)
281: //----------------------------
282: {
283: Class[] parameters = new Class[] { URL.class };
284: URLClassLoader sysloader = (URLClassLoader) ClassLoader
285: .getSystemClassLoader();
286: Class<URLClassLoader> sysclass = URLClassLoader.class;
287: //String urlPath = "jar:file://" + f.getAbsolutePath() + "!/";
288: try {
289: URL url = new URL("file://" + f.getAbsolutePath());
290: Method method = sysclass.getDeclaredMethod("addURL",
291: parameters);
292: method.setAccessible(true);
293:
294: method.invoke(sysloader, new Object[] { url });
295: } catch (Throwable t) {
296: t.printStackTrace();
297: return false;
298: }
299: return true;
300: }
301:
302: private void displayClasspath()
303: //-----------------------------
304: {
305: ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();
306: URL[] urls = ((URLClassLoader) sysClassLoader).getURLs();
307: for (int i = 0; i < urls.length; i++)
308: System.out.println(urls[i].getFile());
309: }
310:
311: private String getPathForResource(String filename) {
312: ClassLoader loader = this .getClass().getClassLoader();
313: URL url = loader.getResource(filename);
314: String path = null;
315: if (url != null) {
316: path = url.getFile();
317: }
318: return path;
319: }
320:
321: @Test(groups={"templatemultijar","All"},dependsOnMethods={"startTemplateMulti"})
322: public void testTemplateMulti() throws IOException,
323: NoSuchFieldException
324: //------------------------------------------------------------------
325: {
326: URL url = new URL("http", "localhost", m_port,
327: "/pagetemplate.st");
328: URLConnection conn = url.openConnection();
329: int len = conn.getContentLength();
330:
331: java.io.File f = new java.io.File(System.getProperty(
332: "java.io.tmpdir", "tmp"));
333: java.io.File dir = new java.io.File(f, "templates");
334: deleteDir(dir);
335: dir.mkdirs();
336: StringTemplateGroup group = new StringTemplateGroup(
337: "testgroup", dir.getAbsolutePath());
338: f = new java.io.File(dir, "pagetemplate.st");
339: java.io.BufferedWriter bw = new java.io.BufferedWriter(
340: new java.io.FileWriter(f));
341: bw.write(getPageTemplateHtml(true));
342: bw.close();
343: f = new java.io.File(dir, "test/htdocs");
344: f.mkdirs();
345: f = new java.io.File(f, "options.st");
346: bw = new java.io.BufferedWriter(new java.io.FileWriter(f));
347: bw.write(getPageTemplateMacro());
348: bw.close();
349: StringTemplate st = group.getInstanceOf("pagetemplate");
350: SelItem[] selList = new SelItem[6];
351: for (int i = 0; i < 5; i++)
352: selList[i] = new SelItem("OPT" + i, "Option " + (i + 1));
353: selList[5] = new SelItem("OPT5", "Option 6", true);
354: st.setAttribute("selList", selList);
355: if (System.getProperty("os.name").toLowerCase().contains(
356: "windows"))
357: st.setAttribute("welcome", "Welcome Dumbass");
358: else
359: st.setAttribute("welcome", "Welcome Master");
360: String expectedContents = null;
361: try {
362: expectedContents = st.toString();
363: } catch (Exception e) {
364: System.err.println(e.getMessage());
365: e.printStackTrace(System.err);
366: }
367:
368: assert len > 0 : "Content length for URL " + url.toString()
369: + " is 0";
370: assert expectedContents.length() == len : "Content length for URL "
371: + url.toString()
372: + " != length of content ("
373: + len
374: + " != " + expectedContents.length() + ")";
375: Object o = conn.getContent();
376: assert o != null : "URL " + url.toString() + " content null";
377: assert o instanceof InputStream : "URL " + url.toString()
378: + " content is not" + "an InputStream ("
379: + o.getClass().getName() + ")";
380: InputStream in = (InputStream) o;
381: byte[] b = readArray(in, len);
382: in.close();
383:
384: String contents = new String(b);
385: assert expectedContents.compareTo(contents) == 0 : "page.html: Content does not match expected content"
386: + LF + expectedContents + LF + contents;
387:
388: stopServer();
389: }
390:
391: @Test(groups={"templatesingle","All"})
392: public void startTemplateSingle() throws IOException,
393: NoSuchFieldException
394: //----------------------------------------------------
395: {
396: setupTemplateFiles();
397: m_httpd = new FileHttpd(m_homeDir, 10);
398: m_httpd.setVerbose(true);
399: m_httpd.setLogger(System.err);
400: FileStringTemplateHandler stHandler = new FileStringTemplateHandler(
401: m_httpd, new TemplatableAdapter() {
402: private SelItem[] selList = null;
403:
404: private void setTemplateAttributes(
405: StringTemplate template, Request request)
406: // ---------------------------------------------------------
407: {
408: System.out.println(template.getName());
409: if (template.getName()
410: .compareTo("pagetemplate") == 0) {
411: if (selList == null) {
412: selList = new SelItem[6];
413: for (int i = 0; i < 5; i++)
414: selList[i] = new SelItem("OPT" + i,
415: "Option " + (i + 1));
416: selList[5] = new SelItem("OPT5",
417: "Option 6", true);
418: }
419: template.setAttribute("selList", selList);
420: if (System.getProperty("os.name")
421: .toLowerCase().contains("windows"))
422: template.setAttribute("welcome",
423: "Welcome Dumbass");
424: else
425: template.setAttribute("welcome",
426: "Welcome Master");
427: }
428: }
429:
430: public java.io.File templateFile(
431: StringTemplate template, Request request,
432: StringBuffer mimeType, File dir) {
433: setTemplateAttributes(template, request);
434: return super .templateFile(template, request,
435: mimeType, dir);
436: }
437:
438: public String templateString(
439: StringTemplate template, Request request,
440: StringBuffer mimeType) {
441: setTemplateAttributes(template, request);
442: return super .templateString(template, request,
443: mimeType);
444: }
445:
446: public InputStream templateStream(
447: StringTemplate template, Request request,
448: StringBuffer mimeType) {
449: setTemplateAttributes(template, request);
450: return super .templateStream(template, request,
451: mimeType);
452: }
453: });
454: stHandler.setDebug(true);
455: m_httpd.addHandler(".st", stHandler);
456: m_httpd.start(m_port, "/");
457: }
458:
459: private void setupTemplateFiles() throws IOException
460: //--------------------------------------------------
461: {
462: deleteDir(m_homeDir);
463: m_homeDir.mkdirs();
464: java.io.File f = new java.io.File(m_homeDir, "pagetemplate.st");
465: f.delete();
466: PrintWriter ps = new PrintWriter(f);
467: ps.print(getPageTemplateHtml(false));
468: ps.close();
469: f = new java.io.File(m_homeDir, "include");
470: f.mkdirs();
471: f = new java.io.File(f, "options.st");
472: f.delete();
473: ps = new PrintWriter(f);
474: ps.print(getPageTemplateMacro());
475: ps.close();
476: }
477:
478: @Test(groups={"templatesingle","All"},dependsOnMethods={"startTemplateSingle"})
479: public void testTemplateSingle() throws IOException,
480: NoSuchFieldException
481: //------------------------------------------------------------------
482: {
483: URL url = new URL("http", "localhost", m_port,
484: "/pagetemplate.st");
485: URLConnection conn = url.openConnection();
486: int len = conn.getContentLength();
487:
488: StringTemplateGroup group = new StringTemplateGroup(
489: "testgroup", m_homeDir.getAbsolutePath());
490: StringTemplate st = group.getInstanceOf("pagetemplate");
491: SelItem[] selList = new SelItem[6];
492: for (int i = 0; i < 5; i++)
493: selList[i] = new SelItem("OPT" + i, "Option " + (i + 1));
494: selList[5] = new SelItem("OPT5", "Option 6", true);
495: st.setAttribute("selList", selList);
496: if (System.getProperty("os.name").toLowerCase().contains(
497: "windows"))
498: st.setAttribute("welcome", "Welcome Dumbass");
499: else
500: st.setAttribute("welcome", "Welcome Master");
501: String expectedContents = null;
502: try {
503: expectedContents = st.toString();
504: } catch (Exception e) {
505: System.err.println(e.getMessage());
506: e.printStackTrace(System.err);
507: }
508:
509: assert len > 0 : "Content length for URL " + url.toString()
510: + " is 0";
511: //assert expectedContents.length() == len : "Content length for URL " + url.toString() +
512: //" != length of content (" + len + " != " + expectedContents.length() + ")";
513: Object o = conn.getContent();
514: assert o != null : "URL " + url.toString() + " content null";
515: assert o instanceof InputStream : "URL " + url.toString()
516: + " content is not" + "an InputStream ("
517: + o.getClass().getName() + ")";
518: InputStream in = (InputStream) o;
519: byte[] b = readArray(in, len);
520: in.close();
521:
522: String contents = new String(b);
523: assert expectedContents.compareTo(contents) == 0 : "page.html: Content does not match expected content"
524: + LF + expectedContents + LF + contents;
525:
526: stopServer();
527: }
528:
529: @Test(groups={"post","All"})
530: public void startPost() throws IOException, NoSuchFieldException
531: //----------------------------------------------------
532: {
533: m_httpd = new FileHttpd(m_homeDir, 10);
534: m_httpd.setVerbose(true);
535: m_httpd.setLogger(System.err);
536: m_httpd.addPostHandler("/post", new Postable() {
537:
538: public Object onHandlePost(long id, HttpExchange ex,
539: Request request, HttpResponse response,
540: java.io.File dir, Object... extraParameters) {
541: Headers getParameters = request.getGETParameters();
542: String v1 = getParameters.getFirst("get1");
543: String v2 = getParameters.getFirst("get2");
544: java.io.BufferedWriter bw = null;
545: java.io.File f = new java.io.File(m_homeDir, "post.txt");
546: try {
547: bw = new java.io.BufferedWriter(
548: new java.io.FileWriter(f));
549: bw.write(v1);
550: bw.newLine();
551: bw.write(v2);
552: bw.newLine();
553: } catch (IOException e) {
554: e.printStackTrace();
555: return null;
556: } finally {
557: if (bw != null)
558: try {
559: bw.close();
560: } catch (Exception e) {
561: }
562: }
563:
564: Headers postParameters = request.getPOSTParameters();
565: assert postParameters != null : "No POST parameters ";
566: v1 = postParameters.getFirst("key1");
567: v2 = postParameters.getFirst("key2");
568: try {
569: bw = new java.io.BufferedWriter(
570: new java.io.FileWriter(f, true));
571: bw.write(v1);
572: bw.newLine();
573: bw.write(v2);
574: bw.newLine();
575: } catch (Exception e) {
576: return null;
577: } finally {
578: if (bw != null)
579: try {
580: bw.close();
581: } catch (Exception e) {
582: }
583: }
584: return f;
585: }
586: });
587: m_httpd.start(m_port, "/");
588: }
589:
590: @Test(groups={"post","All"},dependsOnMethods={"startPost"})
591: public void testPost() throws IOException, NoSuchFieldException
592: //------------------------------------------------------------------
593: {
594: String data = URLEncoder.encode("key1", "UTF-8") + "="
595: + URLEncoder.encode("Value 1", "UTF-8");
596: data += "&" + URLEncoder.encode("key2", "UTF-8") + "="
597: + URLEncoder.encode("Value 2", "UTF-8");
598:
599: // Send data
600: URL url = new URL("http://localhost:" + m_port + "/post?get1="
601: + URLEncoder.encode("Get 1", "UTF-8") + "&get2="
602: + URLEncoder.encode("Get 2", "UTF-8"));
603: System.out.println(url.toExternalForm());
604: URLConnection conn = url.openConnection();
605: conn.setDoOutput(true);
606: java.io.OutputStreamWriter wr = new java.io.OutputStreamWriter(
607: conn.getOutputStream());
608: wr.write(data);
609: wr.flush();
610:
611: // Get the response
612: java.io.BufferedReader rd = new java.io.BufferedReader(
613: new java.io.InputStreamReader(conn.getInputStream()));
614: String line;
615: int lc = 0;
616: while ((line = rd.readLine()) != null) {
617: System.out.println(line);
618: switch (lc++) {
619: case 0:
620: assert line.compareTo("Get 1") == 0 : "Invalid line 1"
621: + line;
622: break;
623: case 1:
624: assert line.compareTo("Get 2") == 0 : "Invalid line 2"
625: + line;
626: break;
627: case 2:
628: assert line.compareTo("Value 1") == 0 : "Invalid line 1"
629: + line;
630: break;
631: case 3:
632: assert line.compareTo("Value 2") == 0 : "Invalid line 2"
633: + line;
634: break;
635:
636: }
637: }
638: wr.close();
639: rd.close();
640: }
641:
642: private void stopServer()
643: //-----------------------
644: {
645: try {
646: Thread.sleep(1000);
647: } catch (Exception e) {
648: }
649: m_httpd.stop(1);
650: m_httpd = null;
651:
652: }
653:
654: private void testBasic(int port, String protocol)
655: throws IOException
656: //-------------------------------------------------------------------
657: {
658: URL url = new URL(protocol, "localhost", port, "/basic.html");
659: URLConnection conn = url.openConnection();
660: int len = conn.getContentLength();
661: assert len > 0 : "Content length for URL " + url.toString()
662: + " is " + len;
663: String expectedContents = getBasicHTML();
664:
665: Object o = conn.getContent();
666: assert o != null : "URL " + url.toString() + " content null";
667: assert o instanceof InputStream : "URL " + url.toString()
668: + " content is not" + "an InputStream ("
669: + o.getClass().getName() + ")";
670: java.io.InputStream in = (java.io.InputStream) o;
671: byte[] b = readArray(in, len);
672: in.close();
673:
674: String contents = new String(b);
675: /*
676: assert expectedContents.length() == len : "Content length for URL " + url.toString() +
677: " != length of content (" + len + " != " + expectedContents.length() + ")";*/
678: System.out.printf("%d %d\n", expectedContents.length(),
679: contents.length());
680: assert (expectedContents.compareTo(contents) == 0) : "basic.html: Content does not match expected content"
681: + LF + expectedContents + LF + contents;
682: }
683:
684: private void testPage(int port, String protocol) throws IOException
685: //------------------------------------------------------------------
686: {
687: URL url = new URL(protocol, "localhost", port, "/page.html");
688: URLConnection conn = url.openConnection();
689: int len = conn.getContentLength();
690: String expectedContents = getPageHTML();
691: assert len > 0 : "Content length for URL " + url.toString()
692: + " is 0";
693: assert expectedContents.length() == len : "Content length for URL "
694: + url.toString()
695: + " != length of content ("
696: + len
697: + " != " + expectedContents.length() + ")";
698: Object o = conn.getContent();
699: assert o != null : "URL " + url.toString() + " content null";
700: assert o instanceof java.io.InputStream : "URL "
701: + url.toString() + " content is not"
702: + "an InputStream (" + o.getClass().getName() + ")";
703: java.io.InputStream in = (java.io.InputStream) o;
704: byte[] b = readArray(in, len);
705: in.close();
706:
707: String contents = new String(b);
708: assert expectedContents.compareTo(contents) == 0 : "page.html: Content does not match expected content"
709: + LF + expectedContents + LF + contents;
710:
711: }
712:
713: private void testOveride(int port) throws IOException
714: //-------------------------------------------------------------------
715: {
716: TestOverideHttpd ohttpd = (TestOverideHttpd) m_httpd;
717: URL url = new URL("http", "localhost", port,
718: "/test-overide.txt");
719: URLConnection conn = url.openConnection();
720: int len = conn.getContentLength();
721: assert len > 0 : "Content length for URL " + url.toString()
722: + " is " + len;
723: String expectedContents = ohttpd.getContent();
724:
725: Object o = conn.getContent();
726: assert o != null : "URL " + url.toString() + " content null";
727: assert o instanceof InputStream : "URL " + url.toString()
728: + " content is not" + "an InputStream ("
729: + o.getClass().getName() + ")";
730: InputStream in = (InputStream) o;
731: byte[] b = readArray(in, len);
732: in.close();
733:
734: String contents = new String(b);
735: /*
736: assert expectedContents.length() == len : "Content length for URL " + url.toString() +
737: " != length of content (" + len + " != " + expectedContents.length() + ")";*/
738: System.out.printf("%d %d\n", expectedContents.length(),
739: contents.length());
740: assert (expectedContents.compareTo(contents) == 0) : "basic.html: Content does not match expected content"
741: + LF + expectedContents + LF + contents;
742: }
743:
744: private void testNotFound(int port) throws IOException
745: //------------------------------------------------------
746: {
747: URL url = new URL("http", "localhost", port, "/no.such.file");
748: URLConnection conn = url.openConnection();
749: int len = conn.getContentLength();
750: assert len > 0 : "Content length for URL " + url.toString()
751: + " is " + len;
752: String expectedContents = "I think therefore I am.";
753:
754: Object o = conn.getContent();
755: assert o != null : "URL " + url.toString() + " content null";
756: assert o instanceof InputStream : "URL " + url.toString()
757: + " content is not" + "an InputStream ("
758: + o.getClass().getName() + ")";
759: InputStream in = (InputStream) o;
760: byte[] b = readArray(in, len);
761: in.close();
762:
763: String contents = new String(b);
764: /*
765: assert expectedContents.length() == len : "Content length for URL " + url.toString() +
766: " != length of content (" + len + " != " + expectedContents.length() + ")";*/
767: System.out.printf("%d %d\n", expectedContents.length(),
768: contents.length());
769: assert (expectedContents.compareTo(contents) == 0) : "basic.html: Content does not match expected content"
770: + LF + expectedContents + LF + contents;
771: }
772:
773: private byte[] readArray(InputStream in, int len)
774: throws IOException
775: //------------------------------------------------------------------
776: {
777: byte[] b = new byte[len];
778: int l = in.read(b);
779: int off = l;
780: while (off < len) {
781: l = in.read(b, off, len - off);
782: if (l < 0)
783: break;
784: off += l;
785: }
786: return b;
787: }
788:
789: private String getBasicHTML()
790: //---------------------------
791: {
792: return "<HTML>" + LF + " <HEAD>" + LF + " </HEAD>" + LF
793: + " <BODY" + LF + " <P> Hello World !!!! </P>"
794: + LF + " </BODY>" + LF + " </HTML>";
795: }
796:
797: private String getPageCSS(int i)
798: //------------------------------
799: {
800: switch (i) {
801: case 0:
802: return "hr {color: sienna}" + LF + "p " + LF + "{" + LF
803: + " margin-left: 20px;" + LF
804: + " text-align: center;" + LF
805: + " font-size: 10pt" + LF + "}" + LF;// +
806: //"body {background-image: url(\"images/notfound.gif\")}";
807: case 1:
808: return "a { color:red; }" + LF;
809: }
810: return "";
811: }
812:
813: private String getPageHTML()
814: //-------------------------
815: {
816: return "<HTML>"
817: + LF
818: + " <HEAD>"
819: + LF
820: + " <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css!+!style2.css\" />"
821: + LF + " </HEAD>" + LF + " <BODY>" + LF
822: + " <P> Hello World !!!! </P>" + LF + " <HR>"
823: + LF + " </BODY>" + LF + " </HTML>";
824: }
825:
826: public String getPageTemplateHtml(boolean isInJar)
827: //-----------------------------------------------
828: {
829: return "<HTML>"
830: + LF
831: + " <HEAD>"
832: + LF
833: + " </HEAD>"
834: + LF
835: + " <BODY"
836: + LF
837: + " <P>$welcome$</P>"
838: + LF
839: + " <SELECT SIZE=\"1\" name=\"sel\" id=\"sel\">"
840: + LF
841: + ((isInJar) ? " $selList:test/htdocs/options()$"
842: : " $selList:include/options()$") + LF
843: + " </SELECT>" + LF + " <HR>" + LF
844: + " </BODY>" + LF + " </HTML>";
845: }
846:
847: public String getPageTemplateMacro()
848: //---------------------------------
849: {
850: return "$if(it.selected)$"
851: + LF
852: + " <option value=\"$it.key$\" selected> $it.value$</option>"
853: + LF + "$else$" + LF
854: + " <option value=\"$it.key$\"> $it.value$</option>"
855: + LF + "$endif$";
856: }
857:
858: private boolean deleteDir(java.io.File dir)
859: //---------------------------------------
860: { // a symbolic link has a different canonical path than its actual path,
861: // unless it's a link to itself
862: java.io.File candir;
863: try {
864: candir = dir.getCanonicalFile();
865: } catch (IOException e) {
866: return false;
867: }
868: if (!candir.equals(dir.getAbsoluteFile()))
869: return false;
870:
871: java.io.File[] files = candir.listFiles();
872: if (files != null) {
873: for (int i = 0; i < files.length; i++) {
874: java.io.File file = files[i];
875: boolean deleted = file.delete();
876: if (!deleted)
877: if (file.isDirectory())
878: deleteDir(file);
879:
880: }
881: }
882: return dir.delete();
883: }
884:
885: }
|