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.onebusaway.util.FileUtility.java

/**
 * Untar an input file into an output file.
 * /*from ww  w. j a v  a2s. c o  m*/
 * The output file is created in the output folder, having the same name as
 * the input file, minus the '.tar' extension.
 * 
 * @param inputFile the input .tar file
 * @param outputDir the output directory file.
 * @throws IOException
 * @throws FileNotFoundException
 * 
 * @return The {@link List} of {@link File}s with the untared content.
 * @throws ArchiveException
 */
public List<File> unTar(final File inputFile, final File outputDir)
        throws FileNotFoundException, IOException, ArchiveException {

    _log.info(
            String.format("Untaring %s to dir %s.", inputFile.getAbsolutePath(), outputDir.getAbsolutePath()));

    final List<File> untaredFiles = new LinkedList<File>();
    final InputStream is = new FileInputStream(inputFile);
    final TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory()
            .createArchiveInputStream("tar", is);
    TarArchiveEntry entry = null;
    while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) {
        final File outputFile = new File(outputDir, entry.getName());
        if (entry.isDirectory()) {
            _log.info(String.format("Attempting to write output directory %s.", outputFile.getAbsolutePath()));
            if (!outputFile.exists()) {
                _log.info(String.format("Attempting to create output directory %s.",
                        outputFile.getAbsolutePath()));
                if (!outputFile.mkdirs()) {
                    throw new IllegalStateException(
                            String.format("CHUNouldn't create directory %s.", outputFile.getAbsolutePath()));
                }
            }
        } else {
            _log.info(String.format("Creating output file %s.", outputFile.getAbsolutePath()));
            final OutputStream outputFileStream = new FileOutputStream(outputFile);
            IOUtils.copy(debInputStream, outputFileStream);
            outputFileStream.close();
        }
        untaredFiles.add(outputFile);
    }
    debInputStream.close();

    return untaredFiles;
}

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

public VNFPackageMetadata add(String fileName, byte[] pack, boolean imageLink)
        throws IOException, VimException, NotFoundException, SQLException, PluginException,
        AlreadyExistingException, PackageIntegrityException, FailedToUploadException {
    try {//  w  w  w  .  java 2 s.c  om
        updateVims();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SDKException e) {
        e.printStackTrace();
    }

    VNFPackage vnfPackage = new VNFPackage();
    vnfPackage.setScripts(new HashSet<Script>());
    Map<String, Object> metadata = null;
    VirtualNetworkFunctionDescriptor virtualNetworkFunctionDescriptor = null;
    byte[] imageFile = null;
    NFVImage image = new NFVImage();
    ImageMetadata imageMetadata = new ImageMetadata();

    InputStream tarStream;
    ArchiveInputStream myTarFile;
    try {
        tarStream = new ByteArrayInputStream(pack);
        myTarFile = new ArchiveStreamFactory().createArchiveInputStream("tar", tarStream);
    } catch (ArchiveException e) {
        e.printStackTrace();
        throw new IOException();
    }
    TarArchiveEntry entry;
    Map<String, Object> imageDetails = new HashMap<>();
    while ((entry = (TarArchiveEntry) myTarFile.getNextEntry()) != null) {
        /* Get the name of the file */
        if (entry.isFile() && !entry.getName().startsWith("./._")) {
            log.debug("file inside tar: " + entry.getName());
            byte[] content = new byte[(int) entry.getSize()];
            myTarFile.read(content, 0, content.length);
            if (entry.getName().equals("Metadata.yaml")) {
                YamlJsonParser yaml = new YamlJsonParser();
                log.info(new String(content));
                metadata = yaml.parseMap(new String(content));
                //Get configuration for NFVImage
                String[] REQUIRED_PACKAGE_KEYS = new String[] { "name", "description", "provider", "image",
                        "shared" };
                for (String requiredKey : REQUIRED_PACKAGE_KEYS) {
                    if (!metadata.containsKey(requiredKey)) {
                        throw new PackageIntegrityException(
                                "Not found " + requiredKey + " of VNFPackage in Metadata.yaml");
                    }
                    if (metadata.get(requiredKey) == null) {
                        throw new PackageIntegrityException(
                                "Not defined " + requiredKey + " of VNFPackage in Metadata.yaml");
                    }
                }
                vnfPackage.setName((String) metadata.get("name"));

                if (vnfPackageMetadataRepository
                        .findByNameAndUsername(vnfPackage.getName(), userManagement.getCurrentUser())
                        .size() != 0) {
                    throw new AlreadyExistingException("Package with name " + vnfPackage.getName()
                            + " already exists, please " + "change the name");
                }

                if (metadata.containsKey("scripts-link")) {
                    vnfPackage.setScriptsLink((String) metadata.get("scripts-link"));
                }
                if (metadata.containsKey("image")) {
                    imageDetails = (Map<String, Object>) metadata.get("image");
                    String[] REQUIRED_IMAGE_DETAILS = new String[] { "upload" };
                    log.debug("image: " + imageDetails);
                    for (String requiredKey : REQUIRED_IMAGE_DETAILS) {
                        if (!imageDetails.containsKey(requiredKey)) {
                            throw new PackageIntegrityException(
                                    "Not found key: " + requiredKey + " of image in Metadata.yaml");
                        }
                        if (imageDetails.get(requiredKey) == null) {
                            throw new PackageIntegrityException(
                                    "Not defined value of key: " + requiredKey + " of image in Metadata.yaml");
                        }
                    }
                    imageMetadata.setUsername(userManagement.getCurrentUser());
                    imageMetadata.setUpload((String) imageDetails.get("option"));
                    if (imageDetails.containsKey("ids")) {
                        imageMetadata.setIds((List<String>) imageDetails.get("ids"));
                    } else {
                        imageMetadata.setIds(new ArrayList<String>());
                    }
                    if (imageDetails.containsKey("names")) {
                        imageMetadata.setNames((List<String>) imageDetails.get("names"));
                    } else {
                        imageMetadata.setNames(new ArrayList<String>());
                    }
                    if (imageDetails.containsKey("link")) {
                        imageMetadata.setLink((String) imageDetails.get("link"));
                    } else {
                        imageMetadata.setLink(null);
                    }

                    //If upload==true -> create a new Image
                    if (imageDetails.get("upload").equals("true")
                            || imageDetails.get("upload").equals("check")) {
                        vnfPackage.setImageLink((String) imageDetails.get("link"));
                        if (metadata.containsKey("image-config")) {
                            log.debug("image-config: " + metadata.get("image-config"));
                            Map<String, Object> imageConfig = (Map<String, Object>) metadata
                                    .get("image-config");
                            //Check if all required keys are available
                            String[] REQUIRED_IMAGE_CONFIG = new String[] { "name", "diskFormat",
                                    "containerFormat", "minCPU", "minDisk", "minRam", "isPublic" };
                            for (String requiredKey : REQUIRED_IMAGE_CONFIG) {
                                if (!imageConfig.containsKey(requiredKey)) {
                                    throw new PackageIntegrityException("Not found key: " + requiredKey
                                            + " of image-config in Metadata.yaml");
                                }
                                if (imageConfig.get(requiredKey) == null) {
                                    throw new PackageIntegrityException("Not defined value of key: "
                                            + requiredKey + " of image-config in Metadata.yaml");
                                }
                            }
                            image.setName((String) imageConfig.get("name"));
                            image.setDiskFormat(((String) imageConfig.get("diskFormat")).toUpperCase());
                            image.setContainerFormat(
                                    ((String) imageConfig.get("containerFormat")).toUpperCase());
                            image.setMinCPU(Integer.toString((Integer) imageConfig.get("minCPU")));
                            image.setMinDiskSpace((Integer) imageConfig.get("minDisk"));
                            image.setMinRam((Integer) imageConfig.get("minRam"));
                            image.setIsPublic(Boolean
                                    .parseBoolean(Integer.toString((Integer) imageConfig.get("minRam"))));
                        } else {
                            throw new PackageIntegrityException(
                                    "The image-config is not defined. Please define it to upload a new image");
                        }
                    }
                } else {
                    throw new PackageIntegrityException(
                            "The image details are not defined. Please define it to use the right image");
                }
            } else if (!entry.getName().startsWith("scripts/") && entry.getName().endsWith(".json")) {
                //this must be the vnfd
                //and has to be onboarded in the catalogue
                String json = new String(content);
                log.trace("Content of json is: " + json);
                try {
                    virtualNetworkFunctionDescriptor = mapper.fromJson(json,
                            VirtualNetworkFunctionDescriptor.class);
                    //remove the images
                    for (VirtualDeploymentUnit vdu : virtualNetworkFunctionDescriptor.getVdu()) {
                        vdu.setVm_image(new HashSet<String>());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                log.trace("Created VNFD: " + virtualNetworkFunctionDescriptor);
            } else if (entry.getName().endsWith(".img")) {
                //this must be the image
                //and has to be upladed to the RIGHT vim
                imageFile = content;
                log.debug("imageFile is: " + entry.getName());
                throw new VimException(
                        "Uploading an image file from the VNFPackage is not supported at this moment. Please use the image link"
                                + ".");
            } else if (entry.getName().startsWith("scripts/")) {
                Script script = new Script();
                script.setName(entry.getName().substring(8));
                script.setPayload(content);
                vnfPackage.getScripts().add(script);
            }
        }
    }
    if (metadata == null) {
        throw new PackageIntegrityException("Not found Metadata.yaml");
    }
    if (vnfPackage.getScriptsLink() != null) {
        if (vnfPackage.getScripts().size() > 0) {
            log.debug(
                    "VNFPackageManagement: Remove scripts got by scripts/ because the scripts-link is defined");
            vnfPackage.setScripts(new HashSet<Script>());
        }
    }
    List<String> vimInstances = new ArrayList<>();
    if (imageDetails.get("upload").equals("check")) {
        if (!imageLink) {
            if (vnfPackage.getImageLink() == null && imageFile == null) {
                throw new PackageIntegrityException(
                        "VNFPackageManagement: For option upload=check you must define an image. Neither the image link is "
                                + "defined nor the image file is available. Please define at least one if you want to upload a new image");
            }
        }
    }

    if (imageDetails.get("upload").equals("true")) {
        log.debug("VNFPackageManagement: Uploading a new Image");
        if (vnfPackage.getImageLink() == null && imageFile == null) {
            throw new PackageIntegrityException(
                    "VNFPackageManagement: Neither the image link is defined nor the image file is available. Please define "
                            + "at least one if you want to upload a new image");
        }
    } else {
        if (!imageDetails.containsKey("ids") && !imageDetails.containsKey("names")) {
            throw new PackageIntegrityException(
                    "VNFPackageManagement: Upload option 'false' or 'check' requires at least a list of ids or names to find "
                            + "the right image.");
        }
    }
    vnfPackage.setImage(image);
    myTarFile.close();
    vnfPackage = vnfPackageRepository.save(vnfPackage);
    virtualNetworkFunctionDescriptor.setVnfPackageLocation(vnfPackage.getId());

    VNFPackageMetadata vnfPackageMetadata = new VNFPackageMetadata();
    vnfPackageMetadata.setName(vnfPackage.getName());
    vnfPackageMetadata.setUsername(userManagement.getCurrentUser());
    vnfPackageMetadata.setVnfd(virtualNetworkFunctionDescriptor);
    vnfPackageMetadata.setVnfPackage(vnfPackage);
    vnfPackageMetadata.setNfvImage(image);
    vnfPackageMetadata.setImageMetadata(imageMetadata);
    vnfPackageMetadata.setVnfPackageFileName(fileName);
    vnfPackageMetadata.setVnfPackageFile(pack);
    String description = (String) metadata.get("description");
    if (description.length() > 100) {
        description = description.substring(0, 100);
    }
    vnfPackageMetadata.setDescription(description);
    vnfPackageMetadata.setProvider((String) metadata.get("provider"));
    vnfPackageMetadata.setRequirements((Map) metadata.get("requirements"));
    vnfPackageMetadata.setShared((boolean) metadata.get("shared"));
    vnfPackageMetadata.setMd5sum(DigestUtils.md5DigestAsHex(pack));
    try {
        this.dispatch(vnfPackageMetadata);
    } catch (FailedToUploadException e) {
        vnfPackageRepository.delete(vnfPackage.getId());
        throw e;
    }
    vnfPackageMetadataRepository.save(vnfPackageMetadata);

    //        vnfdRepository.save(virtualNetworkFunctionDescriptor);
    log.debug("Persisted " + vnfPackageMetadata);
    //        log.trace("Onboarded VNFPackage (" + virtualNetworkFunctionDescriptor.getVnfPackageLocation() + ")
    // successfully");

    return vnfPackageMetadata;
}

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 {//from  w w  w. j a  v a 2  s.  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.openbaton.nfvo.core.api.VNFPackageManagement.java

@Override
public VirtualNetworkFunctionDescriptor onboard(byte[] pack, String projectId)
        throws IOException, VimException, NotFoundException, PluginException, IncompatibleVNFPackage,
        AlreadyExistingException, NetworkServiceIntegrityException {
    log.info("Onboarding VNF Package...");
    VNFPackage vnfPackage = new VNFPackage();
    vnfPackage.setScripts(new HashSet<Script>());
    Map<String, Object> metadata = null;
    VirtualNetworkFunctionDescriptor virtualNetworkFunctionDescriptor = null;
    byte[] imageFile = null;
    NFVImage image = new NFVImage();

    InputStream tarStream;//  w  ww . j  ava  2 s  .  com
    ArchiveInputStream myTarFile;
    try {
        tarStream = new ByteArrayInputStream(pack);
        myTarFile = new ArchiveStreamFactory().createArchiveInputStream("tar", tarStream);
    } catch (ArchiveException e) {
        e.printStackTrace();
        throw new IOException();
    }
    TarArchiveEntry entry;
    Map<String, Object> imageDetails = new HashMap<>();
    while ((entry = (TarArchiveEntry) myTarFile.getNextEntry()) != null) {
        /* Get the name of the file */
        if (entry.isFile() && !entry.getName().startsWith("./._")) {
            log.debug("file inside tar: " + entry.getName());
            byte[] content = new byte[(int) entry.getSize()];
            myTarFile.read(content, 0, content.length);
            if (entry.getName().equals("Metadata.yaml")) {
                YamlJsonParser yaml = new YamlJsonParser();
                metadata = yaml.parseMap(new String(content));
                imageDetails = handleMetadata(metadata, vnfPackage, imageDetails, image);

            } else if (!entry.getName().startsWith("scripts/") && entry.getName().endsWith(".json")) {
                //this must be the vnfd
                //and has to be onboarded in the catalogue
                String json = new String(content);
                log.trace("Content of json is: " + json);
                try {
                    virtualNetworkFunctionDescriptor = mapper.fromJson(json,
                            VirtualNetworkFunctionDescriptor.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                int i = 1;
                for (VirtualDeploymentUnit vdu : virtualNetworkFunctionDescriptor.getVdu()) {
                    if (vdu.getName() == null) {
                        vdu.setName(virtualNetworkFunctionDescriptor.getName() + "-" + i);
                        i++;
                    }
                }
                for (VirtualDeploymentUnit vdu : virtualNetworkFunctionDescriptor.getVdu()) {
                    log.debug("vdu name: " + vdu.getName());
                }
                log.debug("Created VNFD: " + virtualNetworkFunctionDescriptor.getName());
                log.trace("Created VNFD: " + virtualNetworkFunctionDescriptor);
                nsdUtils.fetchVimInstances(virtualNetworkFunctionDescriptor, projectId);
            } else if (entry.getName().endsWith(".img")) {
                //this must be the image
                //and has to be upladed to the RIGHT vim
                imageFile = content;
                log.debug("imageFile is: " + entry.getName());
                throw new VimException(
                        "Uploading an image file from the VNFPackage is not supported at this moment. Please use the image link"
                                + ".");
            } else if (entry.getName().startsWith("scripts/")) {
                Script script = new Script();
                script.setName(entry.getName().substring(8));
                script.setPayload(content);
                vnfPackage.getScripts().add(script);
            }
        }
    }

    handleImage(vnfPackage, imageFile, virtualNetworkFunctionDescriptor, metadata, image, imageDetails,
            projectId);

    vnfPackage.setImage(image);
    myTarFile.close();
    virtualNetworkFunctionDescriptor.setProjectId(projectId);
    vnfPackage.setProjectId(projectId);
    for (VirtualNetworkFunctionDescriptor vnfd : vnfdRepository.findByProjectId(projectId)) {
        if (vnfd.getVendor().equals(virtualNetworkFunctionDescriptor.getVendor())
                && vnfd.getName().equals(virtualNetworkFunctionDescriptor.getName())
                && vnfd.getVersion().equals(virtualNetworkFunctionDescriptor.getVersion())) {
            throw new AlreadyExistingException("A VNF with this vendor, name and version is already existing");
        }
    }

    nsdUtils.checkIntegrity(virtualNetworkFunctionDescriptor);

    vnfPackageRepository.save(vnfPackage);
    virtualNetworkFunctionDescriptor.setVnfPackageLocation(vnfPackage.getId());
    virtualNetworkFunctionDescriptor = vnfdRepository.save(virtualNetworkFunctionDescriptor);
    log.trace("Persisted " + virtualNetworkFunctionDescriptor);
    log.trace("Onboarded VNFPackage (" + virtualNetworkFunctionDescriptor.getVnfPackageLocation()
            + ") successfully");
    return virtualNetworkFunctionDescriptor;
}

From source file:org.openo.commontosca.catalog.mdserver.csar.export.ZipExporter.java

public void createZip(OutputStream out, CsarMetaEntity csarInfo, String inputDir)
        throws ArchiveException, MdCommonException, IOException {
    zos = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);
    File file = Paths.get(inputDir, Constants.TOSCA_META).toFile();
    if (!file.exists()) {
        logger.info("start add manifest data");
        try {/*from  ww w . j a  va2s  .c  o m*/
            addManifest();
        } catch (IOException e) {
            throwMdCommonException("add manifest faild! errorMsg:" + e.getMessage());
        }
    }
    logger.info("start other files");
    try {
        addDirToZipArchive(inputDir, "");
    } catch (IOException e) {
        throwMdCommonException("add manifest faild! errorMsg:" + e.getMessage());
    }
    file = Paths.get(new File(inputDir).getPath(), Constants.CSAR_META).toFile();
    if (!file.exists()) {
        logger.info("start add csar meta data");
        try {
            addCsarMeta(csarInfo);
        } catch (IOException e) {
            throwMdCommonException("add csar meta faild! errorMsg:" + e.getMessage());
        }
    }
}

From source file:org.openo.nfvo.jujuvnfmadapter.common.UnCompressUtil.java

/**
 * tar.gz/*from w  ww  . java2 s  .  com*/
 * <br/>
 * 
 * @param zipfileName
 * @param outputDirectory
 * @param fileNames
 * @return
 * @since NFVO 0.5
 */
public static boolean unCompressGzip(String zipfileName, String outputDirectory, List<String> fileNames) {
    FileInputStream fis = null;
    ArchiveInputStream in = null;
    BufferedInputStream bis = null;
    try {
        fis = new FileInputStream(zipfileName);
        GZIPInputStream gis = new GZIPInputStream(new BufferedInputStream(fis));
        in = new ArchiveStreamFactory().createArchiveInputStream("tar", gis);
        bis = new BufferedInputStream(in);
        TarArchiveEntry entry = (TarArchiveEntry) in.getNextEntry();
        while (entry != null) {
            String name = entry.getName();
            String[] names = name.split("/");
            String fileName = outputDirectory;
            for (int i = 0; i < names.length; i++) {
                String str = names[i];
                fileName = fileName + File.separator + str;
            }
            if (name.endsWith("/")) {
                FileUtils.mkDirs(fileName);
            } else {
                File file = getRealFileName(outputDirectory, name);
                if (null != fileNames) {
                    fileNames.add(file.getName());
                }
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                int b = -1;
                while ((b = bis.read()) != -1) {
                    bos.write(b);
                }
                log.debug("ungzip to:" + file.getCanonicalPath());
                bos.flush();
                bos.close();
            }
            entry = (TarArchiveEntry) in.getNextEntry();
        }
        return true;
    } catch (Exception e) {
        log.error("UnCompressGZip faield:", e);
        return false;
    } finally {
        try {
            if (null != bis) {
                bis.close();
            }
        } catch (IOException e) {
            log.error("UnCompressGZip faield:", e);
        }
    }
}

From source file:org.openo.nfvo.jujuvnfmadapter.common.UnCompressUtil.java

/**
 * tar.xz//w w w  . j a  va  2 s  . c  o m
 * <br/>
 * 
 * @param zipfileName
 * @param outputDirectory
 * @param fileNames
 * @return
 * @since NFVO 0.5
 */
public static boolean unCompressTarXZ(String zipfileName, String outputDirectory, List<String> fileNames) {
    ArchiveInputStream in = null;
    BufferedInputStream bis = null;
    try {
        XZCompressorInputStream xzis = new XZCompressorInputStream(
                new BufferedInputStream(new FileInputStream(zipfileName)));
        in = new ArchiveStreamFactory().createArchiveInputStream("tar", xzis);
        bis = new BufferedInputStream(in);
        TarArchiveEntry entry = (TarArchiveEntry) in.getNextEntry();
        while (entry != null) {
            String name = entry.getName();
            String[] names = name.split("/");
            String fileName = outputDirectory;
            for (int i = 0; i < names.length; i++) {
                String str = names[i];
                fileName = fileName + File.separator + str;
            }
            if (name.endsWith("/")) {
                FileUtils.mkDirs(fileName);
            } else {
                File file = getRealFileName(outputDirectory, name);
                if (null != fileNames) {
                    fileNames.add(file.getName());
                }
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                int b = -1;
                while ((b = bis.read()) != -1) {
                    bos.write(b);
                }
                log.debug("ungzip to:" + file.getCanonicalPath());
                bos.flush();
                bos.close();
            }
            entry = (TarArchiveEntry) in.getNextEntry();
        }
        return true;
    } catch (Exception e) {
        log.error("unCompressTarXZ faield:", e);
    } finally {
        try {
            if (null != bis) {
                bis.close();
            }
        } catch (IOException e) {
            log.error("unCompressTarXZ faield:", e);
        }
    }
    return false;
}

From source file:org.opensextant.xtext.collectors.ArchiveNavigator.java

public File unzip(File zipFile) throws IOException, ConfigException {

    // String _working = FilenameUtils.concat(getWorkingDir(),
    // FilenameUtils.getBaseName(zipFile.getPath()));
    // if (_working == null){
    // throw new IOException("Invalid archive path for "+zipFile.getPath());
    // }/* w ww .ja v  a 2  s  . c  om*/

    // File workingDir = new File(_working);
    // workingDir.mkdir();
    File workingDir = saveDir;

    InputStream input = new BufferedInputStream(new FileInputStream(zipFile));
    ZipArchiveInputStream in = null;
    try {
        in = (ZipArchiveInputStream) (new ArchiveStreamFactory().createArchiveInputStream("zip", input));

        ZipArchiveEntry zipEntry;
        while ((zipEntry = (ZipArchiveEntry) in.getNextEntry()) != null) {
            if (filterEntry(zipEntry)) {
                continue;
            }

            try {
                File tmpFile = saveArchiveEntry(zipEntry, in, workingDir);
                converter.convert(tmpFile);

            } catch (IOException err) {
                log.error("Unable to save item, FILE=" + zipEntry.getName() + "!" + zipEntry.getName(), err);
            }
        }
        return workingDir;

    } catch (ArchiveException ae) {
        throw new IOException(ae);
    } finally {
        in.close();
    }
}

From source file:org.opensextant.xtext.collectors.ArchiveNavigator.java

public File untar(File tarFile) throws IOException, ConfigException {

    String _working = FilenameUtils.concat(getWorkingDir(), FilenameUtils.getBaseName(tarFile.getPath()));
    if (_working == null) {
        throw new IOException("Invalid archive path for " + tarFile.getPath());
    }/*from   w ww  .  j  av  a  2s  . c om*/
    File workingDir = new File(_working);
    workingDir.mkdir();

    InputStream input = new BufferedInputStream(new FileInputStream(tarFile));
    TarArchiveInputStream in = null;
    try {
        in = (TarArchiveInputStream) (new ArchiveStreamFactory().createArchiveInputStream("tar", input));

        TarArchiveEntry tarEntry;
        while ((tarEntry = (TarArchiveEntry) in.getNextEntry()) != null) {
            if (filterEntry(tarEntry)) {
                continue;
            }

            try {
                File tmpFile = saveArchiveEntry(tarEntry, in, _working);
                converter.convert(tmpFile);
            } catch (IOException err) {
                log.error("Unable to save item, FILE=" + tarFile.getName() + "!" + tarEntry.getName(), err);
            }
        }
    } catch (ArchiveException ae) {
        throw new IOException(ae);
    } finally {
        in.close();
    }
    return workingDir;
}

From source file:org.phoenicis.tools.archive.Tar.java

/**
 * Uncompress a tar//ww  w .  j  a  v a  2  s  .  c o m
 *
 * @param countingInputStream
 *            to count the number of byte extracted
 * @param outputDir
 *            The directory where files should be extracted
 * @return A list of extracted files
 * @throws ArchiveException
 *             if the process fails
 */
private List<File> uncompress(final InputStream inputStream, CountingInputStream countingInputStream,
        final File outputDir, long finalSize, Consumer<ProgressEntity> stateCallback) {
    final List<File> uncompressedFiles = new LinkedList<>();
    try (ArchiveInputStream debInputStream = new ArchiveStreamFactory().createArchiveInputStream("tar",
            inputStream)) {
        TarArchiveEntry entry;
        while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) {
            final File outputFile = new File(outputDir, entry.getName());
            if (entry.isDirectory()) {
                LOGGER.info(String.format("Attempting to write output directory %s.",
                        outputFile.getAbsolutePath()));

                if (!outputFile.exists()) {
                    LOGGER.info(String.format("Attempting to createPrefix output directory %s.",
                            outputFile.getAbsolutePath()));
                    Files.createDirectories(outputFile.toPath());
                }
            } else {
                LOGGER.info(String.format("Creating output file %s (%s).", outputFile.getAbsolutePath(),
                        entry.getMode()));

                if (entry.isSymbolicLink()) {
                    Files.createSymbolicLink(Paths.get(outputFile.getAbsolutePath()),
                            Paths.get(entry.getLinkName()));
                } else {
                    try (final OutputStream outputFileStream = new FileOutputStream(outputFile)) {
                        IOUtils.copy(debInputStream, outputFileStream);

                        Files.setPosixFilePermissions(Paths.get(outputFile.getPath()),
                                fileUtilities.octToPosixFilePermission(entry.getMode()));
                    }
                }

            }
            uncompressedFiles.add(outputFile);

            stateCallback.accept(new ProgressEntity.Builder()
                    .withPercent((double) countingInputStream.getCount() / (double) finalSize * (double) 100)
                    .withProgressText("Extracting " + outputFile.getName()).build());

        }
        return uncompressedFiles;
    } catch (IOException | org.apache.commons.compress.archivers.ArchiveException e) {
        throw new ArchiveException("Unable to extract the file", e);
    }
}