Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrap arbitary InputStream as tar InputStream #23

Open
plamentotev opened this issue Mar 20, 2017 · 0 comments
Open

Wrap arbitary InputStream as tar InputStream #23

plamentotev opened this issue Mar 20, 2017 · 0 comments

Comments

@plamentotev
Copy link

Hi,

I work on an application that as a part of it's operation uploads a file to a Docker container. The Docker API accepts only tar files. That's why the client API expects InputStream containing tar file to be passed. Of course I could create temporary tar file but the file I want to upload could be of arbitrary size so I would rather avoid that. The tar file format does not compress the content of the file and essentially is headers plus the content of the file plus padding. So what I've done is to wrap the original InputStream and create a new one that will return tar file. Here is my code:

public static InputStream wrapInputStream(InputStream inputStream, String fileName,
                                          long size, long modificationTime, int fileMode)
{
    TarHeader header = TarHeader.createHeader(fileName, size, modificationTime, false, fileMode);
    TarEntry entry = new TarEntry(header);
    byte[] headerBytes = new byte[TarConstants.HEADER_BLOCK];
    entry.writeEntryHeader(headerBytes);
    InputStream headerInputStream = new ByteArrayInputStream(headerBytes);

    byte[] eofBytes = getPaddingAndEOF(size);
    InputStream eofInputStream = new ByteArrayInputStream(eofBytes);

    return new SequenceInputStream(Collections.enumeration(
                Arrays.asList(headerInputStream, inputStream, eofInputStream)
    ));
}

private static byte[] getPaddingAndEOF(long entrySize) {
    int paddingLen = TarConstants.DATA_BLOCK - ((int)(entrySize % TarConstants.DATA_BLOCK));

    return new byte[paddingLen + TarConstants.EOF_BLOCK];
}

Do you think such feature could be a valuable addition to the library? If you think so I could make the code more generic and open a pull request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant