Example usage for java.util.zip ZipFile ZipFile

List of usage examples for java.util.zip ZipFile ZipFile

Introduction

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

Prototype

public ZipFile(File file) throws ZipException, IOException 

Source Link

Document

Opens a ZIP file for reading given the specified File object.

Usage

From source file:azkaban.project.AzkabanProjectLoader.java

private File unzipFile(final File archiveFile) throws IOException {
    final ZipFile zipfile = new ZipFile(archiveFile);
    final File unzipped = Utils.createTempDir(this.tempDir);
    Utils.unzip(zipfile, unzipped);/*w w  w.  j  a  v  a 2s .c  o  m*/
    zipfile.close();

    return unzipped;
}

From source file:org.n52.geoar.newdata.PluginLoader.java

/**
 * Extracts and parses the geoar-plugin.xml plugin-descriptor to create and
 * fill a {@link PluginInfo} instance.//from ww w. j a  v a  2  s .  c  om
 * 
 * @param pluginFile
 * @return
 */
private static PluginInfo readPluginInfoFromPlugin(File pluginFile) {
    try {
        ZipFile zipFile = new ZipFile(pluginFile);
        ZipEntry pluginDescriptorEntry = zipFile.getEntry("geoar-plugin.xml");
        if (pluginDescriptorEntry == null) {
            return null;
        }

        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(zipFile.getInputStream(pluginDescriptorEntry));
        // Find name
        String name = null;
        NodeList nodeList = document.getElementsByTagName("name");
        if (nodeList != null && nodeList.getLength() >= 1) {
            name = nodeList.item(0).getTextContent();
        } else {
            LOG.warn("Plugin Descriptor for " + pluginFile.getName() + " does not specify a name");
        }

        // Find publisher
        String publisher = null;
        nodeList = document.getElementsByTagName("publisher");
        if (nodeList != null && nodeList.getLength() >= 1) {
            publisher = nodeList.item(0).getTextContent();
        } else {
            LOG.warn("Plugin Descriptor for " + pluginFile.getName() + " does not specify a publisher");
        }

        // Find description
        String description = null;
        nodeList = document.getElementsByTagName("description");
        if (nodeList != null && nodeList.getLength() >= 1) {
            description = nodeList.item(0).getTextContent();
        } else {
            LOG.warn("Plugin Descriptor for " + pluginFile.getName() + " does not specify a description");
        }

        // Find identifier
        String identifier = null;
        nodeList = document.getElementsByTagName("identifier");
        if (nodeList != null && nodeList.getLength() >= 1) {
            identifier = nodeList.item(0).getTextContent();
        } else {
            LOG.warn("Plugin Descriptor for " + pluginFile.getName() + " does not specify an identifier");
        }

        // Find version
        Long version = null;
        nodeList = document.getElementsByTagName("version");
        if (nodeList != null && nodeList.getLength() >= 1) {
            String versionString = "-" + nodeList.item(0).getTextContent();

            Matcher matcher = pluginVersionPattern.matcher(versionString);
            if (matcher.find() && matcher.group(1) != null) {
                try {
                    version = parseVersionNumber(matcher.group(1));
                } catch (NumberFormatException e) {
                    LOG.error("Plugin filename version invalid: " + matcher.group(1));
                }
            }
        } else {
            LOG.warn("Plugin Descriptor for " + pluginFile.getName() + " does not specify a version");
        }

        if (identifier == null) {
            identifier = name;
        }

        return new PluginInfo(pluginFile, name, description, version, identifier, publisher);
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (ZipException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.moss.nomad.core.runner.Runner.java

private MigrationContainer extractContainer(File f) throws Exception {

    ZipFile file = new ZipFile(f);
    ZipEntry entry = new ZipEntry("META-INF/container.xml");
    InputStream in = file.getInputStream(entry);
    Unmarshaller u = context.createUnmarshaller();
    MigrationContainer container = (MigrationContainer) u.unmarshal(in);
    in.close();/*from   ww  w . ja v  a 2  s  .  co m*/
    file.close();

    return container;
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.commands.CreateUploadZipCommand.java

/**
 * Get the root directory in zip archive to build a fake directory path and
 * use ignore file to exclude zip entries. e.g. Given a zip C:\java.zip if
 * top level folder in Java.zip is Java5, it will return C:\Java.zip\Java5\
 *
 * This method is only used to build the right ignore pattern to exclude zip
 * entries/* w  w  w .  j  a  va 2 s .  c om*/
 *
 * @param zipPath
 * @return
 * @throws IOException
 */
private String getRootFolderInZip(final String zipPath) throws Exception {
    final ZipFile zipSrc = new ZipFile(zipPath);
    final Enumeration<? extends ZipEntry> entries = zipSrc.entries();

    int minBinDepth = Integer.MAX_VALUE;
    String binEntryName = null;
    final int zipDepth = LocalPath.getFolderDepth(zipPath);

    while (entries.hasMoreElements()) {
        final ZipEntry entry = entries.nextElement();
        final String parentEntryName = LocalPath.getParent(LocalPath.combine(zipPath, entry.getName()));
        final String name = LocalPath.getFileName(parentEntryName);

        if (name.equalsIgnoreCase("bin")) //$NON-NLS-1$
        {
            final int depth = LocalPath.getFolderDepth(parentEntryName);
            if (minBinDepth > depth) {
                minBinDepth = depth;
                binEntryName = parentEntryName;
            }
            if (minBinDepth == zipDepth + 1) {
                break;
            }
        }
    }

    if (binEntryName != null) {
        return LocalPath.getParent(binEntryName);
    } else {
        errorMsg = MessageFormat.format(
                Messages.getString("CreateUploadZipCommand.InvalidArchiveErrorMessageFormat"), //$NON-NLS-1$
                buildToolName);
        log.error("Invalid archive " + zipPath); //$NON-NLS-1$
        throw new Exception("The archive does not contain valid " + buildToolName); //$NON-NLS-1$
    }
}

From source file:gdt.data.entity.facet.ExtensionHandler.java

public static InputStream getResourceStream(Entigrator entigrator, String extension$, String resource$) {
    try {//from w ww  .  j  av  a 2 s  .  c o  m

        System.out.println(
                "ExtensionHandler:getResourceStream:extension=" + extension$ + " resource=" + resource$);
        Sack extension = entigrator.getEntityAtKey(extension$);
        String lib$ = extension.getElementItemAt("field", "lib");
        String jar$ = entigrator.getEntihome() + "/" + extension$ + "/" + lib$;
        //      System.out.println("ExtensionHandler:loadIcon:jar="+jar$);
        ZipFile zf = new ZipFile(jar$);
        Enumeration<? extends ZipEntry> entries = zf.entries();
        ZipEntry ze;
        String[] sa;
        while (entries.hasMoreElements()) {
            try {
                ze = entries.nextElement();
                sa = ze.getName().split("/");
                //     System.out.println("ExtensionHandler:loadIcon:zip entry="+sa[sa.length-1]);
                if (resource$.equals(sa[sa.length - 1])) {
                    InputStream is = zf.getInputStream(ze);
                    if (is != null)
                        return is;

                }
            } catch (Exception e) {

            }
        }
        return null;
    } catch (Exception e) {
        Logger.getLogger(ExtensionHandler.class.getName()).severe(e.toString());
        return null;
    }

}

From source file:io.fabric8.forge.camel.commands.CamelNewComponentsCommand.java

private String findComponentFQCN(String component, String selectedVersion) {
    String result = null;//from  w  w  w  . j a v a 2  s  . com
    InputStream stream = null;
    try {
        File tmp = File.createTempFile("camel-dep", "jar");
        URL url = new URL(String.format("https://repo1.maven.org/maven2/org/apache/camel/%s/%s/%s-%s.jar",
                component, selectedVersion, component, selectedVersion));

        FileUtils.copyURLToFile(url, tmp);

        ZipFile zipFile = new ZipFile(tmp);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.getName().startsWith("META-INF/services/org/apache/camel/component/")
                    && !entry.isDirectory()) {
                stream = zipFile.getInputStream(entry);
                Properties prop = new Properties();
                prop.load(stream);
                result = prop.getProperty("class");
                break;
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Unable to inspect added component", e);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (Exception e) {
            }
        }
    }
    return result;
}

From source file:org.openmrs.module.sdmxhdintegration.reporting.extension.SDMXHDCrossSectionalReportRenderer.java

/**
  * @see org.openmrs.module.report.renderer.ReportRenderer#render(org.openmrs.module.report.ReportData, java.lang.String, java.io.OutputStream)
  *///from   w w  w. j a  va 2 s.c  o m
@Override
public void render(ReportData reportData, String argument, OutputStream out)
        throws IOException, RenderingException {
    if (reportData.getDataSets().size() > 1) {
        throw new RenderingException(
                "This report contains multiple DataSets, this renderer does not support multiple DataSets");
    } else if (reportData.getDataSets().size() < 1) {
        throw new RenderingException("No DataSet defined in this report");
    }

    // get results dataSet
    org.openmrs.module.reporting.dataset.DataSet dataSet = reportData.getDataSets()
            .get(reportData.getDataSets().keySet().iterator().next());

    // get OMRS DSD
    Mapped<? extends DataSetDefinition> mappedOMRSDSD = reportData.getDefinition().getDataSetDefinitions()
            .get(reportData.getDefinition().getDataSetDefinitions().keySet().iterator().next());
    SDMXHDCohortIndicatorDataSetDefinition omrsDSD = (SDMXHDCohortIndicatorDataSetDefinition) mappedOMRSDSD
            .getParameterizable();

    // get SDMX-HD DSD
    SDMXHDService sdmxhdService = (SDMXHDService) Context.getService(SDMXHDService.class);
    SDMXHDMessage sdmxhdMessage = sdmxhdService.getMessage(omrsDSD.getSDMXHDMessageId());

    // get keyFamilyId
    KeyFamilyMapping keyFamilyMapping = sdmxhdService
            .getKeyFamilyMappingByReportDefinitionId(reportData.getDefinition().getId());
    String keyFamilyId = keyFamilyMapping.getKeyFamilyId();

    // get reporting month
    Date reportStartDate = (Date) reportData.getContext().getParameterValue("startDate");
    Date reportEndDate = (Date) reportData.getContext().getParameterValue("endDate");
    String timePeriod = null;

    // calculate time period and make sure reporting dates make sense
    String freq = sdmxhdMessage.getGroupElementAttributes().get("FREQ");
    if (freq != null) {
        if (freq.equals("M")) {
            // check that start and end date are the report are beginning and end day of the same month
            Calendar startCal = Calendar.getInstance();
            startCal.setTime(reportStartDate);

            int lastDay = startCal.getActualMaximum(Calendar.DAY_OF_MONTH);
            int month = startCal.get(Calendar.MONTH);
            int year = startCal.get(Calendar.YEAR);

            Calendar endCal = Calendar.getInstance();
            endCal.setTime(reportEndDate);

            if (endCal.get(Calendar.MONTH) != month || endCal.get(Calendar.DAY_OF_MONTH) != lastDay
                    || endCal.get(Calendar.YEAR) != year) {
                throw new RenderingException(
                        "Frequency is set to monthly, but the reporting stat and end date don't correspond to a start and end date of a specific month");
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            timePeriod = sdf.format(reportStartDate);

        } else if (freq.equals("A")) {
            // check start and end date are beginning and end day of same year
            Calendar startCal = Calendar.getInstance();
            startCal.setTime(reportStartDate);

            int startDay = startCal.get(Calendar.DAY_OF_MONTH);
            int startMonth = startCal.get(Calendar.MONTH);
            int startYear = startCal.get(Calendar.YEAR);

            Calendar endCal = Calendar.getInstance();
            endCal.setTime(reportEndDate);

            int endDay = startCal.get(Calendar.DAY_OF_MONTH);
            int endMonth = startCal.get(Calendar.MONTH);
            int endYear = startCal.get(Calendar.YEAR);

            if (startDay != 1 || startMonth != Calendar.JANUARY || startYear != endYear || endDay != 31
                    || endMonth != Calendar.DECEMBER) {
                throw new RenderingException(
                        "Frequency is set to annual, but the reporting start and end date are not the begining of the end day of the same year");
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            timePeriod = sdf.format(reportStartDate);
        }
        // TODO other checks
    }

    try {
        String path = Context.getAdministrationService()
                .getGlobalProperty("sdmxhdintegration.messageUploadDir");
        ZipFile zf = new ZipFile(path + File.separator + sdmxhdMessage.getZipFilename());
        SDMXHDParser parser = new SDMXHDParser();
        org.jembi.sdmxhd.SDMXHDMessage sdmxhdData = parser.parse(zf);
        DSD sdmxhdDSD = sdmxhdData.getDsd();

        //Construct CDS object
        Sender p = new Sender();
        p.setId("OMRS");
        p.setName("OpenMRS");

        Header h = new Header();
        h.setId("SDMX-HD-CSDS");
        h.setTest(false);
        h.setTruncated(false);
        h.getName().addValue("en", "OpenMRS SDMX-HD Export");
        h.setPrepared(iso8601DateFormat.format(new Date()));
        h.getSenders().add(p);

        h.setReportingBegin(iso8601DateFormat.format(reportStartDate));
        h.setReportingEnd(iso8601DateFormat.format(reportEndDate));

        // Construct dataset
        DataSet sdmxhdDataSet = new DataSet();

        sdmxhdDataSet.setReportingBeginDate(iso8601DateFormat.format(reportStartDate));
        sdmxhdDataSet.setReportingEndDate(iso8601DateFormat.format(reportEndDate));

        // Add fixed dataset attributes
        Map<String, String> datasetElementAttributes = sdmxhdMessage.getDatasetElementAttributes();
        for (String attribute : datasetElementAttributes.keySet()) {
            String value = datasetElementAttributes.get(attribute);
            if (StringUtils.hasText(value)) {
                sdmxhdDataSet.addAttribute(attribute, value);
            }
        }

        // Construct group
        Group group = new Group();

        // Set time period and frequency
        if (timePeriod != null)
            group.addAttribute("TIME_PERIOD", timePeriod);
        if (timePeriod != null)
            group.addAttribute("FREQ", freq);

        // Set DataSet attributes
        Map<String, String> dataSetAttachedAttributes = omrsDSD.getDataSetAttachedAttributes();
        for (String key : dataSetAttachedAttributes.keySet()) {
            sdmxhdDataSet.getAttributes().put(key, dataSetAttachedAttributes.get(key));
        }

        // Holder for all sections. Will hold a default section if no explicit hierarchy is found in SL_ISET
        List<Section> sectionList = new ArrayList<Section>();

        // Iterate each row and colum of the dataset
        for (DataSetRow row : dataSet) {
            for (DataSetColumn column : row.getColumnValues().keySet()) {

                CohortIndicatorAndDimensionColumn cidColumn = (CohortIndicatorAndDimensionColumn) column;
                Object value = row.getColumnValues().get(column);
                String columnName = column.getName();

                //get the indicator code for this column
                CohortIndicator indicator = cidColumn.getIndicator().getParameterizable();
                String sdmxhdIndicatorName = omrsDSD.getSDMXHDMappedIndicator(indicator.getId());

                // get indicator/dataelement codelist
                Dimension indDim = sdmxhdDSD.getIndicatorOrDataElementDimension(keyFamilyId);
                CodeList indCodeList = sdmxhdDSD.getCodeList(indDim.getCodelistRef());
                Code indCode = indCodeList.getCodeByDescription(sdmxhdIndicatorName);

                //setup or get the section for this indicator
                Section section = getSectionHelper(indCode, sectionList, sdmxhdDSD); //indicator code, listOfSections, message

                //get the dimension for the list of indicators (CL_INDICATOR)
                Dimension indDimension = sdmxhdDSD.getDimension(indCodeList);

                //construct new (SDMX-HD) obs to contain the indicator value
                Obs obs = new Obs();

                // set the indicator attribute
                obs.getAttributes().put(indDimension.getConceptRef(), indCode.getValue());

                // set Section Attributes
                Map<String, String> seriesAttachedAttributes = omrsDSD.getSeriesAttachedAttributes()
                        .get(columnName);
                if (seriesAttachedAttributes != null) {
                    for (String key : seriesAttachedAttributes.keySet()) {
                        section.getAttributes().put(key, seriesAttachedAttributes.get(key));
                    }
                }

                // write dimensions to obs
                Map<String, String> dimensionOptions = cidColumn.getDimensionOptions();
                // for each dimension option for this column
                for (String omrsDimensionId : dimensionOptions.keySet()) {
                    Integer omrsDimensionIdInt = Integer.parseInt(omrsDimensionId);
                    // find sdmx-hd dimension name in mapping
                    String sdmxhdDimensionName = null;
                    Map<String, Integer> omrsMappedDimensions = omrsDSD.getOMRSMappedDimensions();
                    for (String sdmxhdDimensionNameTemp : omrsMappedDimensions.keySet()) {
                        if (omrsMappedDimensions.get(sdmxhdDimensionNameTemp).equals(omrsDimensionIdInt)) {
                            sdmxhdDimensionName = sdmxhdDimensionNameTemp;
                            break;
                        }
                    }
                    // find sdmx-hd dimension option name in mapping
                    String omrsDimensionOptionName = dimensionOptions.get(omrsDimensionId);
                    String sdmxhdDimensionOptionName = null;
                    Map<String, String> omrsMappedDimensionOptions = omrsDSD.getOMRSMappedDimensionOptions()
                            .get(sdmxhdDimensionName);
                    for (String sdmxhdDimensionOptionNameTemp : omrsMappedDimensionOptions.keySet()) {
                        if (omrsMappedDimensionOptions.get(sdmxhdDimensionOptionNameTemp)
                                .equals(omrsDimensionOptionName)) {
                            sdmxhdDimensionOptionName = sdmxhdDimensionOptionNameTemp;
                            break;
                        }
                    }
                    //find code corresponding to this dimension option
                    Dimension sdmxhdDimension = sdmxhdDSD.getDimension(sdmxhdDimensionName, keyFamilyId);
                    CodeList codeList = sdmxhdDSD.getCodeList(sdmxhdDimension.getCodelistRef());
                    Code code = codeList.getCodeByDescription(sdmxhdDimensionOptionName);
                    obs.addAttribute(sdmxhdDimensionName, code.getValue());
                }

                // add dimensions with default values
                List<String> mappedFixedDimensions = omrsDSD.getMappedFixedDimension(columnName);
                Map<String, String> fixedDimensionValues = omrsDSD.getFixedDimensionValues();
                for (String sdmxhdDimension : mappedFixedDimensions) {
                    if (fixedDimensionValues.get(sdmxhdDimension) != null) {
                        String fixedValue = fixedDimensionValues.get(sdmxhdDimension);
                        Dimension dimension = sdmxhdDSD.getDimension(sdmxhdDimension, keyFamilyId);
                        CodeList codeList = sdmxhdDSD.getCodeList(dimension.getCodelistRef());
                        Code code = codeList.getCodeByDescription(fixedValue);
                        obs.addAttribute(sdmxhdDimension, code.getValue());
                    }
                }

                // set Obs Attributes
                Map<String, String> obsAttachedAttributes = omrsDSD.getObsAttachedAttributes().get(columnName);
                if (obsAttachedAttributes != null) {
                    for (String key : obsAttachedAttributes.keySet()) {
                        obs.getAttributes().put(key, obsAttachedAttributes.get(key));
                    }
                }

                String primaryMeasure = sdmxhdDSD.getKeyFamily(keyFamilyId).getComponents().getPrimaryMeasure()
                        .getConceptRef();
                obs.elementName = primaryMeasure;

                // write value
                if (value instanceof CohortIndicatorAndDimensionResult) {
                    CohortIndicatorAndDimensionResult typedValue = (CohortIndicatorAndDimensionResult) value;
                    obs.getAttributes().put("value", typedValue.getValue().toString());
                } else {
                    obs.getAttributes().put("value", value.toString());
                }

                section.getObs().add(obs);
            }
        }

        // Add all sections to group
        for (Section section : sectionList) {
            group.getSections().add(section);
        }

        // Add group to dataset
        sdmxhdDataSet.getGroups().add(group);

        CSDS csds = new CSDS();
        csds.getDatasets().add(sdmxhdDataSet);
        csds.setHeader(h);

        // build up namespace
        KeyFamily keyFamily = sdmxhdDSD.getKeyFamily(keyFamilyId);
        String derivedNamespace = Constants.DERIVED_NAMESPACE_PREFIX + keyFamily.getAgencyID() + ":"
                + keyFamily.getId() + ":" + keyFamily.getVersion() + ":cross";
        String xml = csds.toXML(derivedNamespace);

        // output csds in original zip
        zf = new ZipFile(path + File.separator + sdmxhdMessage.getZipFilename());
        Utils.outputCsdsInDsdZip(zf, xml, out);
    } catch (IllegalArgumentException e) {
        log.error("Error generated", e);
        throw new RenderingException("Error rendering the SDMX-HD message: " + e.getMessage(), e);
    } catch (XMLStreamException e) {
        log.error("Error generated", e);
        throw new RenderingException("Error rendering the SDMX-HD message: " + e.getMessage(), e);
    } catch (ExternalRefrenceNotFoundException e) {
        log.error("Error generated", e);
        throw new RenderingException("Error rendering the SDMX-HD message: " + e.getMessage(), e);
    } catch (IllegalAccessException e) {
        log.error("Error generated", e);
        throw new RenderingException("Error rendering the SDMX-HD message: " + e.getMessage(), e);
    } catch (ValidationException e) {
        log.error("Error generated", e);
        throw new RenderingException("Error rendering the SDMX-HD message: " + e.getMessage(), e);
    } catch (SchemaValidationException e) {
        log.error("Error generated", e);
        throw new RenderingException("Error rendering the SDMX-HD message: " + e.getMessage(), e);
    }
}

From source file:lucee.commons.io.compress.CompressUtil.java

private static void unzip2(File zipFile, Resource targetDir) throws IOException {
    ZipFile zf = null;// w w w  .j a va  2  s. c  om
    try {
        zf = new ZipFile(zipFile);

        ZipEntry entry;
        Enumeration en = zf.entries();
        while (en.hasMoreElements()) {
            entry = (ZipEntry) en.nextElement();
            Resource target = targetDir.getRealResource(entry.getName());
            if (entry.isDirectory()) {
                target.mkdirs();
            } else {
                Resource parent = target.getParentResource();
                if (!parent.exists())
                    parent.mkdirs();
                InputStream is = zf.getInputStream(entry);
                IOUtil.copy(is, target, true);
            }
            target.setLastModified(entry.getTime());
        }
    } finally {
        IOUtil.closeEL(zf);
    }
}

From source file:com.pari.mw.api.execute.reports.template.ReportTemplateRunner.java

private File[] exportReport(ReportTemplateRequestDef templateRequestDef, Map<String, String> varValues,
        String directoryName, ExportFormat format, ServerIfProvider serverIfProvider, ExportInfo exportInfo,
        int customerIdOfTemplate, String customerNameOfTemplate, String templateId) throws PariException {
    // transformation resources
    File topLevelFolder = null;/* www. j  a v a  2 s.co m*/
    try {
        topLevelFolder = getTopLevelFolder(new File(zipFileName));
    } catch (IOException e1) {
        logger.error("Unable to get top level folder of zip file " + zipFileName);
    }

    // unzip the template
    String outDirName = directoryName + "/" + topLevelFolder.getName();
    UnzipDir.unzip(zipFileName, directoryName);

    File outDir = new File(outDirName);

    /*
     * if ((valueMap != null) && (valueMap.size() > 0)) { varValues.putAll(valueMap); }
     */
    ReportTemplateMetaInfo templateMetaInfo = null;
    try {
        templateMetaInfo = ReportTemplateDefManagerImpl.getInstance().getTemplateMetaInfo(templateId,
                customerIdOfTemplate);
        if (templateMetaInfo != null && templateMetaInfo.getSourceType() == IC_SOURCE_TYPE.ICF) {
            // device count considered as 1 as report template wont be executed per device.
            ICManager.getInstance().validateLicense(customerIdOfTemplate, templateMetaInfo.getIdentifier(), 1);
        }
    } catch (Exception e) {
        if (templateMetaInfo != null) {
            logger.warn("No sufficient license to run " + templateMetaInfo.getTitle() + " - " + e.getMessage());
        } else {
            logger.warn("No sufficient license to run.Failed to get ReportTemplateMetaInfo for " + templateId
                    + " - " + e.getMessage());
        }
        throw new PariException(e.getMessage());
    }

    FileOutputStream fos = null;
    try {
        // ReportExportFactory.createDirectories(outDir.getAbsolutePath());TODO
        fos = new FileOutputStream(new File(outDir, templateIndexDef.getIdentifier() + ".xml"));
        ReportTemplateExecutor executor = new ReportTemplateExecutor(templateIndexDef, templateRequestDef);
        executor.setUserDetails(getUserDetails());
        executor.setDevices(new HashSet<Integer>(getSelectedDevices()));
        executor.execute(selectedDevices, parameters, varValues, fos, serverIfProvider, customerIdOfTemplate,
                customerNameOfTemplate);
    } catch (Exception e) {
        logger.error("Error while exporting the report", e);
        throw new PariException(ShadowWrapper.getString("Error_While_Report_Export"));
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                logger.warn("Error while closing the output stream");
            }
        }
    }

    FileInputStream xml = null;
    FileOutputStream os = null;
    InputStream xsl = null;
    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(new File(zipFileName));

        // transformation file
        String xslFileName = templateIndexDef.getTransformationFileMap().get(format);
        xsl = getInputStream(zipFile, xslFileName);

        // intermediate xml with data
        xml = new FileInputStream(new File(outDir, templateIndexDef.getIdentifier() + ".xml"));

        File outputFile = null;

        outputFile = new File(outDir.getAbsolutePath(),
                templateIndexDef.getIdentifier() + "." + format.getDefaultExtension());
        os = new FileOutputStream(outputFile);
        if (format == ExportFormat.WEB_PAGE_COMPLETE) {

            ReportExporter.exportToHtml(xml, xsl, os, outDir);
        } else if (format == ExportFormat.MSWORD_DOCUMENT) {

            ReportExporter.exportToHtml(xml, xsl, os, outDir);
        } else if (format == ExportFormat.ADOBE_PDF) {

            ReportExporter.exportToPDF(xml, xsl, os, outDir);
        }

        // cleanup
        if (xml != null) {
            try {
                xml.close();
            } catch (IOException ioe) {
                logger.warn("Could not close the InputStream" + xml, ioe);
            }
        }

        if (xsl != null) {
            try {
                xsl.close();
            } catch (IOException ioe) {
                logger.warn("Could not close the InputStream" + xsl, ioe);
            }
        }

        if (os != null) {
            try {
                os.close();
            } catch (IOException ioe) {
                logger.warn("Could not close the OutputStream" + os, ioe);
            }
        }

        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (Exception e) {
                logger.warn("Unable to close zip file.");
            }

            File file = new File(zipFileName);
            if (!file.delete()) {
                logger.warn("Unable to delete zip file.");
            }
        }

        // Cleanup the additional xml and png files created.
        File tempXmlFile = new File(outDir, templateIndexDef.getIdentifier() + ".xml");

        // Delete temp file // TODO:- Not deleting. Required to write XSL.

        try {
            if (tempXmlFile.exists()) {
                if (!tempXmlFile.delete()) {
                    logger.error("Could not delete the temporary xml file after" + " exporting the report: "
                            + tempXmlFile.getAbsolutePath());
                }
            }
        } catch (SecurityException se) {
            logger.error("Exception while deleting temporary xml file." + se);
        }

        String fileName = directoryName + "/" + topLevelFolder.getName() + "_" + exportInfo.getTaskID()
                + ".zip";
        ZIPProcessor.zipDirectory(outDirName, fileName);
        updateExportInfo(new File(fileName), exportInfo);

        if (templateMetaInfo != null && templateMetaInfo.getSourceType() == IC_SOURCE_TYPE.ICF) {
            ICStatisticsManager.getInstance().populateICUsageStatisticsInfo(templateMetaInfo, 1);
        }

        return new File[] { outDir, outputFile };
    } catch (Exception ex) {
        logger.warn(ex.getMessage());
        throw new PariException(ShadowWrapper.getString("Error_While_Report_Export") + "\n" + ex.getMessage());
    } finally {
        try {
            if (xml != null) {
                xml.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        try {
            if (os != null) {
                os.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}