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

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

Introduction

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

Prototype

public void write(int b) throws IOException 

Source Link

Document

Writes a byte to the current archive entry.

Usage

From source file:cpcc.vvrte.services.VirtualVehicleMigratorTest.java

private static void appendEntryToStream(String entryName, byte[] content, ArchiveOutputStream os)
        throws IOException {
    TarArchiveEntry entry = new TarArchiveEntry(entryName);
    entry.setModTime(new Date());
    entry.setSize(content.length);//from  w  ww  . j  a  v a  2  s .  com
    entry.setIds(0, 0);
    entry.setNames("vvrte", "cpcc");

    os.putArchiveEntry(entry);
    os.write(content);
    os.closeArchiveEntry();
}

From source file:cpcc.vvrte.services.TarArchiveDemo.java

@Test
public void shouldWriteTarFile() throws IOException, ArchiveException {
    byte[] c1 = "content1\n".getBytes("UTF-8");
    byte[] c2 = "content2 text\n".getBytes("UTF-8");

    Date t1 = new Date(1000L * (System.currentTimeMillis() / 1000L));
    Date t2 = new Date(t1.getTime() - 30000);

    FileOutputStream fos = new FileOutputStream("bugger1.tar");

    ArchiveStreamFactory factory = new ArchiveStreamFactory("UTF-8");
    ArchiveOutputStream outStream = factory.createArchiveOutputStream("tar", fos);

    TarArchiveEntry archiveEntry1 = new TarArchiveEntry("entry1");
    archiveEntry1.setModTime(t1);/*from  ww  w  .ja  v  a2 s .  co m*/
    archiveEntry1.setSize(c1.length);
    archiveEntry1.setIds(STORAGE_ID_ONE, CHUNK_ID_ONE);
    archiveEntry1.setNames(USER_NAME_ONE, GROUP_NAME_ONE);

    outStream.putArchiveEntry(archiveEntry1);
    outStream.write(c1);
    outStream.closeArchiveEntry();

    TarArchiveEntry archiveEntry2 = new TarArchiveEntry("data/entry2");
    archiveEntry2.setModTime(t2);
    archiveEntry2.setSize(c2.length);
    archiveEntry2.setIds(STORAGE_ID_TWO, CHUNK_ID_TWO);
    archiveEntry2.setNames(USER_NAME_TWO, GROUP_NAME_TWO);

    outStream.putArchiveEntry(archiveEntry2);
    outStream.write(c2);
    outStream.closeArchiveEntry();

    outStream.close();

    FileInputStream fis = new FileInputStream("bugger1.tar");
    ArchiveInputStream inStream = factory.createArchiveInputStream("tar", fis);

    TarArchiveEntry entry1 = (TarArchiveEntry) inStream.getNextEntry();
    assertThat(entry1.getModTime()).isEqualTo(t1);
    assertThat(entry1.getSize()).isEqualTo(c1.length);
    assertThat(entry1.getLongUserId()).isEqualTo(STORAGE_ID_ONE);
    assertThat(entry1.getLongGroupId()).isEqualTo(CHUNK_ID_ONE);
    assertThat(entry1.getUserName()).isEqualTo(USER_NAME_ONE);
    assertThat(entry1.getGroupName()).isEqualTo(GROUP_NAME_ONE);
    ByteArrayOutputStream b1 = new ByteArrayOutputStream();
    IOUtils.copy(inStream, b1);
    b1.close();
    assertThat(b1.toByteArray().length).isEqualTo(c1.length);
    assertThat(b1.toByteArray()).isEqualTo(c1);

    TarArchiveEntry entry2 = (TarArchiveEntry) inStream.getNextEntry();
    assertThat(entry2.getModTime()).isEqualTo(t2);
    assertThat(entry2.getSize()).isEqualTo(c2.length);
    assertThat(entry2.getLongUserId()).isEqualTo(STORAGE_ID_TWO);
    assertThat(entry2.getLongGroupId()).isEqualTo(CHUNK_ID_TWO);
    assertThat(entry2.getUserName()).isEqualTo(USER_NAME_TWO);
    assertThat(entry2.getGroupName()).isEqualTo(GROUP_NAME_TWO);
    ByteArrayOutputStream b2 = new ByteArrayOutputStream();
    IOUtils.copy(inStream, b2);
    b2.close();
    assertThat(b2.toByteArray().length).isEqualTo(c2.length);
    assertThat(b2.toByteArray()).isEqualTo(c2);

    TarArchiveEntry entry3 = (TarArchiveEntry) inStream.getNextEntry();
    assertThat(entry3).isNull();

    inStream.close();
}

From source file:cpcc.vvrte.services.VirtualVehicleMigratorImpl.java

/**
 * @param virtualVehicle the virtual vehicle.
 * @param os the output stream to write to.
 * @param chunkNumber the chunk number./*from ww w . ja  v  a 2  s . c  o m*/
 * @throws IOException thrown in case of errors.
 */
private void writeVirtualVehicleContinuation(VirtualVehicle virtualVehicle, ArchiveOutputStream os,
        int chunkNumber) throws IOException {
    byte[] continuation = virtualVehicle.getContinuation();

    if (continuation == null) {
        return;
    }

    TarArchiveEntry entry = new TarArchiveEntry(DATA_VV_CONTINUATION_JS);
    entry.setModTime(new Date());
    entry.setSize(continuation.length);
    entry.setIds(0, chunkNumber);
    entry.setNames("vvrte", "cpcc");

    os.putArchiveEntry(entry);
    os.write(continuation);
    os.closeArchiveEntry();
}

From source file:cpcc.vvrte.services.VirtualVehicleMigratorImpl.java

/**
 * @param virtualVehicle the virtual vehicle.
 * @param os the output stream to write to.
 * @param chunkNumber the chunk number.//from w  ww.  java2  s.  c  o m
 * @throws IOException thrown in case of errors.
 */
private void writeVirtualVehicleSourceCode(VirtualVehicle virtualVehicle, ArchiveOutputStream os,
        int chunkNumber) throws IOException {
    if (virtualVehicle.getCode() == null) {
        return;
    }

    byte[] source = virtualVehicle.getCode().getBytes("UTF-8");

    TarArchiveEntry entry = new TarArchiveEntry(DATA_VV_SOURCE_JS);
    entry.setModTime(new Date());
    entry.setSize(source.length);
    entry.setIds(0, chunkNumber);
    entry.setNames("vvrte", "cpcc");

    os.putArchiveEntry(entry);
    os.write(source);
    os.closeArchiveEntry();
}

From source file:cpcc.vvrte.services.VirtualVehicleMigratorImpl.java

/**
 * @param os the output stream to write to.
 * @throws IOException thrown in case of errors.
 *///from  ww w  . j a va2  s  .  com
private void writeVirtualVehicleStorageChunk(VirtualVehicle virtualVehicle, ArchiveOutputStream os,
        int chunkNumber, List<VirtualVehicleStorage> storageChunk) throws IOException {
    for (VirtualVehicleStorage se : storageChunk) {
        logger.debug("Writing storage entry '" + se.getName() + "'");

        byte[] content = se.getContentAsByteArray();
        TarArchiveEntry entry = new TarArchiveEntry("storage/" + se.getName());
        entry.setModTime(se.getModificationTime());
        entry.setSize(content.length);
        entry.setIds(se.getId(), chunkNumber);
        entry.setNames("vvrte", "cpcc");

        os.putArchiveEntry(entry);
        os.write(content);
        os.closeArchiveEntry();
    }
}

From source file:cpcc.vvrte.services.VirtualVehicleMigratorImpl.java

/**
 * @param virtualVehicle the virtual vehicle.
 * @param os the output stream to write to.
 * @param chunkNumber the chunk number./*from   ww  w . ja  v a 2  s  . c  om*/
 * @throws IOException thrown in case of errors.
 */
private void writeVirtualVehicleProperties(VirtualVehicle virtualVehicle, ArchiveOutputStream os,
        int chunkNumber, boolean lastChunk) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Properties virtualVehicleProps = fillVirtualVehicleProps(virtualVehicle, lastChunk);
    virtualVehicleProps.store(baos, "Virtual Vehicle Properties");
    baos.close();

    byte[] propBytes = baos.toByteArray();

    TarArchiveEntry entry = new TarArchiveEntry(DATA_VV_PROPERTIES);
    entry.setModTime(new Date());
    entry.setSize(propBytes.length);
    entry.setIds(0, chunkNumber);
    entry.setNames("vvrte", "cpcc");

    os.putArchiveEntry(entry);
    os.write(propBytes);
    os.closeArchiveEntry();
}

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

/**
 * Writes the configured mapping namespaceprefix -> namespace to the archive
 * //w  w  w.j  ava 2 s  .c o m
 * This is kind of a quick hack. TODO: during the import, the prefixes should be extracted using
 * JAXB and stored in the NamespacesResource
 * 
 * @throws IOException
 */
private void addNamespacePrefixes(ArchiveOutputStream zos) throws IOException {
    Configuration configuration = Repository.INSTANCE.getConfiguration(new NamespacesId());
    if (configuration instanceof PropertiesConfiguration) {
        // Quick hack: direct serialization only works for PropertiesConfiguration
        PropertiesConfiguration pconf = (PropertiesConfiguration) configuration;
        ArchiveEntry archiveEntry = new ZipArchiveEntry(CSARExporter.PATH_TO_NAMESPACES_PROPERTIES);
        zos.putArchiveEntry(archiveEntry);
        try {
            pconf.save(zos);
        } catch (ConfigurationException e) {
            CSARExporter.logger.debug(e.getMessage(), e);
            zos.write("#Could not export properties".getBytes());
            zos.write(("#" + e.getMessage()).getBytes());
        }
        zos.closeArchiveEntry();
    }
}

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

/**
 * Writes the configured mapping namespaceprefix -> namespace to the archive
 * //  ww w.  ja va  2  s.c o  m
 * This is kind of a quick hack. TODO: during the import, the prefixes should be extracted using
 * JAXB and stored in the NamespacesResource
 * 
 * @throws IOException
 */
private void addNamespacePrefixes(ArchiveOutputStream zos) throws IOException {
    Configuration configuration = Repository.INSTANCE.getConfiguration(new NamespacesId());
    if (configuration instanceof PropertiesConfiguration) {
        // Quick hack: direct serialization only works for PropertiesConfiguration
        PropertiesConfiguration pconf = (PropertiesConfiguration) configuration;
        ArchiveEntry archiveEntry = new ZipArchiveEntry(ZipExporter.PATH_TO_NAMESPACES_PROPERTIES);
        zos.putArchiveEntry(archiveEntry);
        try {
            pconf.save(zos);
        } catch (ConfigurationException e) {
            ZipExporter.logger.debug(e.getMessage(), e);
            zos.write("#Could not export properties".getBytes());
            zos.write(("#" + e.getMessage()).getBytes());
        }
        zos.closeArchiveEntry();
    }
}

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

/**
 * Compress a byte array using zip compression
 *
 * @param aBA// ww  w.  j a va 2s  .  co  m
 * @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);//w w w . jav a2s.c  om
    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;
}