Adding attachment to pdf file with a link to it - java

How can i attach a file to existing pdf including a link to the attachment on the main page?
I am using Itext and so far managed to attach on the document level only.

Use the below code to create an attachments,
please go throw the code as I have spent only few minutes, understand
it and remove the unnecessary codes.
There is a RESOURCE variable which points all the
pdf's or files you want to attach.
here in this case, it is public static final String RESOURCE = "chapter16/%s.pdf";
Where the chapter16 folder has the pdf's you want to attached
and %s will be replaced with the name of the file that you provide and
the file format is .pdf(if you are attaching a pdf file)
It works and tested in my system. I refered this code from here
// I create the list which has the list of files names i want to attach
ArrayList<String> strList = new ArrayList<String>();
strList.add("Strings"); // its the same file I'm attaching four times
strList.add("Strings"); // where "Strings" is the name of the file
strList.add("Strings");
strList.add("Strings");
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PRStream;
import com.itextpdf.text.pdf.PdfAnnotation;
import com.itextpdf.text.pdf.PdfArray;
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
/**
* Creates a PDF listing of attachments
* The attachments can be extracted.
*/
public class AttachFiles {
/** Path to the resources. */
public static final String RESOURCE = "chapter16/%s.pdf";
/** The filename of the resulting PDF. */
public static final String FILENAME = "ResultingFile.pdf";
/** The path to the resulting PDFs */
public static final String PATH = "chapter16/%s";
/** The filename of the PDF */
public static final String RESULT = String.format(PATH, FILENAME);
/**
* Creates a PDF listing
* #throws IOException
* #throws DocumentException
* #throws SQLException
*/
public static void main(String[] args) throws IOException, DocumentException, SQLException {
AttachFiles attachFiles = new AttachFiles();
FileOutputStream os = new FileOutputStream(RESULT);
os.write(attachFiles.createPdf());
os.flush();
os.close();
attachFiles.extractAttachments(RESULT);
}
/**
* Extracts attachments from an existing PDF.
* #param src the path to the existing PDF
* #param dest where to put the extracted attachments
* #throws IOException
*/
public void extractAttachments(String src) throws IOException {
PdfReader reader = new PdfReader(src);
PdfArray array;
PdfDictionary annot;
PdfDictionary fs;
PdfDictionary refs;
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
array = reader.getPageN(i).getAsArray(PdfName.ANNOTS);
if (array == null) continue;
for (int j = 0; j < array.size(); j++) {
annot = array.getAsDict(j);
if (PdfName.FILEATTACHMENT.equals(annot.getAsName(PdfName.SUBTYPE))) {
fs = annot.getAsDict(PdfName.FS);
refs = fs.getAsDict(PdfName.EF);
for (PdfName name : refs.getKeys()) {
FileOutputStream fos
= new FileOutputStream(String.format(PATH, fs.getAsString(name).toString()));
fos.write(PdfReader.getStreamBytes((PRStream)refs.getAsStream(name)));
fos.flush();
fos.close();
}
}
}
}
}
/**
* Creates the PDF.
* #return the bytes of a PDF file.
* #throws DocumentExcetpion
* #throws IOException
* #throws SQLException
*/
public byte[] createPdf() throws DocumentException, IOException, SQLException {
// step 1
Document document = new Document();
// step 2
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, baos);
// step 3
document.open();
// step 4
document.add(new Paragraph("This is a list pdf attachments."));
PdfAnnotation annot;
ListItem item;
Chunk chunk;
List list = new List();
// I create the list which has the list of files names i want to attach
ArrayList<String> strList = new ArrayList<String>();
strList.add("Strings"); // its the same file I'm attaching four times
strList.add("Strings");
strList.add("Strings");
strList.add("Strings");
for (String strWord : strList) {
annot = PdfAnnotation.createFileAttachment(
writer, null, "Name", null,
String.format(RESOURCE, strWord), String.format("%s.pdf", strWord));
item = new ListItem("Name");
item.add("\u00a0\u00a0");
chunk = new Chunk("\u00a0\u00a0\u00a0\u00a0");
chunk.setAnnotation(annot);
item.add(chunk);
list.add(item);
}
document.add(list);
// step 5
document.close();
return baos.toByteArray();
}
}

Related

TestNG Unit Testing Tar and 7z

folder structure is here
console output is here
I'd like to write a test class for the 2 methods below
package jfe;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.utils.IOUtils;
public class JThreadFile {
/**
* uncompresses .tar file
* #param in
* #param out
* #throws IOException
*/
public static void decompressTar(String in, File out) throws IOException {
try (TarArchiveInputStream tin = new TarArchiveInputStream(new FileInputStream(in))){
TarArchiveEntry entry;
while ((entry = tin.getNextTarEntry()) != null) {
if (entry.isDirectory()) {
continue;
}
File curfile = new File(out, entry.getName());
File parent = curfile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
IOUtils.copy(tin, new FileOutputStream(curfile));
}
}
}
/**
* uncompresses .7z file
* #param in
* #param destination
* #throws IOException
*/
public static void decompressSevenz(String in, File destination) throws IOException {
//#SuppressWarnings("resource")
SevenZFile sevenZFile = new SevenZFile(new File(in));
SevenZArchiveEntry entry;
while ((entry = sevenZFile.getNextEntry()) != null){
if (entry.isDirectory()){
continue;
}
File curfile = new File(destination, entry.getName());
File parent = curfile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
FileOutputStream out = new FileOutputStream(curfile);
byte[] content = new byte[(int) entry.getSize()];
sevenZFile.read(content, 0, content.length);
out.write(content);
out.close();
}
sevenZFile.close();
}
}
I use testNG and try to read from a folder, filter the folder for certain extensions (.tar and .7z) feed those files to the uncompress methods and compare the result to the actualOutput folder with AssertEquals. I manage to read the file names from the folder (see console output) but can't feed them to decompressTar(String in, File out). Is this because "result" is a String array and I need a String? I have no clue how DataProvider of TestNG handles data. Any help would be appreciated :) Thank you :)
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class JThreadFileTest {
protected static final File ACT_INPUT = new File("c:\\Test\\TestInput\\"); //input directory
protected static final File EXP_OUTPUT = new File("c:\\Test\\ExpectedOutput\\"); //expected output directory
protected static final File TEST_OUTPUT = new File("c:\\Test\\TestOutput\\");
#DataProvider(name = "tarJobs")
public Object[] getTarJobs() {
//1
String[] tarFiles = ACT_INPUT.list(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return name.endsWith(".tar");
}
});
//2
Object[] result = new Object[tarFiles.length];
int i = 0;
for (String filename : tarFiles) {
result[i] = filename;
i++;
}
return result;
}
#Test(dataProvider = "tarJobs")
public void testTar(String result) throws IOException {
System.out.println("Running test" + result);
--> JThreadFile.decompressTar(result, TEST_OUTPUT);
Assert.assertEquals(TEST_OUTPUT, EXP_OUTPUT);
}
}

Reading text of a pdf using PDFBOX occasionally returns \r\n

I’m currently using PDFBox to read the text of a set of pdfs that I’ve inherited.
I’m only interested in reading the text, not making any changes to the file.
The code that works for most of the files is:
File pdfFile = myPath.toFile();
PDDocument document = PDDocument.load(pdfFile );
Writer sw = new StringWriter();
PDFTextStripper stripper = new PDFTextStripper();
stripper.setStartPage( 1 );
stripper.writeText( document, sw );
String documentText = sw.toString()
For most files, I wind up with the text in the documentText field.
But, for 3 of 24 files, the documentText content for the first file is “\r\n”, for the second “\r\n\r\n”, and for the third “\r\n\r\n\r\n:, But the three files are not consecutive. Multiple good files are between each of these files.
The File is derived from a java.nio.Path. The WindowsFileAttribute that is part of the Path has a size of 279K, so the file is not empty on disk.
I can open the file and view the data, and it looks like the other files that my code reads.
I’m using Java 8.0.121, and PDFBox 2.0.4. (this is the latest version, I believe.)
Any suggestions? Is there a better way to read the text? (I’m not interested in the formatting, or fonts used, just the text.)
Thanks.
Reading multiple PDF docs using pdfbox in java
package readwordfile;
import java.io.BufferedReader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
/**
* This is an example on how to extract words from PDF document
*
* #author saravanan
*/
public class GetWordsFromPDF extends PDFTextStripper {
static List<String> words = new ArrayList<String>();
public GetWordsFromPDF() throws IOException {
}
/**
* #param args
* #throws IOException If there is an error parsing the document.
*/
public static void main(String[] args) throws IOException {
String files;
// FileWriter fs = new FileWriter("C:\\Users\\saravanan\\Desktop\\New Text Document (2).txt");
// FileInputStream fstream1 = new FileInputStream("C:\\Users\\saravanan\\Desktop\\New Text Document (2).txt");
// DataInputStream in1 = new DataInputStream(fstream1);
// BufferedReader br1 = new BufferedReader(new InputStreamReader(in1));
String path = "C:\\Users\\saravanan\\Desktop\\New folder\\"; //local folder path name
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
if (files.endsWith(".pdf") || files.endsWith(".PDF")) {
String nfiles = "C:\\Users\\saravanan\\Desktop\\New folder\\";
String fileName1 = nfiles + files;
System.out.print("\n\n" + files+"\n");
PDDocument document = null;
try {
document = PDDocument.load(new File(fileName1));
PDFTextStripper stripper = new GetWordsFromPDF();
stripper.setSortByPosition(true);
stripper.setStartPage(0);
stripper.setEndPage(document.getNumberOfPages());
Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
stripper.writeText(document, dummy);
int x = 0;
System.out.println("");
for (String word : words) {
if (word.startsWith("xxxxxx")) { //here you can give your pdf doc starting word
x = 1;
}
if (x == 1) {
if (!(word.endsWith("YYYYYY"))) { //here you can give your pdf doc ending word
System.out.print(word + " ");
// fs.write(word);
} else {
x = 0;
break;
}
}
}
} finally {
if (document != null) {
document.close();
words.clear();
}
}
}
}
}
}
/**
* Override the default functionality of PDFTextStripper.writeString()
*
* #param str
* #param textPositions
* #throws java.io.IOException
*/
#Override
protected void writeString(String str, List<TextPosition> textPositions) throws IOException {
String[] wordsInStream = str.split(getWordSeparator());
if (wordsInStream != null) {
for (String word : wordsInStream) {
words.add(word); //store the pdf content into the List
}
}
}
}

unzipping files in /data/data/ folder - Android Java Programming

How would I programmatically unzip backed up data directly into a /data/data/com.appname folder from the SD Card?
I am able to directly unzip folders in the /data/data/com.appname folder using ES File Explorer, however I need to automate this via the app I'm developing.
I've tried the following code, Unfortunately I am only able to unzip to the SD Card and data folder of my app.
I'm guessing this is due to some form of app/folder security?
MainActivity.java
package fb.ziptester;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void buttonOnClick(View v) {
TextView zipSource = (TextView)findViewById(R.id.zip_source);
TextView zipDest = (TextView)findViewById(R.id.zip_dest);
String sZipSource = "/storage/sdcard1/ACC/BU.zip";
String sZipDest = "/data/data/com.appname/";
zipSource.setText(sZipSource);
zipDest.setText(sZipDest);
UnzipUtility zipUtil = new UnzipUtility();
try {
zipUtil.unzip(sZipSource, sZipDest);
} catch(Exception ex) {
//TODO
}
}
}
package fb.ziptester;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
UnzipUtility.java
public class UnzipUtility {
/**
* Size of the buffer to read/write data
*/
private static final int BUFFER_SIZE = 4096;
/**
* Extracts a zip file specified by the zipFilePath to a directory specified by
* destDirectory (will be created if does not exists)
* #param zipFilePath
* #param destDirectory
* #throws IOException
*/
public void unzip(String zipFilePath, String destDirectory) throws IOException {
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdir();
}
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry entry = zipIn.getNextEntry();
// iterates over entries in the zip file
while (entry != null) {
String filePath = destDirectory + File.separator + entry.getName();
if (!entry.isDirectory()) {
// if the entry is a file, extracts it
extractFile(zipIn, filePath);
} else {
// if the entry is a directory, make the directory
File dir = new File(filePath);
dir.mkdir();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
}
/**
* Extracts a zip entry (file entry)
* #param zipIn
* #param filePath
* #throws IOException
*/
private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
}
}
Any help would be much appreciated.
Thank you.

Sequence File created gives strange output in hadoop

I want to combine several small bzip2 files into a sequence file .I saw a code to create sequence file and tried it. But it gives strange output as below. Is this because it is unable to read bzip2 files?
SEQorg.apache.hadoop.io.Textorg.apache.hadoop.io.Text
�*org.apache.hadoop.io.compress.DefaultCodec����gWŒ‚ÊO≈îbº¡vœÖ��� ���
.DS_StorexúÌò±
¬0EÔ4.S∫a�6∞¢0P∞=0ì·‡/d)ÄDï˛ì¨w≈ù7÷ùØ›⁄ÖüO;≥X¬`’∂µóÆ Æâ¡=Ñ B±lP6Û˛ÜbÅå˜C¢3}ª‘�Lp¥oä"ùËL?jK�&:⁄”Åét¢3]Î
º∑¿˘¸68§ÄÉùø:µ√™*é-¿fifi>!~¯·0Ùˆú ¶ eõ¯c‡ÍÉa◊':”ÍÑòù;I1•�∂©���00.json.bz2xúL\gWTK∞%
,Y
ä( HJFêúsŒ\PrRrŒ9ÁCŒ9√0ÃZUÏÌÊΩÔ≤Ù‚Ãô”’UªvÌÍÓ3£oˆä2ä<˝”-”ãȧπË/d;u¥Û£üV;ÀÒÛ¯Ú˜ˇ˚…≥2¢5Í0‰˝8M⁄,S¸¢`f•†`O<ëüD£≈tÃ¥ó`•´D˚~aº˝«õ˜v'≠)(F|§fiÆÕ ?y¬àœTÒÊYåb…U%E?⁄§efiWˇÒY#üÛÓÓ‚
⁄è„ÍåÚÊU5‡ æ‚Â?q‘°�À{©?íWyü÷ÈûF<[˘éŒhãd>x_ÅÁ
fiÒ_eâ5-—|-M)˙)¸R·ªCÆßs„F>UŒ©ß{o„uÔ&∫˚˚Ÿ?Ä©ßW,”◊Ê∫â«õxã¸[yûgÈñFmx|‡ªÍ¶”¶‡Óp-∆ú§ı
<JN t «F4™#Àä¥Jœ¥‰√|E„‘œ„&º§#g|ˆá{iõOx
The code is
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.util.GenericOptionsParser;
public class cinput {
/**
* #param args
* #throws IOException
* #throws IllegalAccessException
* #throws InstantiationException
*/
public static void main(String[] args) throws IOException,
InstantiationException, IllegalAccessException {
// TODO Auto-generated method stub
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
String[] otherArgs = new GenericOptionsParser(conf, args)
.getRemainingArgs();
Path inputFile = new Path(otherArgs[0]);
Path outputFile = new Path(otherArgs[1]);
FSDataInputStream inputStream;
Text key = new Text();
Text value = new Text();
SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf,
outputFile, key.getClass(), value.getClass());
FileStatus[] fStatus = fs.listStatus(inputFile);
for (FileStatus fst : fStatus) {
String str = "";
System.out.println("Processing file : " + fst.getPath().getName() + " and the size is : " + fst.getPath().getName().length());
inputStream = fs.open(fst.getPath());
key.set(fst.getPath().getName());
while(inputStream.available()>0) {
str = str+inputStream.readLine();
// System.out.println(str);
}
value.set(str);
writer.append(key, value);
}
fs.close();
IOUtils.closeStream(writer);
System.out.println("SEQUENCE FILE CREATED SUCCESSFULLY........");
}
}
The input I am passing is Json.bzip2 files. Could someone please point out why I am getting strange output.

What is the best way to compare tar archives in junit testing

I am attempting to create jUnit tests for some code that generates tar files. During testing I will be creating a variety of tar files and comparing them to "Gold" tar images of the expected output. I have been struggling to create an assertTarEquals(String file1, String file2) function, and was hoping someone could provide guidance as to the best approach. It's not important to have the tar file entries in the same order, or with the same attributes. I just need to verify that they have all the same files and that those files contain the same content. I have created a assertZipEquals(String file1, String file2) based on the example provided here: http://www.java2s.com/Tutorial/Java/0180__File/Comparetwozipfiles.htm but the ZipFile.getInputSteam(EntryName) does not appear to have a parallel function in the Commons Tar classes, as they have not implemented markers in the TarInputStream.
I would typically agree that unit testing is no place for testing Archives, but the code that is being tested manages the creation of archives, so in my mind it is not only appropriate but necessary. The code below is pretty ugly, and I would never want to use something like this in production code, but for testing I guess it's ok.... here's the code I'm using for assertArchiveEquals, it supports both tar and zip files.... as always all feedback is welcome.
package com.foo.util.merge;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.io.IOUtils;
import static org.junit.Assert.*;
public final class CompareArchives {
public static final void assertArchiveEquals(String type, String archive1, String archive2) throws NoSuchAlgorithmException, IOException {
if (type.endsWith("zip")) {
assertZipEquals(archive1, archive2);
} else {
assertTarEquals(archive1, archive2);
}
}
/**
* #param archive1
* #param archive2
* #throws ZipException
* #throws IOException
*/
public static final void assertZipEquals(String archive1, String archive2) throws ZipException, IOException {
// Get Archives
ZipFile zipFile1 = new ZipFile(new File(archive1));
ZipFile zipFile2 = new ZipFile(new File(archive2));
// Get Member Hash
HashMap<String, ZipEntry> files1 = getMembers(zipFile1);
HashMap<String, ZipEntry> files2 = getMembers(zipFile2);
// Compare Files
assertMembersEqual(zipFile1, files1, zipFile2, files2);
}
/**
* #param archive
* #return
* #throws IOException
*/
private static final HashMap<String, ZipEntry> getMembers(ZipFile archive) throws IOException {
HashMap<String, ZipEntry> map = new HashMap<String, ZipEntry>();
#SuppressWarnings("unchecked")
Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) archive.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
map.put(entry.getName(), entry);
}
return map;
}
/**
* #param zip1
* #param files1
* #param zip2
* #param files2
* #throws IOException
*/
private static final void assertMembersEqual(ZipFile zip1, HashMap<String, ZipEntry> files1,
ZipFile zip2, HashMap<String, ZipEntry> files2) throws IOException {
if (files1.size() != files2.size()) {
fail("Different Sizes, expected " + Integer.toString(files1.size()) + " found " + Integer.toString(files2.size()));
}
for (String key : files1.keySet()) {
if (!files2.containsKey(key)) {
fail("Expected file not in target " + key);
}
String file1 = IOUtils.toString(zip1.getInputStream(files1.get(key)));
String file2 = IOUtils.toString(zip2.getInputStream(files2.get(key)));
assertEquals(file1, file2);
}
}
/**
* #param archive1
* #param archive2
* #throws IOException
* #throws NoSuchAlgorithmException
*/
public static final void assertTarEquals(String archive1, String archive2) throws IOException, NoSuchAlgorithmException {
// Get Member Hash
HashMap<String, TarArchiveEntry> files1 = getMembers(archive1);
HashMap<String, TarArchiveEntry> files2 = getMembers(archive2);
// Compare Files
assertMembersEqual(archive1, files1, archive2, files2);
}
/**
* #param archive
* #return
* #throws IOException
*/
private static final HashMap<String,TarArchiveEntry> getMembers(String archive) throws IOException {
TarArchiveInputStream input = new TarArchiveInputStream(
new BufferedInputStream(
new FileInputStream(archive)));
TarArchiveEntry entry;
HashMap<String, TarArchiveEntry> map = new HashMap<String, TarArchiveEntry>();
while ((entry = input.getNextTarEntry()) != null) {
map.put(entry.getName(), entry);
}
input.close();
return map;
}
/**
* #param tar1
* #param files1
* #param tar2
* #param files2
* #throws IOException
*/
private static final void assertMembersEqual(String tar1, HashMap<String, TarArchiveEntry> files1,
String tar2, HashMap<String, TarArchiveEntry> files2) throws IOException {
if (files1.size() != files2.size()) {
fail("Different Sizes, expected " + Integer.toString(files1.size()) + " found " + Integer.toString(files2.size()));
}
for (String key : files1.keySet()) {
if (!files2.containsKey(key)) {
fail("Expected file not in target " + key);
}
}
for (String key : files1.keySet()) {
if (!files2.containsKey(key)) {
fail("Expected file not in target " + key);
}
}
for (String key : files1.keySet()) {
String file1 = getTarFile(tar1, key);
String file2 = getTarFile(tar2, key);
assertEquals(file1, file2);
}
}
/**
* #param archive
* #param name
* #return
* #throws IOException
*/
private static final String getTarFile(String archive, String name) throws IOException {
TarArchiveInputStream input = new TarArchiveInputStream(
new BufferedInputStream(
new FileInputStream(archive)));
TarArchiveEntry entry;
while ((entry = input.getNextTarEntry()) != null) {
if (entry.getName().equals(name)) {
byte[] content = new byte[(int) entry.getSize()];
input.read(content, 0, content.length);
input.close();
return new String(content);
}
}
input.close();
return "";
}
}

Categories

Resources