Example usage for org.apache.commons.compress.archivers ArchiveOutputStream finish

List of usage examples for org.apache.commons.compress.archivers ArchiveOutputStream finish

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers ArchiveOutputStream finish.

Prototype

public abstract void finish() throws IOException;

Source Link

Document

Finishes the addition of entries to this stream, without closing it.

Usage

From source file:org.eclipse.winery.generators.ia.Generator.java

/**
 * Packages the generated project into a ZIP file which is stored in outDir
 * and has the name of the Project.//w  ww  . j  a  v a2s .  co m
 * 
 * @return ZIP file
 */
private File packageProject() {
    try {
        File packagedProject = new File(this.outDir.getAbsoluteFile() + File.separator + this.name + ".zip");
        FileOutputStream fileOutputStream = new FileOutputStream(packagedProject);
        final ArchiveOutputStream zos = new ArchiveStreamFactory().createArchiveOutputStream("zip",
                fileOutputStream);

        this.addFilesRecursively(this.workingDir.getAbsoluteFile(),
                this.workingDir.getAbsoluteFile().getAbsolutePath() + File.separator, zos);

        zos.finish();
        zos.close();

        return packagedProject;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.eclipse.winery.repository.export.CSARExporter.java

/**
 * Writes a complete CSAR containing all necessary things reachable from the given service
 * template/* w w w . j a v  a  2s  .  com*/
 * 
 * @param id the id of the service template to export
 * @param out the outputstream to write to
 * @throws JAXBException
 */
public void writeCSAR(TOSCAComponentId entryId, OutputStream out)
        throws ArchiveException, IOException, XMLStreamException, JAXBException {
    CSARExporter.logger.trace("Starting CSAR export with {}", entryId.toString());

    Map<RepositoryFileReference, String> refMap = new HashMap<RepositoryFileReference, String>();
    Collection<String> definitionNames = new ArrayList<>();

    final ArchiveOutputStream zos = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);

    TOSCAExportUtil exporter = new TOSCAExportUtil();
    Map<String, Object> conf = new HashMap<>();

    ExportedState exportedState = new ExportedState();

    TOSCAComponentId currentId = entryId;
    do {
        String defName = CSARExporter.getDefinitionsPathInsideCSAR(currentId);
        definitionNames.add(defName);

        zos.putArchiveEntry(new ZipArchiveEntry(defName));
        Collection<TOSCAComponentId> referencedIds;
        try {
            referencedIds = exporter.exportTOSCA(currentId, zos, refMap, conf, null);
        } catch (IllegalStateException e) {
            // thrown if something went wrong inside the repo
            out.close();
            // we just rethrow as there currently is no error stream.
            throw e;
        }
        zos.closeArchiveEntry();

        exportedState.flagAsExported(currentId);
        exportedState.flagAsExportRequired(referencedIds);

        currentId = exportedState.pop();
    } while (currentId != null);

    // if we export a ServiceTemplate, data for the self-service portal might exist
    if (entryId instanceof ServiceTemplateId) {
        this.addSelfServiceMetaData((ServiceTemplateId) entryId, refMap);
    }

    // now, refMap contains all files to be added to the CSAR

    // write manifest directly after the definitions to have it more at the beginning of the ZIP
    // rather than having it at the very end
    this.addManifest(entryId, definitionNames, refMap, zos);

    // used for generated XSD schemas
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        transformer = tFactory.newTransformer();
    } catch (TransformerConfigurationException e1) {
        CSARExporter.logger.debug(e1.getMessage(), e1);
        throw new IllegalStateException("Could not instantiate transformer", e1);
    }

    // write all referenced files
    for (RepositoryFileReference ref : refMap.keySet()) {
        String archivePath = refMap.get(ref);

        archivePath = replaceBPMN4Tosca2BPELPath(archivePath, ref.getFileName(), entryId);
        ref = replaceBPMN4Tosca2BPELRef(archivePath, ref);

        CSARExporter.logger.trace("Creating {}", archivePath);
        ArchiveEntry archiveEntry = new ZipArchiveEntry(archivePath);
        zos.putArchiveEntry(archiveEntry);
        if (ref instanceof DummyRepositoryFileReferenceForGeneratedXSD) {
            CSARExporter.logger.trace("Special treatment for generated XSDs");
            Document document = ((DummyRepositoryFileReferenceForGeneratedXSD) ref).getDocument();
            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(zos);
            try {
                transformer.transform(source, result);
            } catch (TransformerException e) {
                CSARExporter.logger.debug("Could not serialize generated xsd", e);
            }
        } else {
            try (InputStream is = Repository.INSTANCE.newInputStream(ref)) {
                IOUtils.copy(is, zos);
            } catch (Exception e) {
                CSARExporter.logger.error("Could not copy file content to ZIP outputstream", e);
            }
        }
        zos.closeArchiveEntry();
    }

    this.addNamespacePrefixes(zos);

    deleteFiles(tempFiles.toArray(new File[tempFiles.size()]));
    zos.finish();
    zos.close();
}

From source file:org.eclipse.winery.repository.export.ZipExporter.java

/**
 * Writes a complete CSAR containing all necessary things reachable from the given service
 * template/*from w w w .j a v  a 2s  .  co m*/
 * 
 * @param id the id of the service template to export
 * @param out the outputstream to write to
 * @throws JAXBException
 */
public void writeZip(TOSCAComponentId entryId, OutputStream out)
        throws ArchiveException, IOException, XMLStreamException, JAXBException {
    ZipExporter.logger.trace("Starting CSAR export with {}", entryId.toString());

    Map<RepositoryFileReference, String> refMap = new HashMap<RepositoryFileReference, String>();
    Collection<String> definitionNames = new ArrayList<>();

    final ArchiveOutputStream zos = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);

    TOSCAExportUtil exporter = new TOSCAExportUtil();
    Map<String, Object> conf = new HashMap<>();

    ExportedState exportedState = new ExportedState();

    TOSCAComponentId currentId = entryId;
    do {
        logger.info("begin to scan class:" + System.currentTimeMillis());
        Reflections reflections = new Reflections("org.eclipse.winery.repository.ext");
        Set<Class<? extends ExportFileGenerator>> implenmetions = reflections
                .getSubTypesOf(org.eclipse.winery.repository.ext.export.custom.ExportFileGenerator.class);
        logger.info("end to scan class:" + System.currentTimeMillis());
        Iterator<Class<? extends ExportFileGenerator>> it = implenmetions.iterator();
        Collection<TOSCAComponentId> referencedIds = null;

        String defName = ZipExporter.getDefinitionsPathInsideCSAR(currentId);
        definitionNames.add(defName);

        zos.putArchiveEntry(new ZipArchiveEntry(defName));

        try {
            referencedIds = exporter.exportTOSCA(currentId, zos, refMap, conf, null);
        } catch (IllegalStateException e) {
            // thrown if something went wrong inside the repo
            out.close();
            // we just rethrow as there currently is no error stream.
            throw e;
        }
        zos.closeArchiveEntry();

        while (it.hasNext()) {
            Class<? extends ExportFileGenerator> exportClass = it.next();
            logger.trace("the " + exportClass.toString() + "begin to write file");
            try {
                if (!Modifier.isAbstract(exportClass.getModifiers())) {
                    ExportFileGenerator fileGenerator = exportClass.newInstance();
                    referencedIds = exporter.exportTOSCA(currentId, zos, refMap, conf, fileGenerator);
                }
            } catch (InstantiationException e) {
                logger.error("export error occur while instancing " + exportClass.toString(), e);
                out.close();
            } catch (IllegalAccessException e) {
                logger.error("export error occur", e);
                out.close();
            }
        }

        exportedState.flagAsExported(currentId);
        exportedState.flagAsExportRequired(referencedIds);

        currentId = exportedState.pop();
    } while (currentId != null);

    // if we export a ServiceTemplate, data for the self-service portal might exist
    if (entryId instanceof ServiceTemplateId) {
        this.addSelfServiceMetaData((ServiceTemplateId) entryId, refMap);
        addCsarMeta((ServiceTemplateId) entryId, zos);
    }

    // write custom file
    CustomizedFileInfos customizedResult = null;
    if (entryId instanceof ServiceTemplateId) {
        customizedResult = this.exportCustomFiles((ServiceTemplateId) entryId, zos);
    }

    // write manifest directly after the definitions to have it more at the beginning of the ZIP
    // rather than having it at the very end
    this.addManifest(entryId, definitionNames, refMap, zos);
    this.addManiYamlfest(entryId, exporter.getYamlExportDefResultList(), refMap, zos, exporter);
    this.addCheckSumFest(
            getCheckSums(exporter.getYamlExportDefResultList(), customizedResult.getCustomizedFileResults()),
            zos);
    // used for generated XSD schemas
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        transformer = tFactory.newTransformer();
    } catch (TransformerConfigurationException e1) {
        ZipExporter.logger.debug(e1.getMessage(), e1);
        throw new IllegalStateException("Could not instantiate transformer", e1);
    }

    // write all referenced files
    for (RepositoryFileReference ref : refMap.keySet()) {
        String archivePath = refMap.get(ref);
        ZipExporter.logger.trace("Creating {}", archivePath);
        ArchiveEntry archiveEntry = new ZipArchiveEntry("xml/" + archivePath);
        zos.putArchiveEntry(archiveEntry);
        if (ref instanceof DummyRepositoryFileReferenceForGeneratedXSD) {
            ZipExporter.logger.trace("Special treatment for generated XSDs");
            Document document = ((DummyRepositoryFileReferenceForGeneratedXSD) ref).getDocument();
            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(zos);
            try {
                transformer.transform(source, result);
            } catch (TransformerException e) {
                ZipExporter.logger.debug("Could not serialize generated xsd", e);
            }
        } else {
            try (InputStream is = Repository.INSTANCE.newInputStream(ref)) {
                IOUtils.copy(is, zos);
            } catch (Exception e) {
                ZipExporter.logger.error("Could not copy file content to ZIP outputstream", e);
            }
        }

        // add plan files/artifact templantes to yaml folder
        updatePlanDef(archivePath, ref, zos, customizedResult.getPlanInfos());

        zos.closeArchiveEntry();
    }

    addPlan2Zip(customizedResult.getPlanInfos(), zos);
    this.addNamespacePrefixes(zos);

    zos.finish();
    zos.close();
}

From source file:org.kaaproject.kaa.server.control.service.sdk.CppSdkGenerator.java

@Override
public FileData generateSdk(String buildVersion, List<BootstrapNodeInfo> bootstrapNodes,
        SdkProfileDto sdkProfile, String profileSchemaBody, String notificationSchemaBody,
        String configurationProtocolSchemaBody, String configurationBaseSchema, byte[] defaultConfigurationData,
        List<EventFamilyMetadata> eventFamilies, String logSchemaBody) throws Exception {

    String sdkToken = sdkProfile.getToken();
    Integer configurationSchemaVersion = sdkProfile.getConfigurationSchemaVersion();
    final Integer profileSchemaVersion = sdkProfile.getProfileSchemaVersion();
    Integer notificationSchemaVersion = sdkProfile.getNotificationSchemaVersion();
    Integer logSchemaVersion = sdkProfile.getLogSchemaVersion();
    String defaultVerifierToken = sdkProfile.getDefaultVerifierToken();

    String sdkTemplateLocation = Environment.getServerHomeDir() + "/" + CPP_SDK_DIR + "/" + CPP_SDK_PREFIX
            + buildVersion + ".tar.gz";

    LOG.debug("Lookup Java SDK template: {}", sdkTemplateLocation);

    CompressorStreamFactory csf = new CompressorStreamFactory();
    ArchiveStreamFactory asf = new ArchiveStreamFactory();

    CompressorInputStream cis = csf.createCompressorInputStream(CompressorStreamFactory.GZIP,
            new FileInputStream(sdkTemplateLocation));

    final ArchiveInputStream templateArchive = asf.createArchiveInputStream(ArchiveStreamFactory.TAR, cis);

    ByteArrayOutputStream sdkOutput = new ByteArrayOutputStream();
    CompressorOutputStream cos = csf.createCompressorOutputStream(CompressorStreamFactory.GZIP, sdkOutput);

    ArchiveOutputStream sdkFile = asf.createArchiveOutputStream(ArchiveStreamFactory.TAR, cos);

    Map<String, TarEntryData> replacementData = new HashMap<>();

    List<TarEntryData> cppSources = new ArrayList<>();

    // TODO: remove all version fields and add single sdkToken field
    // create entry for default properties
    TarArchiveEntry entry = new TarArchiveEntry(SDK_DEFAULTS_PATH);
    byte[] data = generateKaaDefaults(bootstrapNodes, sdkToken, defaultConfigurationData, defaultVerifierToken);

    entry.setSize(data.length);/*from  www . j a va  2 s.  com*/
    TarEntryData tarEntry = new TarEntryData(entry, data);
    cppSources.add(tarEntry);

    Map<String, String> profileVars = new HashMap<>();
    profileVars.put(SDK_PROFILE_VERSION_VAR, profileSchemaVersion.toString());
    cppSources.addAll(processFeatureSchema(profileSchemaBody, PROFILE_SCHEMA_AVRO_SRC,
            PROFILE_DEFINITIONS_TEMPLATE, PROFILE_DEFINITIONS_PATH, profileVars));

    cppSources.addAll(processFeatureSchema(notificationSchemaBody, NOTIFICATION_SCHEMA_AVRO_SRC,
            NOTIFICATION_DEFINITIONS_TEMPLATE, NOTIFICATION_DEFINITIONS_PATH, null));
    cppSources.addAll(processFeatureSchema(logSchemaBody, LOG_SCHEMA_AVRO_SRC, LOG_DEFINITIONS_TEMPLATE,
            LOG_DEFINITIONS_PATH, null));
    cppSources.addAll(processFeatureSchema(configurationBaseSchema, CONFIGURATION_SCHEMA_AVRO_SRC,
            CONFIGURATION_DEFINITIONS_TEMPLATE, CONFIGURATION_DEFINITIONS_PATH, null));

    if (eventFamilies != null && !eventFamilies.isEmpty()) {
        cppSources.addAll(CppEventSourcesGenerator.generateEventSources(eventFamilies));
    }

    for (TarEntryData entryData : cppSources) {
        replacementData.put(entryData.getEntry().getName(), entryData);
    }

    ArchiveEntry archiveEntry;
    while ((archiveEntry = templateArchive.getNextEntry()) != null) {
        if (!archiveEntry.isDirectory()) {
            if (replacementData.containsKey(archiveEntry.getName())) {
                TarEntryData entryData = replacementData.remove(archiveEntry.getName());
                sdkFile.putArchiveEntry(entryData.getEntry());
                sdkFile.write(entryData.getData());
            } else {
                sdkFile.putArchiveEntry(archiveEntry);
                IOUtils.copy(templateArchive, sdkFile);
            }
        } else {
            sdkFile.putArchiveEntry(archiveEntry);
        }
        sdkFile.closeArchiveEntry();
    }

    templateArchive.close();

    for (String entryName : replacementData.keySet()) {
        TarEntryData entryData = replacementData.get(entryName);
        sdkFile.putArchiveEntry(entryData.getEntry());
        sdkFile.write(entryData.getData());
        sdkFile.closeArchiveEntry();
    }

    sdkFile.finish();
    sdkFile.close();

    String sdkFileName = CPP_SDK_PREFIX + sdkProfile.getToken() + ".tar.gz";

    byte[] sdkData = sdkOutput.toByteArray();

    FileData sdk = new FileData();
    sdk.setFileName(sdkFileName);
    sdk.setFileData(sdkData);
    return sdk;
}

From source file:org.kaaproject.kaa.server.control.service.sdk.CSdkGenerator.java

@Override
public FileData generateSdk(String buildVersion, List<BootstrapNodeInfo> bootstrapNodes,
        SdkProfileDto sdkProfile, String profileSchemaBody, String notificationSchemaBody,
        String configurationProtocolSchemaBody, String configurationBaseSchemaBody,
        byte[] defaultConfigurationData, List<EventFamilyMetadata> eventFamilies, String logSchemaBody)
        throws Exception {

    String sdkToken = sdkProfile.getToken();
    Integer profileSchemaVersion = sdkProfile.getProfileSchemaVersion();
    String defaultVerifierToken = sdkProfile.getDefaultVerifierToken();

    String sdkTemplateLocation = Environment.getServerHomeDir() + "/" + C_SDK_DIR + "/" + C_SDK_PREFIX
            + buildVersion + ".tar.gz";

    LOG.debug("Lookup C SDK template: {}", sdkTemplateLocation);

    CompressorStreamFactory csf = new CompressorStreamFactory();
    ArchiveStreamFactory asf = new ArchiveStreamFactory();

    CompressorInputStream cis = csf.createCompressorInputStream(CompressorStreamFactory.GZIP,
            new FileInputStream(sdkTemplateLocation));

    final ArchiveInputStream templateArchive = asf.createArchiveInputStream(ArchiveStreamFactory.TAR, cis);

    ByteArrayOutputStream sdkOutput = new ByteArrayOutputStream();
    CompressorOutputStream cos = csf.createCompressorOutputStream(CompressorStreamFactory.GZIP, sdkOutput);

    ArchiveOutputStream sdkFile = asf.createArchiveOutputStream(ArchiveStreamFactory.TAR, cos);

    Map<String, TarEntryData> replacementData = new HashMap<>();

    List<TarEntryData> sources = new ArrayList<>();

    if (!StringUtils.isBlank(profileSchemaBody)) {
        sources.addAll(generateProfileSources(profileSchemaBody));
    }//  w w  w.  j  a va  2 s .c o m

    if (!StringUtils.isBlank(logSchemaBody)) {
        sources.addAll(generateLogSources(logSchemaBody));
    }

    if (!StringUtils.isBlank(configurationBaseSchemaBody)) {
        sources.addAll(generateConfigurationSources(configurationBaseSchemaBody));
    }

    if (!StringUtils.isBlank(notificationSchemaBody)) {
        sources.addAll(generateNotificationSources(notificationSchemaBody));
    }

    if (eventFamilies != null && !eventFamilies.isEmpty()) {
        sources.addAll(CEventSourcesGenerator.generateEventSources(eventFamilies));
    }

    for (TarEntryData entryData : sources) {
        replacementData.put(entryData.getEntry().getName(), entryData);
    }

    ArchiveEntry archiveEntry;
    while ((archiveEntry = templateArchive.getNextEntry()) != null) {
        if (!archiveEntry.isDirectory()) {
            if (archiveEntry.getName().equals(KAA_DEFAULTS_HEADER)) {
                // TODO: eliminate schema versions and substitute them for a single sdkToken
                byte[] kaaDefaultsData = generateKaaDefaults(bootstrapNodes, sdkToken, profileSchemaVersion,
                        configurationProtocolSchemaBody, defaultConfigurationData, defaultVerifierToken);

                TarArchiveEntry kaaDefaultsEntry = new TarArchiveEntry(KAA_DEFAULTS_HEADER);
                kaaDefaultsEntry.setSize(kaaDefaultsData.length);
                sdkFile.putArchiveEntry(kaaDefaultsEntry);
                sdkFile.write(kaaDefaultsData);
            } else if (archiveEntry.getName().equals(KAA_CMAKEGEN)) {
                // Ignore duplicate source names
                List<String> sourceNames = new LinkedList<>();
                for (TarEntryData sourceEntry : sources) {
                    String fileName = sourceEntry.getEntry().getName();
                    if (fileName.endsWith(C_SOURCE_SUFFIX) && !sourceNames.contains(fileName)) {
                        sourceNames.add(fileName);
                    }
                }

                VelocityContext context = new VelocityContext();
                context.put("sourceNames", sourceNames);
                String sourceData = generateSourceFromTemplate(TEMPLATE_DIR + File.separator + "CMakeGen.vm",
                        context);

                TarArchiveEntry kaaCMakeEntry = new TarArchiveEntry(KAA_CMAKEGEN);
                kaaCMakeEntry.setSize(sourceData.length());
                sdkFile.putArchiveEntry(kaaCMakeEntry);
                sdkFile.write(sourceData.getBytes());
            } else if (replacementData.containsKey(archiveEntry.getName())) {
                TarEntryData entryData = replacementData.remove(archiveEntry.getName());
                sdkFile.putArchiveEntry(entryData.getEntry());
                sdkFile.write(entryData.getData());
            } else {
                sdkFile.putArchiveEntry(archiveEntry);
                IOUtils.copy(templateArchive, sdkFile);
            }
        } else {
            sdkFile.putArchiveEntry(archiveEntry);
        }

        sdkFile.closeArchiveEntry();
    }

    templateArchive.close();

    for (String entryName : replacementData.keySet()) {
        TarEntryData entryData = replacementData.get(entryName);
        sdkFile.putArchiveEntry(entryData.getEntry());
        sdkFile.write(entryData.getData());
        sdkFile.closeArchiveEntry();
    }

    sdkFile.finish();
    sdkFile.close();

    String sdkFileName = C_SDK_PREFIX + sdkProfile.getToken() + ".tar.gz";

    FileData sdk = new FileData();
    sdk.setFileName(sdkFileName);
    sdk.setFileData(sdkOutput.toByteArray());

    return sdk;
}

From source file:org.kaaproject.kaa.server.control.service.sdk.ObjCSdkGenerator.java

@Override
public FileData generateSdk(String buildVersion, List<BootstrapNodeInfo> bootstrapNodes,
        SdkProfileDto sdkProperties, String profileSchemaBody, String notificationSchemaBody,
        String configurationProtocolSchemaBody, String configurationBaseSchemaBody,
        byte[] defaultConfigurationData, List<EventFamilyMetadata> eventFamilies, String logSchemaBody)
        throws Exception {

    final String sdkToken = sdkProperties.getToken();
    final String defaultVerifierToken = sdkProperties.getDefaultVerifierToken();

    String sdkTemplateLocation = System.getProperty("server_home_dir") + "/" + SDK_TEMPLATE_DIR + SDK_PREFIX
            + buildVersion + ".tar.gz";

    LOG.debug("Lookup Objective C SDK template: {}", sdkTemplateLocation);

    CompressorStreamFactory csf = new CompressorStreamFactory();
    ArchiveStreamFactory asf = new ArchiveStreamFactory();

    CompressorInputStream cis = csf.createCompressorInputStream(CompressorStreamFactory.GZIP,
            new FileInputStream(sdkTemplateLocation));

    final ArchiveInputStream templateArchive = asf.createArchiveInputStream(ArchiveStreamFactory.TAR, cis);

    ByteArrayOutputStream sdkOutput = new ByteArrayOutputStream();
    CompressorOutputStream cos = csf.createCompressorOutputStream(CompressorStreamFactory.GZIP, sdkOutput);

    ArchiveOutputStream sdkFile = asf.createArchiveOutputStream(ArchiveStreamFactory.TAR, cos);

    Map<String, TarEntryData> replacementData = new HashMap<>();

    List<TarEntryData> objcSources = new ArrayList<>();

    if (StringUtils.isNotBlank(profileSchemaBody)) {
        LOG.debug("Generating profile schema");
        Schema profileSchema = new Schema.Parser().parse(profileSchemaBody);
        String profileClassName = PROFILE_NAMESPACE + profileSchema.getName();

        String profileCommonHeader = readResource(PROFILE_TEMPLATE_DIR + PROFILE_COMMON + _H + TEMPLATE_SUFFIX)
                .replaceAll(PROFILE_CLASS_VAR, profileClassName);

        objcSources.add(CommonSdkUtil.tarEntryForSources(profileCommonHeader,
                KAA_ROOT + PROFILE_DIR + PROFILE_COMMON + _H));

        String profileCommonSource = readResource(PROFILE_TEMPLATE_DIR + PROFILE_COMMON + _M + TEMPLATE_SUFFIX)
                .replaceAll(PROFILE_CLASS_VAR, profileClassName);

        objcSources.add(CommonSdkUtil.tarEntryForSources(profileCommonSource,
                KAA_ROOT + PROFILE_DIR + PROFILE_COMMON + _M));

        objcSources.addAll(generateSourcesFromSchema(profileSchema, PROFILE_GEN, PROFILE_NAMESPACE));
    }/* w w  w . j av a  2 s.c  o  m*/

    String logClassName = "";
    if (StringUtils.isNotBlank(logSchemaBody)) {
        LOG.debug("Generating log schema");
        Schema logSchema = new Schema.Parser().parse(logSchemaBody);
        logClassName = LOGGING_NAMESPACE + logSchema.getName();

        String logRecordHeader = readResource(LOG_TEMPLATE_DIR + LOG_RECORD + _H + TEMPLATE_SUFFIX)
                .replaceAll(LOG_RECORD_CLASS_VAR, logClassName);

        objcSources
                .add(CommonSdkUtil.tarEntryForSources(logRecordHeader, KAA_ROOT + LOG_DIR + LOG_RECORD + _H));

        String logRecordSource = readResource(LOG_TEMPLATE_DIR + LOG_RECORD + _M + TEMPLATE_SUFFIX)
                .replaceAll(LOG_RECORD_CLASS_VAR, logClassName);

        objcSources
                .add(CommonSdkUtil.tarEntryForSources(logRecordSource, KAA_ROOT + LOG_DIR + LOG_RECORD + _M));

        String logCollector = readResource(LOG_TEMPLATE_DIR + LOG_COLLECTOR_INTERFACE + TEMPLATE_SUFFIX)
                .replaceAll(LOG_RECORD_CLASS_VAR, logClassName);

        objcSources.add(
                CommonSdkUtil.tarEntryForSources(logCollector, KAA_ROOT + LOG_DIR + LOG_COLLECTOR_INTERFACE));

        String logCollectorImplHeader = readResource(
                LOG_TEMPLATE_DIR + LOG_COLLECTOR_SOURCE + _H + TEMPLATE_SUFFIX).replaceAll(LOG_RECORD_CLASS_VAR,
                        logClassName);

        objcSources.add(CommonSdkUtil.tarEntryForSources(logCollectorImplHeader,
                KAA_ROOT + LOG_DIR + LOG_COLLECTOR_SOURCE + _H));

        String logCollectorImplSource = readResource(
                LOG_TEMPLATE_DIR + LOG_COLLECTOR_SOURCE + _M + TEMPLATE_SUFFIX).replaceAll(LOG_RECORD_CLASS_VAR,
                        logClassName);

        objcSources.add(CommonSdkUtil.tarEntryForSources(logCollectorImplSource,
                KAA_ROOT + LOG_DIR + LOG_COLLECTOR_SOURCE + _M));

        objcSources.addAll(generateSourcesFromSchema(logSchema, LOG_GEN, LOGGING_NAMESPACE));
    }

    String configurationClassName = "";
    if (StringUtils.isNotBlank(configurationBaseSchemaBody)) {
        LOG.debug("Generating configuration schema");
        Schema configurationSchema = new Schema.Parser().parse(configurationBaseSchemaBody);
        configurationClassName = CONFIGURATION_NAMESPACE + configurationSchema.getName();

        String configurationCommon = readResource(
                CONFIGURATION_TEMPLATE_DIR + CONFIGURATION_COMMON + TEMPLATE_SUFFIX)
                        .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

        objcSources.add(CommonSdkUtil.tarEntryForSources(configurationCommon,
                KAA_ROOT + CONFIGURATION_DIR + CONFIGURATION_COMMON));

        String cfManagerImplHeader = readResource(
                CONFIGURATION_TEMPLATE_DIR + CONFIGURATION_MANAGER_IMPL + _H + TEMPLATE_SUFFIX)
                        .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

        objcSources.add(CommonSdkUtil.tarEntryForSources(cfManagerImplHeader,
                KAA_ROOT + CONFIGURATION_DIR + CONFIGURATION_MANAGER_IMPL + _H));

        String cfManagerImplSource = readResource(
                CONFIGURATION_TEMPLATE_DIR + CONFIGURATION_MANAGER_IMPL + _M + TEMPLATE_SUFFIX)
                        .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

        objcSources.add(CommonSdkUtil.tarEntryForSources(cfManagerImplSource,
                KAA_ROOT + CONFIGURATION_DIR + CONFIGURATION_MANAGER_IMPL + _M));

        String cfDeserializerHeader = readResource(
                CONFIGURATION_TEMPLATE_DIR + CONFIGURATION_DESERIALIZER + _H + TEMPLATE_SUFFIX)
                        .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

        objcSources.add(CommonSdkUtil.tarEntryForSources(cfDeserializerHeader,
                KAA_ROOT + CONFIGURATION_DIR + CONFIGURATION_DESERIALIZER + _H));

        String cfDeserializerSource = readResource(
                CONFIGURATION_TEMPLATE_DIR + CONFIGURATION_DESERIALIZER + _M + TEMPLATE_SUFFIX)
                        .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

        objcSources.add(CommonSdkUtil.tarEntryForSources(cfDeserializerSource,
                KAA_ROOT + CONFIGURATION_DIR + CONFIGURATION_DESERIALIZER + _M));

        objcSources.addAll(
                generateSourcesFromSchema(configurationSchema, CONFIGURATION_GEN, CONFIGURATION_NAMESPACE));
    }

    if (StringUtils.isNotBlank(notificationSchemaBody)) {
        LOG.debug("Generating notification schema");
        Schema notificationSchema = new Schema.Parser().parse(notificationSchemaBody);
        String notificationClassName = NOTIFICATION_NAMESPACE + notificationSchema.getName();

        String nfCommonHeader = readResource(
                NOTIFICATION_TEMPLATE_DIR + NOTIFICATION_COMMON + _H + TEMPLATE_SUFFIX)
                        .replaceAll(NOTIFICATION_CLASS_VAR, notificationClassName);

        objcSources.add(CommonSdkUtil.tarEntryForSources(nfCommonHeader,
                KAA_ROOT + NOTIFICATION_DIR + NOTIFICATION_COMMON + _H));

        String nfCommonSource = readResource(
                NOTIFICATION_TEMPLATE_DIR + NOTIFICATION_COMMON + _M + TEMPLATE_SUFFIX)
                        .replaceAll(NOTIFICATION_CLASS_VAR, notificationClassName);

        objcSources.add(CommonSdkUtil.tarEntryForSources(nfCommonSource,
                KAA_ROOT + NOTIFICATION_DIR + NOTIFICATION_COMMON + _M));

        objcSources.addAll(
                generateSourcesFromSchema(notificationSchema, NOTIFICATION_GEN, NOTIFICATION_NAMESPACE));
    }

    if (eventFamilies != null && !eventFamilies.isEmpty()) {
        objcSources.addAll(ObjCEventClassesGenerator.generateEventSources(eventFamilies));
    }

    String kaaClient = readResource(SDK_TEMPLATE_DIR + KAA_CLIENT + TEMPLATE_SUFFIX)
            .replaceAll(LOG_RECORD_CLASS_VAR, logClassName)
            .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

    objcSources.add(CommonSdkUtil.tarEntryForSources(kaaClient, KAA_ROOT + KAA_CLIENT));

    String baseKaaClientHeader = readResource(SDK_TEMPLATE_DIR + BASE_KAA_CLIENT + _H + TEMPLATE_SUFFIX)
            .replaceAll(LOG_RECORD_CLASS_VAR, logClassName)
            .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

    objcSources.add(CommonSdkUtil.tarEntryForSources(baseKaaClientHeader, KAA_ROOT + BASE_KAA_CLIENT + _H));
    String baseKaaClientSource = readResource(SDK_TEMPLATE_DIR + BASE_KAA_CLIENT + _M + TEMPLATE_SUFFIX)
            .replaceAll(LOG_RECORD_CLASS_VAR, logClassName)
            .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

    objcSources.add(CommonSdkUtil.tarEntryForSources(baseKaaClientSource, KAA_ROOT + BASE_KAA_CLIENT + _M));

    String tokenVerifier = defaultVerifierToken == null ? "nil" : "@\"" + defaultVerifierToken + "\"";

    String tokenVerifierSource = readResource(EVENT_TEMPLATE_DIR + USER_VERIFIER_CONSTANTS + TEMPLATE_SUFFIX)
            .replaceAll(DEFAULT_USER_VERIFIER_TOKEN_VAR, tokenVerifier);

    objcSources.add(CommonSdkUtil.tarEntryForSources(tokenVerifierSource,
            KAA_ROOT + EVENT_DIR + USER_VERIFIER_CONSTANTS));

    String kaaDefaultsTemplate = readResource(SDK_TEMPLATE_DIR + KAA_DEFAULTS + TEMPLATE_SUFFIX);
    objcSources.add(generateKaaDefaults(kaaDefaultsTemplate, bootstrapNodes, sdkToken,
            configurationProtocolSchemaBody, defaultConfigurationData, sdkProperties));

    for (TarEntryData entryData : objcSources) {
        replacementData.put(entryData.getEntry().getName(), entryData);
    }

    ArchiveEntry archiveEntry;
    while ((archiveEntry = templateArchive.getNextEntry()) != null) {
        if (!archiveEntry.isDirectory()) {
            if (replacementData.containsKey(archiveEntry.getName())) {
                TarEntryData entryData = replacementData.remove(archiveEntry.getName());
                sdkFile.putArchiveEntry(entryData.getEntry());
                sdkFile.write(entryData.getData());
            } else {
                sdkFile.putArchiveEntry(archiveEntry);
                IOUtils.copy(templateArchive, sdkFile);
            }
        } else {
            sdkFile.putArchiveEntry(archiveEntry);
        }
        sdkFile.closeArchiveEntry();
    }

    templateArchive.close();

    for (String entryName : replacementData.keySet()) {
        TarEntryData entryData = replacementData.get(entryName);
        sdkFile.putArchiveEntry(entryData.getEntry());
        sdkFile.write(entryData.getData());
        sdkFile.closeArchiveEntry();
    }

    sdkFile.finish();
    sdkFile.close();

    String sdkFileName = SDK_PREFIX + sdkProperties.getToken() + ".tar.gz";

    byte[] sdkData = sdkOutput.toByteArray();

    FileData sdk = new FileData();
    sdk.setFileName(sdkFileName);
    sdk.setFileData(sdkData);
    return sdk;
}

From source file:org.openbaton.marketplace.core.VNFPackageManagement.java

public ByteArrayOutputStream compose(String id) throws IOException, ArchiveException {

    VNFPackageMetadata vnfPackageMetadata = vnfPackageMetadataRepository.findFirstById(id);
    String vnfPackageName = vnfPackageMetadata.getName();
    VirtualNetworkFunctionDescriptor vnfd = vnfPackageMetadata.getVnfd();
    VNFPackage vnfPackage = vnfPackageMetadata.getVnfPackage();
    ImageMetadata imageMetadata = vnfPackageMetadata.getImageMetadata();
    NFVImage nfvImage = vnfPackageMetadata.getNfvImage();
    String vnfdJson = mapper.toJson(vnfd);

    HashMap<String, Object> imageConfigJson = new ObjectMapper().readValue(mapper.toJson(nfvImage),
            HashMap.class);
    imageConfigJson.put("minDisk", imageConfigJson.get("minDiskSpace"));
    Object minCPU = imageConfigJson.get("minCPU");
    if (minCPU != null) {
        imageConfigJson.put("minCPU", Integer.parseInt((String) minCPU));
    } else {/* w ww  .  j  av  a 2s  .co m*/
        imageConfigJson.put("minCPU", 0);
    }
    imageConfigJson.remove("minDiskSpace");
    imageConfigJson.remove("id");
    imageConfigJson.remove("hb_version");

    HashMap<String, String> imageMetadataJson = new ObjectMapper().readValue(mapper.toJson(imageMetadata),
            HashMap.class);
    imageMetadataJson.put("link", imageMetadata.getLink());
    imageMetadataJson.remove("id");
    imageMetadataJson.remove("hb_version");

    ByteArrayOutputStream tar_output = new ByteArrayOutputStream();
    ArchiveOutputStream my_tar_ball = new ArchiveStreamFactory()
            .createArchiveOutputStream(ArchiveStreamFactory.TAR, tar_output);

    //prepare Metadata.yaml
    File tar_input_file = File.createTempFile("Metadata", null);
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("name", vnfPackageName);
    data.put("description", vnfPackageMetadata.getDescription());
    data.put("provider", vnfPackageMetadata.getProvider());
    data.put("requirements", vnfPackageMetadata.getRequirements());
    data.put("shared", vnfPackageMetadata.isShared());
    data.put("image", imageMetadataJson);
    data.put("image-config", imageConfigJson);
    data.put("scripts-link", vnfPackage.getScriptsLink());
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    Yaml yaml = new Yaml(options);
    FileWriter writer = new FileWriter(tar_input_file);
    yaml.dump(data, writer);
    TarArchiveEntry tar_file = new TarArchiveEntry(tar_input_file, "Metadata.yaml");
    tar_file.setSize(tar_input_file.length());
    my_tar_ball.putArchiveEntry(tar_file);
    IOUtils.copy(new FileInputStream(tar_input_file), my_tar_ball);
    /* Close Archieve entry, write trailer information */
    my_tar_ball.closeArchiveEntry();

    //prepare VNFD
    tar_input_file = File.createTempFile("vnfd", null);
    tar_file = new TarArchiveEntry(tar_input_file, "vnfd.json");
    writer = new FileWriter(tar_input_file);
    writer.write(vnfdJson);
    writer.close();
    tar_file.setSize(tar_input_file.length());
    my_tar_ball.putArchiveEntry(tar_file);
    IOUtils.copy(new FileInputStream(tar_input_file), my_tar_ball);
    /* Close Archieve entry, write trailer information */
    my_tar_ball.closeArchiveEntry();

    //scripts
    for (Script script : vnfPackage.getScripts()) {
        tar_input_file = File.createTempFile("script", null);
        tar_file = new TarArchiveEntry(tar_input_file, "scripts/" + script.getName());
        FileOutputStream outputStream = new FileOutputStream(tar_input_file);
        outputStream.write(script.getPayload());
        outputStream.close();
        tar_file.setSize(tar_input_file.length());
        my_tar_ball.putArchiveEntry(tar_file);
        IOUtils.copy(new FileInputStream(tar_input_file), my_tar_ball);
        my_tar_ball.closeArchiveEntry();
    }

    //close tar
    my_tar_ball.finish();
    /* Close output stream, our files are zipped */
    tar_output.close();
    return tar_output;
}

From source file:org.seadva.archive.impl.cloud.SdaArchiveStore.java

public void createTar(final File dir, final String tarFileName) {
    try {//from  w ww  .  j  av  a2  s. c  o m
        OutputStream tarOutput = new FileOutputStream(new File(tarFileName));
        ArchiveOutputStream tarArchive = new TarArchiveOutputStream(tarOutput);
        List<File> files = new ArrayList<File>();
        File[] filesList = dir.listFiles();
        if (filesList != null) {
            for (File file : filesList) {
                files.addAll(recurseDirectory(file));
            }
        }
        for (File file : files) {
            //                tarArchiveEntry = new TarArchiveEntry(file, file.getPath());
            TarArchiveEntry tarArchiveEntry = new TarArchiveEntry(
                    file.toString().substring(dir.getAbsolutePath().length() + 1, file.toString().length()));
            tarArchiveEntry.setSize(file.length());
            tarArchive.putArchiveEntry(tarArchiveEntry);
            FileInputStream fileInputStream = new FileInputStream(file);
            IOUtils.copy(fileInputStream, tarArchive);
            fileInputStream.close();
            tarArchive.closeArchiveEntry();
        }
        tarArchive.finish();
        tarOutput.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}