Example usage for org.apache.commons.compress.archivers.tar TarArchiveEntry getName

List of usage examples for org.apache.commons.compress.archivers.tar TarArchiveEntry getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Get this entry's name.

Usage

From source file:org.moe.cli.utils.ArchiveUtils.java

public static void untarArchive(ArchiveInputStream archStrim, File destination) throws IOException {
    TarArchiveEntry entry;

    while ((entry = (TarArchiveEntry) archStrim.getNextEntry()) != null) {
        if (entry.isDirectory()) {
            String dest = entry.getName();
            File destFolder = new File(destination, dest);
            if (!destFolder.exists()) {
                destFolder.mkdirs();/*from  w w  w  .j av a2 s. co  m*/
            }
        } else {
            int count;
            byte[] data = new byte[2048];
            File d = new File(destination, entry.getName());

            if (!d.getParentFile().exists()) {
                d.getParentFile().mkdirs();
            }

            if (entry.isSymbolicLink()) {
                String link = entry.getLinkName();

                String entryName = entry.getName();
                int parentIdx = entryName.lastIndexOf("/");

                String newLink = entryName.substring(0, parentIdx) + "/" + link;
                File destFile = new File(destination, newLink);
                File linkFile = new File(destination, entryName);

                Files.createSymbolicLink(Paths.get(linkFile.getPath()), Paths.get(destFile.getPath()));

            } else {
                FileOutputStream fos = new FileOutputStream(d);
                BufferedOutputStream dest = new BufferedOutputStream(fos, 2048);
                while ((count = archStrim.read(data, 0, 2048)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.close();
            }
        }
    }
}

From source file:org.mskcc.cbio.importer.io.internal.FileUtilsImpl.java

private InputStream readContent(ImportDataRecord importDataRecord, InputStream is) throws Exception {

    InputStream toReturn = null;/*from  ww w.j  a  v  a  2s  .  c  o  m*/

    try {
        // decompress .gz file
        if (LOG.isInfoEnabled()) {
            LOG.info("readContent(), decompressing: " + importDataRecord.getCanonicalPathToData());
        }

        InputStream unzippedContent = new GzipCompressorInputStream(is);
        // if tarball, untar
        if (importDataRecord.getCanonicalPathToData().toLowerCase().endsWith("tar.gz")) {
            if (LOG.isInfoEnabled()) {
                LOG.info("readContent(), gzip file is a tarball, untarring");
            }
            TarArchiveInputStream tis = new TarArchiveInputStream(unzippedContent);
            TarArchiveEntry entry = null;
            while ((entry = tis.getNextTarEntry()) != null) {
                String entryName = entry.getName();
                String dataFile = importDataRecord.getDataFilename();
                if (dataFile.contains(DatatypeMetadata.TUMOR_TYPE_TAG)) {
                    dataFile = dataFile.replaceAll(DatatypeMetadata.TUMOR_TYPE_TAG,
                            importDataRecord.getTumorType().toUpperCase());
                }
                if (entryName.contains(dataFile)) {
                    if (LOG.isInfoEnabled()) {
                        LOG.info("Processing tar-archive: " + importDataRecord.getDataFilename());
                    }
                    toReturn = tis;
                    break;
                }
            }
        } else {
            toReturn = unzippedContent;
        }
    } catch (Exception e) {
        throw e;
    }

    // outta here
    return toReturn;
}

From source file:org.mulima.internal.freedb.FreeDbTarDaoImpl.java

/**
 * {@inheritDoc}/*from  w  ww  .j  a  v  a  2  s . c om*/
 */
@Override
public List<Disc> getAllDiscsFromOffset(int startNum, int numToRead) {
    FileInputStream fin = null;
    BufferedInputStream bfin = null;
    TarArchiveInputStream tin = null;
    List<Disc> discs = new ArrayList<Disc>();
    try {
        fin = new FileInputStream(tarArchive);
        bfin = new BufferedInputStream(fin);
        tin = new TarArchiveInputStream(bfin);

        int currentNum = 0;
        TarArchiveEntry entry = tin.getNextTarEntry();
        ProgressBar progress = new SLF4JProgressBar("TAR getDiscs", numToRead);
        while (entry != null && (numToRead < 0 || currentNum < startNum + numToRead)) {
            if (!entry.isDirectory() && currentNum >= startNum) {
                logger.debug("Loading: " + entry.getName());
                int offset = 0;
                byte[] content = new byte[(int) entry.getSize()];
                while (offset < content.length) {
                    offset += tin.read(content, offset, content.length - offset);
                }
                Disc disc = bytesToDisc(content);
                if (disc == null) {
                    logger.warn("Invalid file: " + entry.getName());
                } else {
                    logger.debug(disc.toString());
                    discs.add(disc);
                }
            }

            entry = tin.getNextTarEntry();
            currentNum++;
            progress.next();
        }

        if (entry == null) {
            progress.done();
        }
    } catch (IOException e) {
        logger.error("Problem reading tar archive.", e);
        throw new UncheckedIOException("Problem reading tar archive.", e);
    } finally {
        try {
            if (tin != null) {
                tin.close();
            } else if (bfin != null) {
                bfin.close();
            } else if (fin != null) {
                fin.close();
            }
        } catch (IOException e) {
            logger.error("Problem closing streams.", e);
        }
    }
    return discs;
}

From source file:org.mycore.common.MCRUtils.java

/**
 * Extracts files in a tar archive. Currently works only on uncompressed tar files.
 * //from w  w w .jav  a2s.c o m
 * @param source
 *            the uncompressed tar to extract
 * @param expandToDirectory
 *            the directory to extract the tar file to
 * @throws IOException
 *             if the source file does not exists
 */
public static void untar(Path source, Path expandToDirectory) throws IOException {
    try (TarArchiveInputStream tain = new TarArchiveInputStream(Files.newInputStream(source))) {
        TarArchiveEntry tarEntry;
        FileSystem targetFS = expandToDirectory.getFileSystem();
        HashMap<Path, FileTime> directoryTimes = new HashMap<>();
        while ((tarEntry = tain.getNextTarEntry()) != null) {
            Path target = MCRPathUtils.getPath(targetFS, tarEntry.getName());
            Path absoluteTarget = expandToDirectory.resolve(target).normalize().toAbsolutePath();
            if (tarEntry.isDirectory()) {
                Files.createDirectories(expandToDirectory.resolve(absoluteTarget));
                directoryTimes.put(absoluteTarget,
                        FileTime.fromMillis(tarEntry.getLastModifiedDate().getTime()));
            } else {
                if (Files.notExists(absoluteTarget.getParent())) {
                    Files.createDirectories(absoluteTarget.getParent());
                }
                Files.copy(tain, absoluteTarget, StandardCopyOption.REPLACE_EXISTING);
                Files.setLastModifiedTime(absoluteTarget,
                        FileTime.fromMillis(tarEntry.getLastModifiedDate().getTime()));
            }
        }
        //restore directory dates
        Files.walkFileTree(expandToDirectory, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Path absolutePath = dir.normalize().toAbsolutePath();
                Files.setLastModifiedTime(absolutePath, directoryTimes.get(absolutePath));
                return super.postVisitDirectory(dir, exc);
            }
        });
    }
}

From source file:org.nd4j.util.ArchiveUtils.java

/**
 * Extracts files to the specified destination
 *
 * @param file the file to extract to//w  ww. ja va  2s .  co m
 * @param dest the destination directory
 * @throws IOException
 */
public static void unzipFileTo(String file, String dest) throws IOException {
    File target = new File(file);
    if (!target.exists())
        throw new IllegalArgumentException("Archive doesnt exist");
    FileInputStream fin = new FileInputStream(target);
    int BUFFER = 2048;
    byte data[] = new byte[BUFFER];

    if (file.endsWith(".zip") || file.endsWith(".jar")) {
        try (ZipInputStream zis = new ZipInputStream(fin)) {
            //get the zipped file list entry
            ZipEntry ze = zis.getNextEntry();

            while (ze != null) {
                String fileName = ze.getName();
                File newFile = new File(dest + File.separator + fileName);

                if (ze.isDirectory()) {
                    newFile.mkdirs();
                    zis.closeEntry();
                    ze = zis.getNextEntry();
                    continue;
                }

                FileOutputStream fos = new FileOutputStream(newFile);

                int len;
                while ((len = zis.read(data)) > 0) {
                    fos.write(data, 0, len);
                }

                fos.close();
                ze = zis.getNextEntry();
                log.debug("File extracted: " + newFile.getAbsoluteFile());
            }

            zis.closeEntry();
        }
    } else if (file.endsWith(".tar.gz") || file.endsWith(".tgz")) {

        BufferedInputStream in = new BufferedInputStream(fin);
        GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
        TarArchiveInputStream tarIn = new TarArchiveInputStream(gzIn);

        TarArchiveEntry entry;
        /* Read the tar entries using the getNextEntry method **/
        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {
            log.info("Extracting: " + entry.getName());
            /* If the entry is a directory, create the directory. */

            if (entry.isDirectory()) {
                File f = new File(dest + File.separator + entry.getName());
                f.mkdirs();
            }
            /*
             * If the entry is a file,write the decompressed file to the disk
             * and close destination stream.
             */
            else {
                int count;
                try (FileOutputStream fos = new FileOutputStream(dest + File.separator + entry.getName());
                        BufferedOutputStream destStream = new BufferedOutputStream(fos, BUFFER);) {
                    while ((count = tarIn.read(data, 0, BUFFER)) != -1) {
                        destStream.write(data, 0, count);
                    }

                    destStream.flush();
                    IOUtils.closeQuietly(destStream);
                }
            }
        }

        // Close the input stream
        tarIn.close();
    } else if (file.endsWith(".gz")) {
        File extracted = new File(target.getParent(), target.getName().replace(".gz", ""));
        if (extracted.exists())
            extracted.delete();
        extracted.createNewFile();
        try (GZIPInputStream is2 = new GZIPInputStream(fin);
                OutputStream fos = FileUtils.openOutputStream(extracted)) {
            IOUtils.copyLarge(is2, fos);
            fos.flush();
        }
    } else {
        throw new IllegalStateException(
                "Unable to infer file type (compression format) from source file name: " + file);
    }
    target.delete();
}

From source file:org.ngrinder.common.util.CompressionUtil.java

/**
 * Untar an input file into an output file.
 * /*www.  ja va  2  s . 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 inFile
 *            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 static List<File> untar(final File inFile, final File outputDir) {
    final List<File> untaredFiles = new LinkedList<File>();
    try {
        final InputStream is = new FileInputStream(inFile);
        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()) {
                if (!outputFile.exists()) {
                    if (!outputFile.mkdirs()) {
                        throw new IllegalStateException(
                                String.format("Couldn't create directory %s.", outputFile.getAbsolutePath()));
                    }
                }
            } else {
                File parentFile = outputFile.getParentFile();
                if (!parentFile.exists()) {
                    parentFile.mkdirs();
                }
                final OutputStream outputFileStream = new FileOutputStream(outputFile);

                IOUtils.copy(debInputStream, outputFileStream);
                outputFileStream.close();
                if (FilenameUtils.isExtension(outputFile.getName(), EXECUTABLE_EXTENSION)) {
                    outputFile.setExecutable(true, true);
                }
                outputFile.setReadable(true);
                outputFile.setWritable(true, true);
            }
            untaredFiles.add(outputFile);
        }
        debInputStream.close();
    } catch (Exception e) {
        LOGGER.error("Error while untar {} file by {}", inFile, e.getMessage());
        LOGGER.debug("Trace is : ", e);
        throw new NGrinderRuntimeException("Error while untar file", e);
    }
    return untaredFiles;
}

From source file:org.ngrinder.common.util.CompressionUtils.java

/**
 * Untar an input file into an output file.
 * The output file is created in the output folder, having the same name as
 * the input file, minus the '.tar' extension.
 *
 * @param inFile    the input .tar file//  w  w  w. j a v  a  2s. c  o  m
 * @param outputDir the output directory file.
 * @return The {@link List} of {@link File}s with the untared content.
 */
@SuppressWarnings("resource")
public static List<File> untar(final File inFile, final File outputDir) {
    final List<File> untaredFiles = new LinkedList<File>();
    InputStream is = null;
    TarArchiveInputStream debInputStream = null;
    try {
        is = new FileInputStream(inFile);
        debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", is);
        TarArchiveEntry entry;
        while ((entry = (TarArchiveEntry) debInputStream.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 {
                File parentFile = outputFile.getParentFile();
                if (!parentFile.exists()) {
                    parentFile.mkdirs();
                }
                final OutputStream outputFileStream = new FileOutputStream(outputFile);
                try {
                    IOUtils.copy(debInputStream, outputFileStream);
                } finally {
                    IOUtils.closeQuietly(outputFileStream);
                }

                if (FilenameUtils.isExtension(outputFile.getName(), EXECUTABLE_EXTENSION)) {
                    outputFile.setExecutable(true, true);
                }
                outputFile.setReadable(true);
                outputFile.setWritable(true, true);
            }
            untaredFiles.add(outputFile);
        }
    } catch (Exception e) {
        throw processException("Error while untar file", e);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(debInputStream);
    }
    return untaredFiles;
}

From source file:org.onebusaway.util.FileUtility.java

/**
 * Untar an input file into an output file.
 * //from   w  ww .j  av a 2 s. 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.  ja va  2  s  . co m*/
        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.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;//from  w  w w  .j  a va  2  s  .c  om
    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;
}