001: /*
002: * @(#)DynamicPageURLConnection.java 1.2 04/12/06
003: *
004: * Copyright (c) 2003,2004 Sun Microsystems, Inc. All Rights Reserved.
005: *
006: * See the file "LICENSE.txt" for information on usage and redistribution
007: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
008: */
009: package org.pnuts.servlet.protocol.pea;
010:
011: import pnuts.servlet.*;
012: import pnuts.lang.Context;
013: import java.net.URL;
014: import java.net.URLConnection;
015: import java.net.MalformedURLException;
016: import java.io.IOException;
017: import java.io.ByteArrayInputStream;
018: import java.io.Reader;
019: import java.io.Writer;
020: import java.io.StringWriter;
021: import java.io.File;
022: import java.io.InputStreamReader;
023: import java.io.InputStream;
024: import java.util.*;
025:
026: /*
027: * Protocol handler for dynamic pages, that is used in debugging.
028: *
029: * pea:<spec-url>!charset=<charset>
030: */
031: public class DynamicPageURLConnection extends URLConnection {
032: private URL specURL;
033: private Set scriptURLs;
034: private URLConnection specURLConnection;
035: private File dir;
036: private String encoding;
037: private boolean connected;
038: private Context context;
039:
040: public DynamicPageURLConnection(URL url, Context context,
041: Set scriptURLs) throws IOException {
042: super (url);
043: this .context = context;
044: this .scriptURLs = scriptURLs;
045: parseSpecs(url);
046: }
047:
048: private void parseSpecs(URL url) throws MalformedURLException {
049: String spec = url.getFile();
050: int idx = spec.indexOf('!');
051: if (idx > 0) {
052: this .specURL = new URL(spec.substring(0, idx));
053: if (spec.length() > idx + 1) {
054: if (spec.startsWith("charset=", idx + 1)) {
055: this .encoding = spec.substring(idx + 9);
056: }
057: }
058: } else {
059: this .specURL = new URL(spec);
060: }
061: }
062:
063: public int getContentLength() {
064: return -1;
065: }
066:
067: public String getContentType() {
068: return "application/pnuts-dynamic-page";
069: }
070:
071: public synchronized void connect() throws IOException {
072: if (connected) {
073: return;
074: }
075: this .specURLConnection = specURL.openConnection();
076: specURLConnection.connect();
077: connected = true;
078: }
079:
080: public InputStream getInputStream() throws IOException {
081: if (!connected) {
082: connect();
083: }
084: Reader reader;
085: if (encoding == null) {
086: reader = new InputStreamReader(specURLConnection
087: .getInputStream());
088: } else {
089: reader = new InputStreamReader(specURLConnection
090: .getInputStream(), encoding);
091: }
092: StringWriter writer = new StringWriter();
093: DynamicPage.convert(reader, writer, specURL, encoding, context,
094: scriptURLs);
095: if (encoding == null) {
096: return new ByteArrayInputStream(writer.toString()
097: .getBytes());
098: } else {
099: return new ByteArrayInputStream(writer.toString().getBytes(
100: encoding));
101: }
102: }
103: }
|