Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.xmlcalabash.extensions;
  
  
  import java.io.File;
 import java.net.URI;
 import java.net.URL;
 import java.util.Date;
 import java.util.Map;
 

Author(s):
ndw
 
 public class Zip extends DefaultStep {
     protected final static QName _href = new QName("""href");
     protected final static QName _name = new QName("""name");
     protected final static QName _command = new QName("""command");
     protected final static QName _compression_method = new QName("""compression-method");
     protected final static QName _compression_level = new QName("""compression-level");
     protected final static QName c_zip_manifest = new QName("c"."zip-manifest");
     protected final static QName c_zipfile = new QName("c"."zipfile");
     protected final static QName c_entry = new QName("c"."entry");
     protected final static QName c_file = new QName("c"."file");
     protected final static QName c_directory = new QName("c"."directory");
     protected final static QName _compressed_size = new QName("""compressed-size");
     protected final static QName _comment = new QName("""comment");
     protected final static QName _size = new QName("""size");
     protected final static QName _date = new QName("""date");
     private static final QName _status_only = new QName("status-only");
     private static final QName _detailed = new QName("detailed");
     private static final QName _status = new QName("status");
     private static final QName _value = new QName("value");
     private final static int bufsize = 8192;
 
     private final static QName serializerAttrs[] = {
             ,
             ,
             ,
             ,
             ,
             ,
             ,
             ,
             ,
             ,
             ,
             ,
             ,
             ,
             
     };
 
     private ReadablePipe source = null;
     private ReadablePipe manifest = null;
     private WritablePipe result = null;
     private Map<StringFileToZipzipManifest = new LinkedHashMap<StringFileToZip> ();
     private Map<StringXdmNodesrcManifest = new LinkedHashMap<StringXdmNode> ();

    
Creates a new instance of Unzip
    public Zip(XProcRuntime runtimeXAtomicStep step) {
        super(runtime,step);
    }
    public void setInput(String portReadablePipe pipe) {
        if ("source".equals(port)) {
             = pipe;
        } else {
             = pipe;
        }
    }
    public void setOutput(String portWritablePipe pipe) {
         = pipe;
    }
    public void reset() {
        .resetReader();
        .resetReader();
        .resetWriter();
    }
    public void run() throws SaxonApiException {
        super.run();
        String zipFn = getOption().getString();
        XdmNode man = S9apiUtils.getDocumentElement(.read());
        if (!.equals(man.getNodeName())) {
            throw new XProcException(.getNode(), "The cx:zip manifest must be a c:zip-manifest.");
        }
        while (.moreDocuments()) {
            XdmNode doc = .read();
            XdmNode root = S9apiUtils.getDocumentElement(doc);
            .put(root.getBaseURI().toASCIIString(), doc);
        }
        parseManifest(man);
        File zipFile = null;
        try {
            zipFile = new File(new URI(zipFn));
        } catch (URISyntaxException e) {
            throw new XProcException(e);
        }
        File zipParent = zipFile.getParentFile();
        File zipTemp = null;
        ZipFile inZip = null;
        ZipOutputStream outZip = null;
        try {
            zipTemp = File.createTempFile("calabashZip",".zip",zipParent);
            zipTemp.deleteOnExit();
            if (zipFile.exists()) {
                inZip = new ZipFile(zipFile);
            }
            outZip = new ZipOutputStream(new FileOutputStream(zipTemp));
        } catch (IOException ioe) {
            throw new XProcException(ioe);
        }
        String command = getOption().getString();
        if ("create".equals(command)) {
            try {
                if (inZip != null) {
                    inZip.close();
                }
            } catch (IOException ioe) {
                throw new XProcException(ioe);
            }
            inZip = null;
        }
        if ("update".equals(command) || "create".equals(command)) {
            update(inZipoutZipfalse);
        } else if ("freshen".equals(command)) {
            update(inZipoutZiptrue);
        } else if ("delete".equals(command)) {
            delete(inZipoutZip);
        } else {
            throw new XProcException(.getNode(), "Unexpected cx:zip command: " + command);
        }
        if (zipFile.exists()) {
            zipFile.delete();
        }
        zipTemp.renameTo(zipFile);
        TreeWriter tree = new TreeWriter();
        tree.startDocument(.getNode().getBaseURI());
        tree.addStartElement();
        tree.addAttribute(zipFile.toURI().toASCIIString());
        tree.startContent();
        try {
            URL url = zipFile.toURI().toURL();
            URLConnection connection = url.openConnection();
            InputStream stream = connection.getInputStream();
            ZipInputStream zipStream = new ZipInputStream(stream);
            DatatypeFactory dfactory = DatatypeFactory.newInstance();
            GregorianCalendar cal = new GregorianCalendar();
            ZipEntry entry = zipStream.getNextEntry();
            while (entry != null) {
                cal.setTimeInMillis(entry.getTime());
                XMLGregorianCalendar xmlCal = dfactory.newXMLGregorianCalendar(cal);
                if (entry.isDirectory()) {
                    tree.addStartElement();
                } else {
                    tree.addStartElement();
                    tree.addAttribute(""+entry.getCompressedSize());
                    tree.addAttribute(""+entry.getSize());
                }
                if (entry.getComment() != null) {
                    tree.addAttribute(entry.getComment());
                }
                tree.addAttribute(""+entry.getName());
                tree.addAttribute(xmlCal.toXMLFormat());
                tree.startContent();
                tree.addEndElement();
                entry = zipStream.getNextEntry();
            }
            zipStream.close();
        } catch (MalformedURLException mue) {
            throw new XProcException(.mue);
        } catch (IOException ioe) {
            throw new XProcException(.ioe);
        } catch (DatatypeConfigurationException dce) {
            throw new XProcException(.dce);
        }
        tree.addEndElement();
        tree.endDocument();
        .write(tree.getResult());
    }
    private void parseManifest(XdmNode man) {
        for (XdmNode child : new RelevantNodes(man.)) {
            if (. == child.getNodeKind()) {
                if (.equals(child.getNodeName())) {
                    String name = child.getAttributeValue();
                    if (name == null || "".equals(name)) {
                        throw new XProcException(.getNode(), "Missing or invalid name in cx:zip manifest.");
                    }
                    String href = child.getAttributeValue();
                    if (href == null || "".equals(href)) {
                        throw new XProcException(.getNode(), "Missing or invalid href in cx:zip manifest.");
                    }
                    String hrefuri = child.getBaseURI().resolve(href).toASCIIString();
                    String comment = child.getAttributeValue();
                    int method = .;
                    int level = .;
                    String value = child.getAttributeValue();
                    if ("stored".equals(value)) {
                        method = .;
                    }
                    value = child.getAttributeValue();
                    if ("smallest".equals(value)) {
                        level = .;
                    } else if ("fastest".equals(value)) {
                        level = .;
                    } else if ("huffman".equals(value)) {
                        level = .;
                    } else if ("none".equals(value)) {
                        level = .;
                        method = .;
                    }
                    .put(namenew FileToZip(namehrefurimethodlevelcommentchild));
                } else {
                    throw new XProcException(.getNode(), "Unexpected element in cx:zip manifest: " + child.getNodeName());
                }
            } else {
                    throw new XProcException(.getNode(), "Unexpected content in cx:zip manifest.");
            }
        }
    }
    public void update(ZipFile inZipZipOutputStream outZipboolean freshen) {
        byte[] buffer = new byte[];
        try {
            if (inZip != null) {
                Enumeration zenum = inZip.entries();
                while (zenum.hasMoreElements()) {
                    ZipEntry entry = (ZipEntryzenum.nextElement();
                    String name = entry.getName();
                    boolean skip = .containsKey(name);
                    if (!skip) {
                        if (.containsKey(name) && freshen) {
                            FileToZip file = .get(name);
                            long zipDate = entry.getTime();
                            long lastMod = file.getLastModified();
                            skip = (lastMod > zipDate);
                            if (!skip) {
                                .remove(name);
                            }
                        } else if (.containsKey(name)) {
                            skip = true;
                        }
                    }
                    if (!skip) {
                        outZip.putNextEntry(entry);
                        InputStream stream = inZip.getInputStream(entry);
                        int read = stream.read(buffer, 0, );
                        while (read >= 0) {
                            outZip.write(buffer,0, read);
                            read = stream.read(buffer, 0, );
                        }
                        stream.close();
                        outZip.closeEntry();
                    }
                }
            }
            CRC32 crc = new CRC32();
            
            for (String name : .keySet()) {
                FileToZip file = .get(name);
                ZipEntry ze = new ZipEntry(name);
                if (file.getComment() != null) {
                    ze.setComment(file.getComment());
                }
                ze.setMethod(file.getMethod());
                outZip.setLevel(file.getLevel());
                
                URI uri = .get(name).getHref();
                String href = uri.toASCIIString();
                
                if(ze.getMethod() == .) {
                    // FIXME: Using a boas is risky here, it will fail for huge files; but who STOREs a huge file?
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    if (.containsKey(uri.toString())) {
                        XdmNode doc = .get(href);
                        Serializer serializer = makeSerializer(file.getOptions());
                        serializer.setOutputStream(baos);
                        S9apiUtils.serialize(docserializer);
                    } else {
                        URLConnection connection = uri.toURL().openConnection();
                        InputStream stream = connection.getInputStream();
                        int read = stream.read(buffer, 0, );
                        while (read>0){
                            baos.write(buffer,0,read);
                            read = stream.read(buffer, 0, );
                        }
                        stream.close();
                    }
                    byte[] bytes =  baos.toByteArray();
                    ze.setSize(bytes.length);
                    crc.reset();
                    crc.update(bytes);
                    ze.setCrc(crc.getValue());
                }
                outZip.putNextEntry(ze);
                if (.containsKey(href)) {
                    XdmNode doc = .get(href);
                    Serializer serializer = makeSerializer(file.getOptions());
                    serializer.setOutputStream(outZip);
                    S9apiUtils.serialize(docserializer);
                } else {
                    URL url = uri.toURL();
                    URLConnection connection = url.openConnection();
                    InputStream stream = connection.getInputStream();
                    int read = stream.read(buffer, 0, );
                    while (read >= 0) {
                        outZip.write(buffer,0, read);
                        read = stream.read(buffer, 0, );
                    }
                    stream.close();
                }
                outZip.closeEntry();
            }
            outZip.close();
        } catch (IOException ioe) {
            throw new XProcException(ioe);
        } catch (SaxonApiException sae) {
            throw new XProcException(sae);
        }
    }
    public void delete(ZipFile inZipZipOutputStream outZip) {
        try {
            if (inZip != null) {
                Enumeration zenum = inZip.entries();
                while (zenum.hasMoreElements()) {
                    ZipEntry entry = (ZipEntryzenum.nextElement();
                    String name = entry.getName();
                    boolean delete = false;
                    if (.containsKey(name)) {
                        delete = true;
                    }
                    if (!delete) {
                        outZip.putNextEntry(entry);
                        InputStream stream = inZip.getInputStream(entry);
                        byte[] buffer = new byte[];
                        int read = stream.read(buffer, 0, );
                        while (read >= 0) {
                            outZip.write(buffer,0, read);
                            read = stream.read(buffer, 0, );
                        }
                        stream.close();
                        outZip.closeEntry();
                    }
                }
            }
            outZip.close();
        } catch (IOException ioe) {
            throw new XProcException(ioe);
        }
    }
    private class FileToZip {
        private String zipName = null;
        private URI href = null;
        private String origHref = null;
        private int method = -1;
        private int level = -1;
        private String comment = null;
        private long lastModified = -1;
        private Hashtable<QName,Stringoptions = null;
        public FileToZip(String zipNameString hrefint methodint levelString commentXdmNode entry) {
            try {
                 = href;
                this. = zipName;
                this. = new URI(href);
                this. = method;
                this. = level;
                this. = comment;
                 = readLastModified(this.);
                // FIXME: There's no validation here...
                for (QName attr : ) {
                    String value = entry.getAttributeValue(attr);
                    if (value != null) {
                        if ( == null) {
                             = new Hashtable<QNameString> ();
                        }
                        .put(attrvalue);
                    }
                }
            } catch (URISyntaxException use) {
                throw new XProcException(use);
            }
        }
        public String getName() {
            return ;
        }
        public URI getHref() {
            return ;
        }
        public int getMethod() {
            return ;
        }
        public int getLevel() {
            return ;
        }
        public String getComment() {
            return ;
        }
        public long getLastModified() {
            return ;
        }
        public Hashtable<QName,StringgetOptions() {
            return ;
        }
        private long readLastModified(URI uri) {
            if (.containsKey()) {
                // If the document to be zipped is in the set of source documents,
                // don't try to read its timestamp from the disk or the web.
                // Use "now".
                Date date = new Date();
                return date.getTime();
            }
            if (uri.getScheme().equals("file")) {
                String fn = uri.toASCIIString();
                if (fn.startsWith("file:")) {
                    fn = fn.substring(5);
                    if (fn.startsWith("///")) {
                        fn = fn.substring(2);
                    }
                }
                File f = new File(fn);
                return f.lastModified();
            } else {
                // Let's try HTTP
                HttpRequest httpReq = new HttpRequest();
                Pipe inputPipe = new Pipe();
                Pipe outputPipe = new Pipe();
                httpReq.setInput("source"inputPipe);
                httpReq.setOutput("result"outputPipe);
                TreeWriter req = new TreeWriter();
                req.startDocument(.getNode().getBaseURI());
                req.addStartElement(.);
                req.addAttribute("HEAD");
                req.addAttribute(uri.toASCIIString());
                req.addAttribute("true");
                req.addAttribute("true");
                req.startContent();
                req.addEndElement();
                req.endDocument();
                inputPipe.write(req.getResult());
                try {
                    httpReq.run();
                } catch (SaxonApiException sae) {
                    throw new XProcException(sae);
                }
                XdmNode result = S9apiUtils.getDocumentElement(outputPipe.read());
                int status = Integer.parseInt(result.getAttributeValue());
                if (status == 200) {
                    for (XdmNode node : new RelevantNodes(result.)) {
                        if ("Last-Modified".equals(node.getAttributeValue())) {
                            String months[] = {"JAN""FEB""MAR""APR""MAY""JUN",
                                               "JUL""AUG""SEP""OCT""NOV""DEC" };
                            String dateStr = node.getAttributeValue();
                            // dateStr = Fri, 13 Mar 2009 12:12:07 GMT
                            //           00000000001111111111222222222
                            //           01234567890123456789012345678
                            //System.err.println("dateStr: " + dateStr);
                            int day = Integer.parseInt(dateStr.substring(5,7));
                            String monthStr = dateStr.substring(8,11).toUpperCase();
                            int year = Integer.parseInt(dateStr.substring(12,16));
                            int hour = Integer.parseInt(dateStr.substring(17,19));
                            int min = Integer.parseInt(dateStr.substring(20,22));
                            int sec = Integer.parseInt(dateStr.substring(23,25));
                            String tzStr = dateStr.substring(26,29);
                            int month = 0;
                            for (month = 0; month < 12; month++) {
                                if (months[month].equals(monthStr)) {
                                    break;
                                }
                            }
                            // FIXME: check if this is correct!
                            GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
                            cal.set(year,month,day,hour,min,sec);
                            return cal.getTimeInMillis();
                        }
                    }
                    return -1;
                } else {
                    return -1;
                }
            }
        }
    }
    public Serializer makeSerializer(Hashtable<QName,Stringoptions) {
        Serializer serializer = new Serializer();
        if (options == null) {
            return serializer;
        }
        if (options.containsKey()) {
            serializer.setOutputProperty(.."false".equals(options.get()) ? "yes" : "no");
        }
        if (options.containsKey()) {
            String list = options.get();
            // FIXME: Why is list="" sometimes?
            if (!"".equals(list)) {
                String[] names = list.split("\\s+");
                list = "";
                for (String name : names) {
                    QName q = new QName(name.getNode());
                    list += q.getClarkName() + " ";
                }
                serializer.setOutputProperty(..list);
            }
        }
        if (options.containsKey()) {
            serializer.setOutputProperty(..options.get());
        }
        if (options.containsKey()) {
            serializer.setOutputProperty(..options.get());
        }
        if (options.containsKey()) {
            serializer.setOutputProperty(..options.get());
        }
        if (options.containsKey()) {
            serializer.setOutputProperty(.."true".equals(options.get()) ? "yes" : "no");
        }
        if (options.containsKey()) {
            serializer.setOutputProperty(.."true".equals(options.get()) ? "yes" : "no");
        }
        if (options.containsKey()) {
            serializer.setOutputProperty(.."true".equals(options.get()) ? "yes" : "no");
        }
        if (options.containsKey()) {
            serializer.setOutputProperty(..options.get());
        }
        if (options.containsKey()) {
            serializer.setOutputProperty(..options.get());
        }
        if (options.containsKey()) {
            serializer.setOutputProperty(..options.get());
        }
        if (options.containsKey()) {
            serializer.setOutputProperty(.."true".equals(options.get()) ? "yes" : "no");
        }
        if (options.containsKey()) {
            String standalone = options.get();
            if ("true".equals(standalone)) {
                serializer.setOutputProperty(.."yes");
            } else if ("false".equals(standalone)) {
                serializer.setOutputProperty(.."no");
            }
            // What about omit?
        }
        if (options.containsKey()) {
            serializer.setOutputProperty(.."true".equals(options.get()) ? "yes" : "no");
        }
        if (options.containsKey()) {
            serializer.setOutputProperty(..options.get());
        }
        return serializer;
    }
New to GrepCode? Check out our FAQ X