/*
*
* Copyright 2006 Chimen Chen. All rights reserved.
* Modified by Arthur Khusnutdinov, March, 2011.
*
*/
package com.google.code.ftspc.lector.parsers.CHM;
import com.google.code.ftspc.lector.ini_and_vars.Vars;
import com.google.code.jchmweb.jchmweb2.ChmEnumerator;
import com.google.code.jchmweb.jchmweb2.ChmFile;
import com.google.code.jchmweb.jchmweb2.ChmUnitInfo;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.ByteBuffer;
class ChmExtract {
void main(String pathToCHMFile, String pathToTmpDir) throws IOException {
ChmFile chmFile = null;
long time = System.currentTimeMillis(), time_prev = time;
chmFile = new ChmFile(pathToCHMFile);
chmFile.enumerate(ChmFile.CHM_ENUMERATE_ALL,
new Extractor(chmFile, pathToTmpDir));
time = System.currentTimeMillis();
Vars.logger.info(" finished in " + (time - time_prev) + " ms");
}
}
class Extractor implements ChmEnumerator {
String basePath;
ChmFile chmFile;
public Extractor(ChmFile chmFile, String basePath) {
this.chmFile = chmFile;
if (basePath.endsWith("/")) {
this.basePath = basePath.substring(0,
basePath.length() - 1);
} else {
this.basePath = basePath;
}
}
@Override
public void enumerate(ChmUnitInfo ui) {
PrintStream out = null;
ByteBuffer buffer = null;
byte[] bytes = null;
int gotLen;
String fullPath = basePath;
if (!ui.path.startsWith("/")) {
return;
}
fullPath = fullPath.concat(ui.path);
if (ui.length != 0) {
try {
out = new PrintStream(fullPath);
} catch (IOException e) {
Vars.logger.info(" fail while opening the newly created file "
+ ui.path);
}
if (out == null) {
Vars.logger.info(" fail to open the newly created file "
+ ui.path);
return;
}
buffer = chmFile.retrieveObject(ui, 0, ui.length);
if (buffer == null) {
Vars.logger.info(" extract failed on " + ui.path);
return;
}
gotLen = buffer.limit() - buffer.position();
bytes = new byte[gotLen];
buffer.mark();
while (buffer.hasRemaining()) {
buffer.get(bytes);
out.write(bytes, 0, gotLen);
}
buffer.reset();
out.close();
} else {
if (fullPath.endsWith("/")) {
new File(fullPath).mkdirs();
} else {
new File(fullPath).delete();
}
}
}
}