001/*
002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     bstefanescu
018 */
019package org.nuxeo.ecm.automation.core.operations.blob;
020
021import java.io.File;
022import java.io.FileOutputStream;
023import java.io.IOException;
024import java.io.InputStream;
025import java.util.Collection;
026import java.util.HashSet;
027import java.util.zip.ZipOutputStream;
028
029import org.nuxeo.common.utils.StringUtils;
030import org.nuxeo.common.utils.ZipUtils;
031import org.nuxeo.ecm.automation.OperationContext;
032import org.nuxeo.ecm.automation.core.Constants;
033import org.nuxeo.ecm.automation.core.annotations.Context;
034import org.nuxeo.ecm.automation.core.annotations.Operation;
035import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
036import org.nuxeo.ecm.automation.core.annotations.Param;
037import org.nuxeo.ecm.automation.core.util.BlobList;
038import org.nuxeo.ecm.core.api.Blob;
039import org.nuxeo.ecm.core.api.Blobs;
040import org.nuxeo.runtime.api.Framework;
041
042/**
043 * TODO: detect mine?
044 *
045 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
046 */
047@Operation(id = CreateZip.ID, category = Constants.CAT_BLOB, label = "Zip", description = "Creates a zip file from the input file(s). If no file name is given, the first file name in the input will be used. Returns the zip file.")
048public class CreateZip {
049
050    public static final String ID = "Blob.CreateZip";
051
052    public static final String ZIP_ENTRY_ENCODING_PROPERTY = "zip.entry.encoding";
053
054    public static enum ZIP_ENTRY_ENCODING_OPTIONS {
055        ascii
056    }
057
058    @Context
059    protected OperationContext ctx;
060
061    @Param(name = "filename", required = false)
062    protected String fileName;
063
064    @OperationMethod
065    public Blob run(Blob blob) throws IOException {
066        if (fileName == null || (fileName = fileName.trim()).length() == 0) {
067            fileName = blob.getFilename();
068        }
069        File file = Framework.createTempFile("nxops-createzip-", ".tmp");
070        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file));
071        Framework.trackFile(file, file);
072        try {
073            zip(blob, out);
074        } finally {
075            out.finish();
076            out.close();
077        }
078        return Blobs.createBlob(file, "application/zip", null, fileName);
079    }
080
081    @OperationMethod
082    public Blob run(BlobList blobs) throws IOException {
083        if (fileName == null || (fileName = fileName.trim()).length() == 0) {
084            fileName = blobs.isEmpty() ? null : blobs.get(0).getFilename();
085        }
086        File file = Framework.createTempFile("nxops-createzip-", ".tmp");
087        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file));
088        Framework.trackFile(file, file);
089        try {
090            zip(blobs, out);
091        } finally {
092            out.finish();
093            out.close();
094        }
095        return Blobs.createBlob(file, "application/zip", null, fileName);
096    }
097
098    protected String getFileName(Blob blob) {
099        String entry = blob.getFilename();
100        if (entry == null) {
101            entry = "Unknown_" + System.identityHashCode(blob);
102        }
103        return escapeEntryPath(entry);
104    }
105
106    protected void zip(Blob blob, ZipOutputStream out) throws IOException {
107        String entry = getFileName(blob);
108        InputStream in = blob.getStream();
109        try {
110            ZipUtils._zip(entry, in, out);
111        } finally {
112            in.close();
113        }
114    }
115
116    protected void zip(BlobList blobs, ZipOutputStream out) throws IOException {
117        // use a set to avoid zipping entries with same names
118        Collection<String> names = new HashSet<String>();
119        int cnt = 1;
120        for (Blob blob : blobs) {
121            String entry = getFileName(blob);
122            if (!names.add(entry)) {
123                entry = "renamed_" + (cnt++) + "_" + entry;
124            }
125            InputStream in = blob.getStream();
126            try {
127                ZipUtils._zip(entry, in, out);
128            } finally {
129                in.close();
130            }
131        }
132    }
133
134    protected String escapeEntryPath(String path) {
135        String zipEntryEncoding = Framework.getProperty(ZIP_ENTRY_ENCODING_PROPERTY);
136        if (zipEntryEncoding != null && zipEntryEncoding.equals(ZIP_ENTRY_ENCODING_OPTIONS.ascii.toString())) {
137            return StringUtils.toAscii(path, true);
138        }
139        return path;
140    }
141
142}