package org.w3c.jigsaw.filters;
import java.io.*;
import java.util.zip.*;
import org.w3c.tools.resources.*;
import org.w3c.www.mime.*;
import org.w3c.jigsaw.http.*;
import org.w3c.jigsaw.resources.*;
class GZIPDataMover extends Thread {
InputStream in = null;
OutputStream out = null;
public void run() {
try {
byte buf[] = new byte[1024];
int got = -1;
while ((got = in.read(buf)) > 0)
out.write(buf, 0, got);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try { in.close(); } catch (Exception ex) {};
try { out.close(); } catch (Exception ex) {} ;
}
}
GZIPDataMover(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
setName("GZIPDataMover");
start();
}
}
public class GZIPFilter extends ResourceFilter {
protected static int ATTR_MIME_TYPES = -1;
static {
Class c = null;
Attribute a = null;
try {
c = Class.forName("org.w3c.jigsaw.filters.GZIPFilter");
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
a = new StringArrayAttribute("mime-types"
, null
, Attribute.EDITABLE);
ATTR_MIME_TYPES = AttributeRegistry.registerAttribute(c, a);
}
protected MimeType types[] = null;
@param idx@param val
public void setValue(int idx, Object value) {
super.setValue(idx, value);
if ( idx == ATTR_MIME_TYPES ) {
synchronized (this) {
types = null;
}
}
}
@return
public synchronized MimeType[] getMimeTypes() {
if ( types == null ) {
String strtypes[] = (String[]) getValue(ATTR_MIME_TYPES, null);
if ( strtypes == null )
return null;
types = new MimeType[strtypes.length];
for (int i = 0 ; i < types.length ; i++) {
try {
types[i] = new MimeType(strtypes[i]);
} catch (Exception ex) {
types[i] = null;
}
}
}
return types;
}
public ReplyInterface outgoingFilter(RequestInterface req,
ReplyInterface rep)
throws ProtocolException
{
Request request = (Request) req;
Reply reply = (Reply) rep;
if ( ! reply.hasStream() )
return null;
MimeType t[] = getMimeTypes();
boolean matched = false;
if ( t != null ) {
for (int i = 0 ; i < t.length ; i++) {
if ( t[i] == null )
continue;
if ( t[i].match(reply.getContentType()) > 0 ) {
matched = true;
break;
}
}
}
if ( ! matched )
return null;
try {
PipedOutputStream pout = new PipedOutputStream();
PipedInputStream pin = new PipedInputStream(pout);
new GZIPDataMover(reply.openStream()
, new GZIPOutputStream(pout));
reply.addContentEncoding("gzip");
reply.setContentLength(-1);
reply.setStream(pin);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}