// IsFilterResource.java
// $Id: IsFilterResource.java,v 1.2 1997/07/30 14:01:44 ylafon Exp $  
// (c) COPYRIGHT MIT and INRIA, 1997.
// Please first read the full copyright statement in file COPYRIGHT.html

package w3c.jigsaw.upgrade.from1to2;

import java.io.*;
import java.util.*;

/**
 * Converts a non filtered resource into a Filtered Resource.
 * From 1 to 2, ForwardDirectory became a FilteredResource.
 */

public class IsFilterResource extends FilteredResourceUpgrader {

    public byte[] upgrade(byte oldbits[], int off, int len) {
	Vector filters  = new Vector(8);
	Vector fattrs   = new Vector(8);
	Class  cls      = null;
	int    nfilters = 0;
	Vector rattrs   = null;

	// Read in the old format:
	try {
	    DataInputStream in     = (new DataInputStream
				      (new ByteArrayInputStream(oldbits
								, off
								, len)));
	    int                  oldlen = oldbits.length;
	    // Get the resource class and attributes
	    if ((rattrs = skipAttributeHolder(in)) == null)
		return null;
	    cls    = (Class) rattrs.elementAt(0);
	    rattrs.removeElementAt(0);
	    // Hack to our super-class:
	    nfilters = 0;
	} catch (Exception ex) {
	    ex.printStackTrace();
	    return null;
	}
	// Convert into the new format:
	try {
	    ByteArrayOutputStream bout = new ByteArrayOutputStream(512);
	    DataOutputStream      out  = new DataOutputStream(bout);
	    // Dump the class (slow pickle) and std resource attrs:
	    dump(out, cls, rattrs);
	    // Dump the filters:
	    dumpFilters(out, nfilters, filters, fattrs);
	    out.close();
	    return bout.toByteArray();
	} catch (Exception ex) {
	    ex.printStackTrace();
	    return null;
	}
    }

    public byte[] upgrade(Class cls, DataInputStream in) {
	try {
	    ByteArrayOutputStream bout = new ByteArrayOutputStream(512);
	    DataOutputStream      out  = new DataOutputStream(bout);
	    if ( in.readBoolean() )
		return null;
	    // Read in resource attributes:
	    Vector attrs = new Vector(8);
	    skipAttributes(cls, in, attrs);
	    // Read in filters:
	    Vector filters  = new Vector();
	    Vector fattrs   = new Vector();
	    // Hack to our superclass:
	    int    nfilters = 0;
	    // Dump main resource:
	    dump(out, cls, attrs);
	    // Dump filters:
	    dumpFilters(out, nfilters, filters, fattrs);
	    out.close();
	    return bout.toByteArray();
	} catch (Exception ex) {
	    ex.printStackTrace();
	}
	return null;
    }


}

