Example usage for java.util.zip ZipEntry setTime

List of usage examples for java.util.zip ZipEntry setTime

Introduction

In this page you can find the example usage for java.util.zip ZipEntry setTime.

Prototype

public void setTime(long time) 

Source Link

Document

Sets the last modification time of the entry.

Usage

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

/**
 * XML ??//  w w w  . j  a v a2s .com
 * 
 * @param name "area" / "corp"
 * @param suffix "" / "c"
 */
void storeXml(String name, String suffix) {

    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    Collection<City> cities = getCities();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    ZipEntry entry = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_" + name + "_utf8.xml");
    entry.setTime(timestamp);
    int cnt = 0;

    try {

        zos.putNextEntry(entry);

        OutputStreamWriter writer = new OutputStreamWriter(zos, "UTF-8");
        XMLStreamWriter xwriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer);

        xwriter.writeStartDocument("UTF-8", "1.0");
        xwriter.writeStartElement("zips");
        xwriter.writeAttribute("type", name);

        for (City city : cities) {

            ParentChild pc = getParentChildDao().get(city.getCode() + suffix);

            if (pc == null) {
                continue;
            }

            for (String json : pc.getChildren()) {

                Zip zip = Zip.fromJson(json);

                xwriter.writeStartElement("zip");
                xwriter.writeAttribute("zip", zip.getCode());
                xwriter.writeAttribute("x0402", zip.getX0402());
                xwriter.writeAttribute("add1", zip.getAdd1());
                xwriter.writeAttribute("add2", zip.getAdd2());
                xwriter.writeAttribute("corp", zip.getCorp());
                xwriter.writeAttribute("add1Yomi", zip.getAdd1Yomi());
                xwriter.writeAttribute("add2Yomi", zip.getAdd2Yomi());
                xwriter.writeAttribute("corpYomi", zip.getCorpYomi());
                xwriter.writeAttribute("note", zip.getNote());
                xwriter.writeEndElement();
                ++cnt;
            }
        }

        xwriter.writeEndElement();
        xwriter.writeEndDocument();
        xwriter.flush();
        zos.closeEntry();
        zos.finish();
        getRawDao().store(baos.toByteArray(), name + "_utf8_xml.zip");
        log.info("count: " + cnt);

    } catch (XMLStreamException e) {
        log.log(Level.WARNING, "", e);
    } catch (FactoryConfigurationError e) {
        log.log(Level.WARNING, "", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }
}

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

/**
 * IME??//from  w w w .  j a v  a  2s.  c o m
 * 
 * @param name "area" / "corp"
 * @param suffix "" / "c"
 */
void storeIme(String name, String suffix) {

    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    SortedMap<String, Pref> prefs = getPrefMap();
    Collection<City> cities = getCities();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    ZipEntry entry = new ZipEntry(
            FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_" + name + "_ime_dic.txt");
    entry.setTime(timestamp);
    int cnt = 0;

    try {

        byte[] tab = "\t".getBytes("MS932");
        byte[] sonota = "\t?????".getBytes("MS932");
        byte[] crlf = CRLF.getBytes("MS932");

        zos.putNextEntry(entry);

        for (City city : cities) {

            ParentChild pc = getParentChildDao().get(city.getCode() + suffix);

            if (pc == null) {
                continue;
            }

            String prefName = prefs.get(city.getCode().substring(0, 2)).getName();
            String cityName = city.getName();

            for (String json : pc.getChildren()) {

                Zip zip = Zip.fromJson(json);
                zos.write(ZenHanHelper.convertZipHankakuZenkaku(zip.getCode()).getBytes("MS932"));
                zos.write(tab);
                zos.write(prefName.getBytes("MS932"));
                zos.write(cityName.getBytes("MS932"));
                zos.write(zip.getAdd1().getBytes("MS932"));
                zos.write(zip.getAdd2().getBytes("MS932"));
                zos.write(zip.getCorp().getBytes("MS932"));
                zos.write(sonota);
                zos.write(crlf);
                ++cnt;
            }
        }

        zos.closeEntry();
        zos.finish();
        getRawDao().store(baos.toByteArray(), name + "_ime_dic.zip");
        log.info("count: " + cnt);

    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }
}

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

/**
 * ??/*from  w w  w.j  a  v  a2s. c o m*/
 * 
 * @param sep "\t" / ","
 * @param name "area" / "corp"
 * @param suffix "" / "c"
 * @param chaset "UTF-8" / "MS932"
 * @param enc "utf8" / "sjis"
 * @param ext "txt" / "csv"
 */
void storeText(String sep, String name, String suffix, String chaset, String enc, String ext) {

    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    Collection<City> cities = getCities();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    ZipEntry entry = new ZipEntry(
            FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_" + name + "_" + enc + "." + ext);
    entry.setTime(timestamp);
    int cnt = 0;

    try {

        byte[] tab = sep.getBytes("MS932");
        byte[] crlf = CRLF.getBytes("MS932");

        zos.putNextEntry(entry);

        for (City city : cities) {

            ParentChild pc = getParentChildDao().get(city.getCode() + suffix);

            if (pc == null) {
                continue;
            }

            for (String json : pc.getChildren()) {

                Zip zip = Zip.fromJson(json);
                zos.write(zip.getCode().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getX0402().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getAdd1().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getAdd2().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getCorp().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getAdd1Yomi().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getAdd2Yomi().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getCorpYomi().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getNote().getBytes(chaset));
                zos.write(crlf);
                ++cnt;
            }
        }

        zos.closeEntry();
        zos.finish();
        getRawDao().store(baos.toByteArray(), name + "_" + enc + "_" + ext + ".zip");
        log.info("count: " + cnt);

    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }
}

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

public void storeX0401Zip() {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ZipOutputStream out = new ZipOutputStream(baos);
    Collection<Pref> prefs = getPrefs();
    ZipEntry tsv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.txt");
    ZipEntry csv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_sjis.csv");
    ZipEntry json = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.json");
    ZipEntry xml = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.xml");

    tsv.setTime(timestamp);
    csv.setTime(timestamp);/*from w ww.  java  2  s .c  om*/
    json.setTime(timestamp);
    xml.setTime(timestamp);

    try {

        out.putNextEntry(tsv);

        for (Pref pref : prefs) {

            out.write(new String(pref.getCode() + "\t" + pref.getName() + "\t" + pref.getYomi() + CRLF)
                    .getBytes("UTF-8"));
        }

        out.closeEntry();
        out.putNextEntry(csv);

        for (Pref pref : prefs) {

            out.write(new String(pref.getCode() + "," + pref.getName() + "," + pref.getYomi() + CRLF)
                    .getBytes("MS932"));
        }

        out.closeEntry();
        out.putNextEntry(json);

        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
        JSONWriter jwriter = new JSONWriter(writer);

        jwriter.array();

        for (Pref pref : prefs) {

            jwriter.object().key("code").value(pref.getCode()).key("name").value(pref.getName()).key("yomi")
                    .value(pref.getYomi()).endObject();
        }

        jwriter.endArray();
        writer.flush();
        out.closeEntry();
        out.putNextEntry(xml);

        XMLStreamWriter xwriter = XMLOutputFactory.newInstance()
                .createXMLStreamWriter(new OutputStreamWriter(out, "UTF-8"));

        xwriter.writeStartDocument("UTF-8", "1.0");
        xwriter.writeStartElement("x0401s");

        for (Pref pref : prefs) {

            xwriter.writeStartElement("x0401");
            xwriter.writeAttribute("code", pref.getCode());
            xwriter.writeAttribute("name", pref.getName());
            xwriter.writeAttribute("yomi", pref.getYomi());
            xwriter.writeEndElement();
        }

        xwriter.writeEndElement();
        xwriter.writeEndDocument();
        xwriter.flush();
        out.closeEntry();
        out.finish();
        baos.flush();
        getRawDao().store(baos.toByteArray(), "x0401.zip");
        log.info("prefs: " + prefs.size());

    } catch (JSONException e) {
        log.log(Level.WARNING, "", e);
    } catch (XMLStreamException e) {
        log.log(Level.WARNING, "", e);
    } catch (FactoryConfigurationError e) {
        log.log(Level.WARNING, "", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }
}

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

public void storeX0402Zip() {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ZipOutputStream out = new ZipOutputStream(baos);
    Collection<City> cities = getCities();
    ZipEntry tsv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.txt");
    ZipEntry csv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_sjis.csv");
    ZipEntry json = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.json");
    ZipEntry xml = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.xml");

    tsv.setTime(timestamp);
    csv.setTime(timestamp);/*from w ww . ja  va2s .  c om*/
    json.setTime(timestamp);
    xml.setTime(timestamp);

    try {

        out.putNextEntry(tsv);

        for (City city : cities) {

            out.write(new String(city.getCode() + "\t" + city.getName() + "\t" + city.getYomi() + "\t"
                    + ((city.getExpiration().getTime() < new Date().getTime()) ? "" : "") + CRLF)
                            .getBytes("UTF-8"));
        }

        out.closeEntry();
        out.putNextEntry(csv);

        for (City city : cities) {

            out.write(new String(city.getCode() + "," + city.getName() + "," + city.getYomi() + ","
                    + ((city.getExpiration().getTime() < new Date().getTime()) ? "" : "") + CRLF)
                            .getBytes("MS932"));
        }

        out.closeEntry();
        out.putNextEntry(json);

        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
        JSONWriter jwriter = new JSONWriter(writer);

        jwriter.array();

        for (City city : cities) {

            jwriter.object().key("code").value(city.getCode()).key("name").value(city.getName()).key("yomi")
                    .value(city.getYomi()).key("expired")
                    .value((city.getExpiration().getTime() < new Date().getTime()) ? "true" : "false")
                    .endObject();
        }

        jwriter.endArray();
        writer.flush();
        out.closeEntry();
        out.putNextEntry(xml);

        XMLStreamWriter xwriter = XMLOutputFactory.newInstance()
                .createXMLStreamWriter(new OutputStreamWriter(out, "UTF-8"));

        xwriter.writeStartDocument("UTF-8", "1.0");
        xwriter.writeStartElement("x0402s");

        for (City city : cities) {

            xwriter.writeStartElement("x0402");
            xwriter.writeAttribute("code", city.getCode());
            xwriter.writeAttribute("name", city.getName());
            xwriter.writeAttribute("yomi", city.getYomi());
            xwriter.writeAttribute("expired",
                    (city.getExpiration().getTime() < new Date().getTime()) ? "true" : "false");
            xwriter.writeEndElement();
        }

        xwriter.writeEndElement();
        xwriter.writeEndDocument();
        xwriter.flush();
        out.closeEntry();
        out.finish();
        baos.flush();
        getRawDao().store(baos.toByteArray(), "x0402.zip");
        log.info("cities: " + cities.size());

    } catch (JSONException e) {
        log.log(Level.WARNING, "", e);
    } catch (XMLStreamException e) {
        log.log(Level.WARNING, "", e);
    } catch (FactoryConfigurationError e) {
        log.log(Level.WARNING, "", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }
}

From source file:org.openremote.modeler.cache.LocalFileCache.java

/**
 * Compresses a set of files into a target zip archive. The file instances should be relative
 * paths used to structure the archive into directories. The relative paths will be resolved
 * to actual file paths in the current account's file cache.
 *
 * @param target    Target file path where the zip archive will be stored.
 * @param files     Set of <b>relative</b> file paths to include in the zip archive. The file
 *                  paths should be set to match the expected directory structure in the final
 *                  archive (therefore should not reflect the absolute file paths expected to
 *                  be included in the archive).
 *
 * @throws CacheOperationException/*from  w w w.j  av a  2 s  . co m*/
 *            if any of the zip file operations fail
 *
 * @throws ConfigurationException
 *            if there are any security restrictions about reading the set of included files
 *            or writing the target zip archive file
 */
private void compress(File target, Set<File> files) throws CacheOperationException, ConfigurationException {
    ZipOutputStream zipOutput = null;

    try {
        zipOutput = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target)));

        for (File file : files) {
            BufferedInputStream fileInput = null;

            // translate the relative zip archive directory path to existing user cache absolute path...

            File cachePathName = new File(cacheFolder, file.getPath());

            try {
                if (!cachePathName.exists()) {
                    throw new CacheOperationException(
                            "Expected to add file ''{0}'' to export archive ''{1}'' (Account : {2}) but it "
                                    + "has gone missing (cause unknown). This can indicate implementation or deployment "
                                    + "error. Aborting export operation as a safety precaution.",
                            cachePathName.getPath(), target.getAbsolutePath(),
                            currentUserAccount.getAccount().getOid());
                }

                fileInput = new BufferedInputStream(new FileInputStream(cachePathName));

                ZipEntry entry = new ZipEntry(file.getPath());

                entry.setSize(cachePathName.length());
                entry.setTime(cachePathName.lastModified());

                zipOutput.putNextEntry(entry);

                cacheLog.debug("Added new export zip entry ''{0}''.", file.getPath());

                int count, total = 0;
                final int BUFFER_SIZE = 2048;
                byte[] data = new byte[BUFFER_SIZE];

                while ((count = fileInput.read(data, 0, BUFFER_SIZE)) != -1) {
                    zipOutput.write(data, 0, count);

                    total += count;
                }

                zipOutput.flush();

                // Sanity check...

                if (total != cachePathName.length()) {
                    throw new CacheOperationException(
                            "Only wrote {0} out of {1} bytes when archiving file ''{2}'' (Account : {3}). "
                                    + "This could have occured either due implementation error or file I/O error. "
                                    + "Aborting archive operation to prevent a potentially corrupt export archive to "
                                    + "be created.",
                            total, cachePathName.length(), cachePathName.getPath(),
                            currentUserAccount.getAccount().getOid());
                }

                else {
                    cacheLog.debug("Wrote {0} out of {1} bytes to zip entry ''{2}''", total,
                            cachePathName.length(), file.getPath());
                }
            }

            catch (SecurityException e) {
                // we've messed up deployment... quite likely unrecoverable...

                throw new ConfigurationException(
                        "Security manager has denied r/w access when attempting to read file ''{0}'' and "
                                + "write it to archive ''{1}'' (Account : {2}) : {3}",
                        e, cachePathName.getPath(), target, currentUserAccount.getAccount().getOid(),
                        e.getMessage());
            }

            catch (IllegalArgumentException e) {
                // This may occur if we overrun some fixed size limits in ZIP format...

                throw new CacheOperationException("Error creating ZIP archive for account ID = {0} : {1}", e,
                        currentUserAccount.getAccount().getOid(), e.getMessage());
            }

            catch (FileNotFoundException e) {
                throw new CacheOperationException(
                        "Attempted to include file ''{0}'' in export archive but it has gone missing "
                                + "(Account : {1}). Possible implementation error in local file cache. Aborting  "
                                + "export operation as a precaution ({2})",
                        e, cachePathName.getPath(), currentUserAccount.getAccount().getOid(), e.getMessage());
            }

            catch (ZipException e) {
                throw new CacheOperationException("Error writing export archive for account ID = {0} : {1}", e,
                        currentUserAccount.getAccount().getOid(), e.getMessage());
            }

            catch (IOException e) {
                throw new CacheOperationException(
                        "I/O error while creating export archive for account ID = {0}. "
                                + "Operation aborted ({1})",
                        e, currentUserAccount.getAccount().getOid(), e.getMessage());
            }

            finally {
                if (zipOutput != null) {
                    try {
                        zipOutput.closeEntry();
                    }

                    catch (Throwable t) {
                        cacheLog.warn(
                                "Unable to close zip entry for file ''{0}'' in export archive ''{1}'' "
                                        + "(Account : {2}) : {3}.",
                                t, file.getPath(), target.getAbsolutePath(),
                                currentUserAccount.getAccount().getOid(), t.getMessage());
                    }
                }

                if (fileInput != null) {
                    try {
                        fileInput.close();
                    }

                    catch (Throwable t) {
                        cacheLog.warn(
                                "Failed to close input stream from file ''{0}'' being added "
                                        + "to export archive (Account : {1}) : {2}",
                                t, cachePathName.getPath(), currentUserAccount.getAccount().getOid(),
                                t.getMessage());
                    }
                }
            }
        }
    }

    catch (FileNotFoundException e) {
        throw new CacheOperationException(
                "Unable to create target export archive ''{0}'' for account {1) : {2}", e, target,
                currentUserAccount.getAccount().getOid(), e.getMessage());
    }

    finally {
        try {
            if (zipOutput != null) {
                zipOutput.close();
            }
        }

        catch (Throwable t) {
            cacheLog.warn("Failed to close the stream to export archive ''{0}'' : {1}.", t, target,
                    t.getMessage());
        }
    }
}

From source file:com.orange.mmp.midlet.MidletManager.java

/**
 * Get Midlet for download.//from   w w w  .j a va  2 s.  c o  m
 * @param appId            The midlet main application ID
 * @param mobile          The mobile to use
 * @param isMidletSigned   Boolean indicating if the midlet is signed (true), unsigned (false), to sign (null)
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public ByteArrayOutputStream getJar(String appId, Mobile mobile, Boolean isMidletSigned) throws MMPException {
    if (appId == null)
        appId = ServiceManager.getInstance().getDefaultService().getId();

    //Search in Cache first
    String jarKey = appId + isMidletSigned + mobile.getKey();

    if (this.midletCache.isKeyInCache(jarKey)) {
        return (ByteArrayOutputStream) this.midletCache.get(jarKey).getValue();
    }

    Object extraCSSJadAttr = null;

    //Not found, build the JAR
    ByteArrayOutputStream output = null;
    ZipOutputStream zipOut = null;
    ZipInputStream zipIn = null;
    InputStream resourceStream = null;
    try {
        Midlet midlet = new Midlet();
        midlet.setType(mobile.getMidletType());
        Midlet[] midlets = (Midlet[]) DaoManagerFactory.getInstance().getDaoManager().getDao("midlet")
                .find(midlet);
        if (midlets.length == 0)
            throw new MMPException("Midlet type not found : " + mobile.getMidletType());
        else
            midlet = midlets[0];

        //Get navigation widget
        Widget appWidget = WidgetManager.getInstance().getWidget(appId, mobile.getBranchId());
        if (appWidget == null) {
            // Use Default if not found
            appWidget = WidgetManager.getInstance().getWidget(appId);
        }
        List<URL> embeddedResources = WidgetManager.getInstance().findWidgetResources("/m4m/", "*", appId,
                mobile.getBranchId(), false);
        output = new ByteArrayOutputStream();
        zipOut = new ZipOutputStream(output);
        zipIn = new ZipInputStream(new FileInputStream(new File(new URI(midlet.getJarLocation()))));

        ZipEntry entry;
        while ((entry = zipIn.getNextEntry()) != null) {
            zipOut.putNextEntry(entry);

            // Manifest found, modify it before delivery
            if (entry.getName().equals(Constants.JAR_MANIFEST_ENTRY) && appWidget != null) {
                Manifest midletManifest = new Manifest(zipIn);

                // TODO ? Remove optional permissions if midlet is not signed
                if (isMidletSigned != null && !isMidletSigned)
                    midletManifest.getMainAttributes().remove(Constants.JAD_PARAMETER_OPT_PERMISSIONS);

                midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_APPNAME,
                        appWidget.getName());
                String launcherLine = midletManifest.getMainAttributes()
                        .getValue(Constants.JAD_PARAMETER_LAUNCHER);
                Matcher launcherLineMatcher = launcherPattern.matcher(launcherLine);
                if (launcherLineMatcher.matches()) {
                    midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_LAUNCHER,
                            appWidget.getName().concat(", ").concat(launcherLineMatcher.group(2)).concat(", ")
                                    .concat(launcherLineMatcher.group(3)));
                } else
                    midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_LAUNCHER,
                            appWidget.getName());

                // Add/Modify/Delete MANIFEST parameters according to mobile rules
                JadAttributeAction[] jadActions = mobile.getJadAttributeActions();
                for (JadAttributeAction jadAction : jadActions) {
                    if (jadAction.getInManifest().equals(ApplyCase.ALWAYS)
                            || (isMidletSigned != null && isMidletSigned
                                    && jadAction.getInManifest().equals(ApplyCase.SIGNED))
                            || (isMidletSigned != null && !isMidletSigned
                                    && jadAction.getInManifest().equals(ApplyCase.UNSIGNED))) {
                        Attributes.Name attrName = new Attributes.Name(jadAction.getAttribute());
                        boolean exists = midletManifest.getMainAttributes().get(attrName) != null;
                        if (jadAction.isAddAction() || jadAction.isModifyAction()) {
                            if (exists || !jadAction.isStrict())
                                midletManifest.getMainAttributes().putValue(jadAction.getAttribute(),
                                        jadAction.getValue());
                        } else if (jadAction.isDeleteAction() && exists)
                            midletManifest.getMainAttributes().remove(attrName);
                    }
                }

                //Retrieve MeMo CSS extra attribute
                extraCSSJadAttr = midletManifest.getMainAttributes()
                        .get(new Attributes.Name(Constants.JAD_PARAMETER_MEMO_EXTRA_CSS));

                midletManifest.write(zipOut);
            }
            //Other files of Midlet
            else {
                IOUtils.copy(zipIn, zipOut);
            }
            zipIn.closeEntry();
            zipOut.closeEntry();
        }

        if (embeddedResources != null) {
            for (URL resourceUrl : embeddedResources) {
                resourceStream = resourceUrl.openConnection().getInputStream();
                String resourcePath = resourceUrl.getPath();
                entry = new ZipEntry(resourcePath.substring(resourcePath.lastIndexOf("/") + 1));
                entry.setTime(MIDLET_LAST_MODIFICATION_DATE);
                zipOut.putNextEntry(entry);
                IOUtils.copy(resourceStream, zipOut);
                zipOut.closeEntry();
                resourceStream.close();
            }
        }

        //Put JAR in cache for next uses
        this.midletCache.set(new Element(jarKey, output));

        //If necessary, add special CSS file if specified in JAD attributes
        if (extraCSSJadAttr != null) {
            String extraCSSSheetName = (String) extraCSSJadAttr;
            //Get resource stream
            resourceStream = WidgetManager.getInstance().getWidgetResource(
                    extraCSSSheetName + "/" + this.cssSheetsBundleName, mobile.getBranchId());

            if (resourceStream == null)
                throw new DataAccessResourceFailureException("no CSS sheet named " + extraCSSSheetName + " in "
                        + this.cssSheetsBundleName + " special bundle");

            //Append CSS sheet file into JAR
            entry = new ZipEntry(new File(extraCSSSheetName).getName());
            entry.setTime(MidletManager.MIDLET_LAST_MODIFICATION_DATE);
            zipOut.putNextEntry(entry);
            IOUtils.copy(resourceStream, zipOut);
            zipOut.closeEntry();
            resourceStream.close();
        }

        return output;

    } catch (IOException ioe) {
        throw new MMPException(ioe);
    } catch (URISyntaxException use) {
        throw new MMPException(use);
    } catch (DataAccessException dae) {
        throw new MMPException(dae);
    } finally {
        try {
            if (output != null)
                output.close();
            if (zipIn != null)
                zipIn.close();
            if (zipOut != null)
                zipOut.close();
            if (resourceStream != null)
                resourceStream.close();
        } catch (IOException ioe) {
            //NOP
        }
    }
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

@Override
public Object getPortfolio(MimeType outMimeType, String portfolioUuid, int userId, int groupId, String label,
        String resource, String files) throws Exception {
    String rootNodeUuid = getPortfolioRootNode(portfolioUuid);
    String header = "";
    String footer = "";
    NodeRight nodeRight = credential.getPortfolioRight(userId, groupId, portfolioUuid, Credential.READ);
    if (!nodeRight.read)
        return "faux";

    if (outMimeType.getSubType().equals("xml")) {
        //         header = "<portfolio xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' schemaVersion='1.0'>";
        //         footer = "</portfolio>";

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder;
        Document document = null;
        try {//  w ww  . j a  va  2  s .  c  o  m
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.newDocument();
            document.setXmlStandalone(true);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Element root = document.createElement("portfolio");
        root.setAttribute("id", portfolioUuid);
        root.setAttribute("code", "0");

        //// Noeuds supplmentaire pour WAD
        // Version
        Element verNode = document.createElement("version");
        Text version = document.createTextNode("3");
        verNode.appendChild(version);
        root.appendChild(verNode);
        // metadata-wad
        Element metawad = document.createElement("metadata-wad");
        metawad.setAttribute("prog", "main.jsp");
        metawad.setAttribute("owner", "N");
        root.appendChild(metawad);

        //          root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        //          root.setAttribute("schemaVersion", "1.0");
        document.appendChild(root);

        getLinearXml(portfolioUuid, rootNodeUuid, root, true, null, userId, groupId);

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));

        if (resource != null && files != null) {

            if (resource.equals("true") && files.equals("true")) {
                String adressedufichier = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".xml";
                String adresseduzip = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".zip";

                File file = null;
                PrintWriter ecrire;
                PrintWriter ecri;
                try {
                    file = new File(adressedufichier);
                    ecrire = new PrintWriter(new FileOutputStream(adressedufichier));
                    ecrire.println(stw.toString());
                    ecrire.flush();
                    ecrire.close();
                    System.out.print("fichier cree ");
                } catch (IOException ioe) {
                    System.out.print("Erreur : ");
                    ioe.printStackTrace();
                }

                try {
                    String fileName = portfolioUuid + ".zip";

                    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(adresseduzip));
                    zip.setMethod(ZipOutputStream.DEFLATED);
                    zip.setLevel(Deflater.BEST_COMPRESSION);
                    File dataDirectories = new File(file.getName());
                    FileInputStream fis = new FileInputStream(dataDirectories);
                    byte[] bytes = new byte[fis.available()];
                    fis.read(bytes);

                    ZipEntry entry = new ZipEntry(file.getName());
                    entry.setTime(dataDirectories.lastModified());
                    zip.putNextEntry(entry);
                    zip.write(bytes);
                    zip.closeEntry();
                    fis.close();
                    //zipDirectory(dataDirectories, zip);
                    zip.close();

                    file.delete();

                    return adresseduzip;

                } catch (FileNotFoundException fileNotFound) {
                    fileNotFound.printStackTrace();

                } catch (IOException io) {

                    io.printStackTrace();
                }
            }
        }

        return stw.toString();

    } else if (outMimeType.getSubType().equals("json")) {
        header = "{\"portfolio\": { \"-xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\"-schemaVersion\": \"1.0\",";
        footer = "}}";
    }

    return header + getNode(outMimeType, rootNodeUuid, true, userId, groupId, label).toString() + footer;
}

From source file:com.portfolio.data.provider.MysqlDataProvider.java

@Override
public Object getPortfolio(MimeType outMimeType, String portfolioUuid, int userId, int groupId, String label,
        String resource, String files, int substid) throws Exception {
    String rootNodeUuid = getPortfolioRootNode(portfolioUuid);
    String header = "";
    String footer = "";
    NodeRight nodeRight = credential.getPortfolioRight(userId, groupId, portfolioUuid, Credential.READ);
    if (!nodeRight.read) {
        userId = credential.getPublicUid();
        //         NodeRight nodeRight = new NodeRight(false,false,false,false,false,false);
        /// Vrifie les droits avec le compte publique (dernire chance)
        nodeRight = credential.getPublicRight(userId, 123, rootNodeUuid, "dummy");
        if (!nodeRight.read)
            return "faux";
    }/*from  w w w  .  j  a v  a  2s  .co  m*/

    if (outMimeType.getSubType().equals("xml")) {
        //         header = "<portfolio xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' schemaVersion='1.0'>";
        //         footer = "</portfolio>";

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder;
        Document document = null;
        try {
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.newDocument();
            document.setXmlStandalone(true);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }

        Element root = document.createElement("portfolio");
        root.setAttribute("id", portfolioUuid);
        root.setAttribute("code", "0");

        //// Noeuds supplmentaire pour WAD
        // Version
        Element verNode = document.createElement("version");
        Text version = document.createTextNode("4");
        verNode.appendChild(version);
        root.appendChild(verNode);
        // metadata-wad
        //         Element metawad = document.createElement("metadata-wad");
        //         metawad.setAttribute("prog", "main.jsp");
        //         metawad.setAttribute("owner", "N");
        //         root.appendChild(metawad);
        int owner = credential.getOwner(userId, portfolioUuid);
        String isOwner = "N";
        if (owner == userId)
            isOwner = "Y";
        root.setAttribute("owner", isOwner);

        //          root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        //          root.setAttribute("schemaVersion", "1.0");
        document.appendChild(root);

        getLinearXml(portfolioUuid, rootNodeUuid, root, true, null, userId, nodeRight.groupId,
                nodeRight.groupLabel);

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));

        if (resource != null && files != null) {
            if (resource.equals("true") && files.equals("true")) {
                String adressedufichier = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".xml";
                String adresseduzip = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".zip";

                File file = null;
                PrintWriter ecrire;
                try {
                    file = new File(adressedufichier);
                    ecrire = new PrintWriter(new FileOutputStream(adressedufichier));
                    ecrire.println(stw.toString());
                    ecrire.flush();
                    ecrire.close();
                    System.out.print("fichier cree ");
                } catch (IOException ioe) {
                    System.out.print("Erreur : ");
                    ioe.printStackTrace();
                }

                try {
                    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(adresseduzip));
                    zip.setMethod(ZipOutputStream.DEFLATED);
                    zip.setLevel(Deflater.BEST_COMPRESSION);
                    File dataDirectories = new File(file.getName());
                    FileInputStream fis = new FileInputStream(dataDirectories);
                    byte[] bytes = new byte[fis.available()];
                    fis.read(bytes);

                    ZipEntry entry = new ZipEntry(file.getName());
                    entry.setTime(dataDirectories.lastModified());
                    zip.putNextEntry(entry);
                    zip.write(bytes);
                    zip.closeEntry();
                    fis.close();
                    //zipDirectory(dataDirectories, zip);
                    zip.close();

                    file.delete();

                    return adresseduzip;
                } catch (FileNotFoundException fileNotFound) {
                    fileNotFound.printStackTrace();
                } catch (IOException io) {
                    io.printStackTrace();
                }
            }
        }

        return stw.toString();
    } else if (outMimeType.getSubType().equals("json")) {
        header = "{\"portfolio\": { \"-xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\"-schemaVersion\": \"1.0\",";
        footer = "}}";
    }

    return header + getNode(outMimeType, rootNodeUuid, true, userId, groupId, label).toString() + footer;
}