Skip to content

Instantly share code, notes, and snippets.

@trevorhreed
Created April 8, 2014 22:13
Show Gist options
  • Save trevorhreed/10201114 to your computer and use it in GitHub Desktop.
Save trevorhreed/10201114 to your computer and use it in GitHub Desktop.
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.zip.ZipInputStream;
public class zipper {
public static void main(String[] args) {
if(args.length > 0){
String document = args[0];
try {
String docName = document.substring(0, document.lastIndexOf("."));
String tmpDirName = "tmp/" + docName;
String outDirName = "out/" + docName;
unzip(document, tmpDirName);
populate(tmpDirName);
zip(tmpDirName, outDirName);
} catch(IOException e) {
h1("Error: " + e.getMessage());
e.printStackTrace();;
}
}else{
System.out.println("You must supply the name of the Word document!");
}
}
private static Map<String, String> getData() throws IOException {
String[] tokens = {"NAME", "CITY"};
Map<String, String> data = new HashMap<String, String>();
for(int i=0; i < tokens.length; i++){
String response = input(tokens[i] + ": ");
data.put(tokens[i], response);
}
return data;
}
private static void unzip(String zipFileName, String tmpDirName) throws IOException {
h1("Unzipping file: " + zipFileName);
byte[] buffer = new byte[1024];
File outDir = new File(tmpDirName);
if(!outDir.exists()){
outDir.mkdir();
}
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName));
ZipEntry ze = zis.getNextEntry();
while(ze != null){
String fileName = ze.getName();
File newFile = new File(tmpDirName + File.separator + fileName);
System.out.println("...extracting file: " + newFile.getAbsoluteFile());
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int length;
while((length = zis.read(buffer)) > 0){
fos.write(buffer, 0, length);
}
fos.close();
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
private static void populate(String tmpDirName) throws IOException {
h1("Populating document...");
String fileName = tmpDirName + "/word/document.xml";
String contents = loadFile(fileName);
Map data = getData();
Iterator iter = data.entrySet().iterator();
while(iter.hasNext()){
Map.Entry<String, String> pair = (Map.Entry<String, String>)iter.next();
String tokenPattern = "\\{\\{(" + pair.getKey() + ")\\}\\}";
Pattern p = Pattern.compile(tokenPattern, Pattern.DOTALL);
Matcher m = p.matcher(contents);
contents = m.replaceAll(pair.getValue());
}
saveFile(fileName, contents);
}
private static void zip(String tmpDirName, String outDirName) throws IOException {
File fileIn = new File(tmpDirName);
File fileOut = new File(outDirName + ".docx");
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fileOut));
addToZip(zos, fileIn, "");
zos.close();
System.out.println("\n");
}
private static void addToZip(ZipOutputStream zos, File srcFolder, String path) throws IOException {
File[] files = srcFolder.listFiles();
for(int i=0; i < files.length; i++){
if(files[i].getName() == ".DS_Store"){
System.out.println("\t\t\t.DS_Store? Really?");
continue;
}
String filename = path + files[i].getName();
if(files[i].isDirectory()){
filename = filename + "/";
System.out.println("\t> " + filename);
ZipEntry ze = new ZipEntry(filename);
zos.putNextEntry(ze);
zos.closeEntry();
addToZip(zos, files[i], filename);
}else{
System.out.println("\t> " + filename);
zos.putNextEntry(new ZipEntry(filename));
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(files[i]);
int length;
while((length = fis.read(buffer)) > 0){
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
}
}
}
private static String loadFile(String fileName) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(fileName));
return StandardCharsets.UTF_8.decode(ByteBuffer.wrap(encoded)).toString();
}
private static void saveFile(String fileName, String contents) throws IOException {
File file = new File(fileName);
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(contents);
writer.close();
}
private static String input(Object m){
System.out.print(m);
Scanner in = new Scanner(System.in);
return in.nextLine();
}
private static void p1(Object m){
System.out.println("\n" + m + "\n");
}
private static void h1(String m){
String hr = "";
for(int i=0; i < m.length(); i++){
hr += "=";
}
System.out.println("\n");
System.out.println(hr);
System.out.println(m);
System.out.println("");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment