Example usage for org.apache.commons.compress.archivers ArchiveStreamFactory ArchiveStreamFactory

List of usage examples for org.apache.commons.compress.archivers ArchiveStreamFactory ArchiveStreamFactory

Introduction

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

Prototype

ArchiveStreamFactory

Source Link

Usage

From source file:org.jason.mapmaker.server.util.ZipUtil.java

/**
 * Decompress a zip file from a remote URL.
 *
 * @param url       remote URL to import the file from
 * @return          a List<File> containing File objects for each file that was in the zip archive
 * @throws FileNotFoundException    zip archive file was not found
 * @throws ArchiveException         something went wrong creating
 *                                  the archive input stream
 * @throws IOException/*from   w  w  w  . j a v a  2s  .  c om*/
 */
public static List<File> decompress(URL url) throws FileNotFoundException, ArchiveException, IOException {

    List<File> archiveContents = new ArrayList<File>();
    final InputStream is = new BufferedInputStream(url.openStream(), 1024);
    ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP, is);

    // cycle through the entries in the zip archive and write them to the system temp dir
    ZipArchiveEntry entry = (ZipArchiveEntry) ais.getNextEntry();
    while (entry != null) {
        File outputFile = new File(tmpFile, entry.getName()); // don't do this anonymously, need it for the list
        OutputStream os = new FileOutputStream(outputFile);

        IOUtils.copy(ais, os); // copy from the archiveinputstream to the output stream
        os.close(); // close the output stream

        archiveContents.add(outputFile);

        entry = (ZipArchiveEntry) ais.getNextEntry();
    }

    ais.close();
    is.close();

    return archiveContents;
}

From source file:org.jason.mapmaker.server.util.ZipUtil.java

/**
 * Compress a List of File objects into a single ZIP file. User is responsible for deleting the files which
 * have been compressed//from  w w w.j  a  v  a2s.c om
 *
 * @param filename filename for the generated zip file
 * @param fileList List<File> containing the File objects to add to the archive
 * @return a File object representing the zip archive file
 * @throws FileNotFoundException unable to find the file when creating the OutputStream
 * @throws ArchiveException      something went wrong creating
 *                               the output archive
 * @throws IOException
 */
public static File compress(String filename, List<File> fileList) throws FileNotFoundException,

        ArchiveException,

        IOException {

    // Create the File object that will later be returned
    File zipfile = new File(tmpFile, filename);

    // create the output stream and the archiveoutput stream (as a zip file)
    final OutputStream os = new FileOutputStream(zipfile);
    ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP,
            os);

    // cycle throught the files in the list
    for (File file : fileList) {
        // add an anonymous ZipArchiveEntry to the archiveoutputstream, then copy the streams
        aos.putArchiveEntry(new ZipArchiveEntry(file.getName()));
        IOUtils.copy(new FileInputStream(file), aos);
        aos.closeArchiveEntry();

    }

    // cleanup. Everybody do their part.
    aos.close();
    os.close();

    return zipfile;
}

From source file:org.jboss.as.plugin.common.Files.java

/**
 * Unzips the zip file to the target directory.
 *
 * @param zipFile   the zip file to unzip
 * @param targetDir the directory to extract the zip file to
 *
 * @throws IOException if an I/O error occurs
 *//* w w  w. ja  v  a2 s.  co  m*/
public static void unzip(final File zipFile, final File targetDir) throws IOException {
    final File file;
    if (requiresExtraction(zipFile)) {
        file = extract(zipFile);
    } else {
        file = zipFile;
    }

    ArchiveInputStream in = null;
    try {
        in = new ArchiveStreamFactory()
                .createArchiveInputStream(new BufferedInputStream(new FileInputStream(file)));
        final byte[] buff = new byte[1024];
        ArchiveEntry entry;
        while ((entry = in.getNextEntry()) != null) {
            final File extractTarget = new File(targetDir.getAbsolutePath(), entry.getName());
            if (entry.isDirectory()) {
                extractTarget.mkdirs();
            } else {
                final File parent = new File(extractTarget.getParent());
                parent.mkdirs();
                BufferedOutputStream out = null;
                try {
                    out = new BufferedOutputStream(new FileOutputStream(extractTarget));
                    int read;
                    while ((read = in.read(buff)) != -1) {
                        out.write(buff, 0, read);
                    }
                } finally {
                    IoUtils.safeClose(out);
                }
            }
        }
    } catch (ArchiveException e) {
        throw new IOException(e);
    } finally {
        IoUtils.safeClose(in);
    }
}

From source file:org.jbpm.process.workitem.archive.ArchiveWorkItemHandler.java

public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
    String archive = (String) workItem.getParameter("Archive");
    List<File> files = (List<File>) workItem.getParameter("Files");

    try {// w ww .j a  v a2s. co m
        OutputStream outputStream = new FileOutputStream(new File(archive));
        ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", outputStream);

        if (files != null) {
            for (File file : files) {
                final TarArchiveEntry entry = new TarArchiveEntry("testdata/test1.xml");
                entry.setModTime(0);
                entry.setSize(file.length());
                entry.setUserId(0);
                entry.setGroupId(0);
                entry.setMode(0100000);
                os.putArchiveEntry(entry);
                IOUtils.copy(new FileInputStream(file), os);
            }
        }
        os.closeArchiveEntry();
        os.close();
        manager.completeWorkItem(workItem.getId(), null);
    } catch (Throwable t) {
        t.printStackTrace();
        manager.abortWorkItem(workItem.getId());
    }
}

From source file:org.jclouds.docker.features.internal.ArchivesTest.java

private List<File> unTar(final File inputFile, final File outputDir) throws Exception {
    final List<File> untarredFiles = Lists.newArrayList();
    final InputStream is = new FileInputStream(inputFile);
    final TarArchiveInputStream tarArchiveInputStream = (TarArchiveInputStream) new ArchiveStreamFactory()
            .createArchiveInputStream("tar", is);
    TarArchiveEntry entry;// w  w w. ja v  a 2s  .c o m
    while ((entry = (TarArchiveEntry) tarArchiveInputStream.getNextEntry()) != null) {
        final File outputFile = new File(outputDir, entry.getName());
        if (entry.isDirectory()) {
            if (!outputFile.exists()) {
                if (!outputFile.mkdirs()) {
                    throw new IllegalStateException(
                            String.format("Couldn't create directory %s.", outputFile.getAbsolutePath()));
                }
            }
        } else {
            OutputStream outputFileStream = new FileOutputStream(outputFile);
            ByteStreams.copy(tarArchiveInputStream, outputFileStream);
            outputFileStream.close();
        }
        untarredFiles.add(outputFile);
    }
    tarArchiveInputStream.close();
    return untarredFiles;
}

From source file:org.jwebsocket.util.Tools.java

/**
 * Compress a byte array using zip compression
 *
 * @param aBA/* ww  w . j  a  va 2 s. com*/
 * @param aBase64Encode if TRUE, the result is Base64 encoded
 * @return
 * @throws Exception
 */
public static byte[] zip(byte[] aBA, Boolean aBase64Encode) throws Exception {
    ByteArrayOutputStream lBAOS = new ByteArrayOutputStream();
    ArchiveOutputStream lAOS = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP,
            lBAOS);
    ZipArchiveEntry lZipEntry = new ZipArchiveEntry("temp.zip");
    lZipEntry.setSize(aBA.length);
    lAOS.putArchiveEntry(lZipEntry);
    lAOS.write(aBA);
    lAOS.closeArchiveEntry();
    lAOS.flush();
    lAOS.close();

    if (aBase64Encode) {
        aBA = Base64.encodeBase64(lBAOS.toByteArray());
    } else {
        aBA = lBAOS.toByteArray();
    }

    return aBA;
}

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 .  ja v a  2 s. co m*/
    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));
    }/*from w ww .  j ava  2 s  .  com*/

    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));
    }//  www  . j  a  v  a2s  .c om

    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.killbill.billing.beatrix.integration.osgi.util.SetupBundleWithAssertion.java

private static void unTar(final File inputFile, final File outputDir) throws IOException, ArchiveException {
    InputStream is = null;/*from www . j a  va2 s  .c  om*/
    TarArchiveInputStream archiveInputStream = null;
    TarArchiveEntry entry;

    try {
        is = new FileInputStream(inputFile);
        archiveInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar",
                is);
        while ((entry = (TarArchiveEntry) archiveInputStream.getNextEntry()) != null) {
            final File outputFile = new File(outputDir, entry.getName());
            if (entry.isDirectory()) {
                if (!outputFile.exists()) {
                    if (!outputFile.mkdirs()) {
                        throw new IllegalStateException(
                                String.format("Couldn't create directory %s.", outputFile.getAbsolutePath()));
                    }
                }
            } else {
                final OutputStream outputFileStream = new FileOutputStream(outputFile);
                ByteStreams.copy(archiveInputStream, outputFileStream);
                outputFileStream.close();
            }
        }
    } finally {
        if (archiveInputStream != null) {
            archiveInputStream.close();
        }
        if (is != null) {
            is.close();
        }
    }
}