Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Comparing changes

Choose two branches to see what's changed or to start a new pull request. If you need to, you can also compare across forks.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also compare across forks.
  • 6 commits
  • 10 files changed
  • 0 commit comments
  • 1 contributor
View
3  .gitignore
@@ -1,3 +1,4 @@
build/
nbproject/
-tmp/
+tmp/
+.DS_Store
View
4 CHANGELOG
@@ -1,3 +1,7 @@
+January 5, 2012 - v0.4.6
+* Add option for MHTML output file separate from CSS output file. (jbarker)
+* Fixed bug where MHTML content was not rendered by IE6 & IE7.
+
November 22, 2011 - v0.4.5
* Add option to skip some images using /*CSSEmbed:SKIP*/ after the declaration.
View
2  ant.properties
@@ -15,7 +15,7 @@ class.version = 1.5
#CSSEmbed properties
cssembed.name = cssembed
-cssembed.version = 0.4.5
+cssembed.version = 0.4.6
cssembed.jar = ${cssembed.name}-${cssembed.version}.jar
cssembed.main = net.nczonline.web.cssembed.CSSEmbed
View
147 src/net/nczonline/web/cssembed/CSSEmbed.java
@@ -1,17 +1,17 @@
/*
* Copyright (c) 2009 Nicholas C. Zakas. All rights reserved.
* http://www.nczonline.net/
- *
+ *
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
- *
+ *
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
- *
+ *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -35,39 +35,43 @@
import java.nio.charset.Charset;
-public class CSSEmbed {
+public class CSSEmbed {
+
-
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
-
+
//default settings
boolean verbose = false;
String charset = null;
- String outputFilename = null;
- ByteArrayOutputStream bytes = new ByteArrayOutputStream();
- Writer out = null;
+ String cssOutputFilename = null;
+ ByteArrayOutputStream cssBytes = new ByteArrayOutputStream();
+ Writer cssOut = null;
+ String mhtmlFilename = null;
+ ByteArrayOutputStream mhtmlBytes = new ByteArrayOutputStream();
+ Writer mhtmlOut = null;
Reader in = null;
String root;
int options = CSSURLEmbedder.DATAURI_OPTION;
-
+
//initialize command line parser
CmdLineParser parser = new CmdLineParser();
CmdLineParser.Option verboseOpt = parser.addBooleanOption('v', "verbose");
CmdLineParser.Option helpOpt = parser.addBooleanOption('h', "help");
CmdLineParser.Option charsetOpt = parser.addStringOption("charset");
CmdLineParser.Option rootOpt = parser.addStringOption("root");
- CmdLineParser.Option outputFilenameOpt = parser.addStringOption('o', "output");
+ CmdLineParser.Option cssOutputFilenameOpt = parser.addStringOption('o', "output");
CmdLineParser.Option mhtmlOpt = parser.addBooleanOption("mhtml");
CmdLineParser.Option mhtmlRootOpt = parser.addStringOption("mhtmlroot");
+ CmdLineParser.Option mhtmlFilenameOpt = parser.addStringOption("mhtmlfile");
CmdLineParser.Option skipMissingOpt = parser.addBooleanOption("skip-missing");
CmdLineParser.Option uriLengthOpt = parser.addIntegerOption("max-uri-length");
CmdLineParser.Option imageSizeOpt = parser.addIntegerOption("max-image-size");
-
+
try {
-
+
//parse the arguments
parser.parse(args);
@@ -76,11 +80,11 @@ public static void main(String[] args) {
if (help != null && help.booleanValue()) {
usage();
System.exit(0);
- }
-
+ }
+
//determine boolean options
verbose = parser.getOptionValue(verboseOpt) != null;
-
+
//check for charset
charset = (String) parser.getOptionValue(charsetOpt);
if (charset == null || !Charset.isSupported(charset)) {
@@ -92,18 +96,18 @@ public static void main(String[] args) {
System.err.println("\n[INFO] Using charset " + charset);
}
}
-
+
//get the file arguments
String[] fileArgs = parser.getRemainingArgs();
String inputFilename = null;
-
+
//if no file is given, use stdin
if (fileArgs.length == 0){
in = new InputStreamReader(System.in, charset);
} else {
//only the first filename is used
- inputFilename = fileArgs[0];
- in = new InputStreamReader(new FileInputStream(inputFilename), charset);
+ inputFilename = fileArgs[0];
+ in = new InputStreamReader(new FileInputStream(inputFilename), charset);
}
//determine if there's a maximum URI length
@@ -115,7 +119,7 @@ public static void main(String[] args) {
uriLength = 0;
}
}
-
+
//maximum size allowed for image files
int imageSize = 0;
Integer imageSizeOption = (Integer) parser.getOptionValue(imageSizeOpt);
@@ -135,76 +139,102 @@ public static void main(String[] args) {
if (mhtml && mhtmlRoot == null){
throw new Exception("Must use --mhtmlroot when using --mhtml.");
}
-
+ mhtmlFilename = (String) parser.getOptionValue(mhtmlFilenameOpt);
+ if (null != mhtmlFilename){
+ options = options | CSSURLEmbedder.MHTML_FILE_OPTION;
+ }
+
//are missing files ok?
boolean skipMissingFiles = parser.getOptionValue(skipMissingOpt) != null;
if(skipMissingFiles) {
options = options | CSSURLEmbedder.SKIP_MISSING_OPTION;
}
-
- CSSURLEmbedder embedder = new CSSURLEmbedder(in, options, verbose, uriLength, imageSize);
+
+ CSSURLEmbedder embedder = new CSSURLEmbedder(in, options, verbose, uriLength, imageSize);
embedder.setMHTMLRoot(mhtmlRoot);
-
+
//close in case writing to the same file
in.close(); in = null;
-
+
//get root for relative URLs
root = (String) parser.getOptionValue(rootOpt);
if(root == null){
-
+
if (inputFilename != null) {
//no root specified, so get from input file
root = (new File(inputFilename)).getCanonicalPath();
- root = root.substring(0, root.lastIndexOf(File.separator));
+ root = root.substring(0, root.lastIndexOf(File.separator));
} else {
throw new Exception("Must use --root when not specifying a filename.");
}
}
-
+
if (!root.endsWith(File.separator)){
root += File.separator;
}
-
+
if (verbose){
System.err.println("[INFO] Using '" + root + "' as root for relative file paths.");
}
-
- //get output filename
- outputFilename = (String) parser.getOptionValue(outputFilenameOpt);
- if (outputFilename == null) {
+
+ //set CSS output
+ cssOutputFilename = (String) parser.getOptionValue(cssOutputFilenameOpt);
+ if (cssOutputFilename == null) {
if (verbose){
- System.err.println("[INFO] No output file specified, defaulting to stdout.");
- }
-
- out = new OutputStreamWriter(System.out);
+ System.err.println("[INFO] No CSS output file specified, defaulting to stdout.");
+ }
+ cssOut = new OutputStreamWriter(System.out);
} else {
- File outputFile = new File(outputFilename);
+ File cssOutputFile = new File(cssOutputFilename);
if (verbose){
- System.err.println("[INFO] Output file is '" + outputFile.getAbsolutePath() + "'");
+ System.err.println("[INFO] CSS output file is '" + cssOutputFile.getAbsolutePath() + "'");
}
- embedder.setFilename(outputFile.getName());
- out = new OutputStreamWriter(bytes, charset);
- }
-
+ embedder.setFilename(cssOutputFile.getName());
+ cssOut = new OutputStreamWriter(cssBytes, charset);
+ }
+
+ //set MHTML output
+ if (null != mhtmlFilename) {
+ File mhtmlOutputFile = new File(mhtmlFilename);
+ if (verbose){
+ System.err.println("[INFO] MHTML output file is '" + mhtmlOutputFile.getAbsolutePath() + "'");
+ }
+ mhtmlOut = new OutputStreamWriter(mhtmlBytes, charset);
+ // overwrite previous filename, if any
+ embedder.setFilename(mhtmlOutputFile.getName());
+ }
+
//set verbose option
- embedder.embedImages(out, root);
-
+ embedder.embedImages(cssOut, mhtmlOut, root);
+
} catch (CmdLineParser.OptionException e) {
usage();
- System.exit(1);
- } catch (Exception e) {
+ System.exit(1);
+ } catch (Exception e) {
System.err.println("[ERROR] " + e.getMessage());
if (verbose){
e.printStackTrace();
}
System.exit(1);
} finally {
- if (out != null) {
+ if (cssOut != null) {
+ try {
+ cssOut.close();
+ if(cssBytes.size() > 0) {
+ cssBytes.writeTo(new FileOutputStream(cssOutputFilename));
+ }
+ } catch (IOException e) {
+ System.err.println("[ERROR] " + e.getMessage());
+ if (verbose){
+ e.printStackTrace();
+ }
+ }
+ }
+ if (mhtmlOut != null) {
try {
- out.close();
-
- if(bytes.size() > 0) {
- bytes.writeTo(new FileOutputStream(outputFilename));
+ mhtmlOut.close();
+ if(mhtmlBytes.size() > 0) {
+ mhtmlBytes.writeTo(new FileOutputStream(mhtmlFilename));
}
} catch (IOException e) {
System.err.println("[ERROR] " + e.getMessage());
@@ -212,11 +242,11 @@ public static void main(String[] args) {
e.printStackTrace();
}
}
- }
+ }
}
-
+
}
-
+
/**
* Outputs help information to the console.
*/
@@ -228,12 +258,13 @@ private static void usage() {
+ " -h, --help Displays this information.\n"
+ " --charset <charset> Character set of the input file.\n"
+ " --mhtml Enable MHTML mode.\n"
- + " --mhtmlroot <root> Use <root> as the MHTML root for the file.\n"
+ + " --mhtmlroot <root> Use <root> as the MHTML root for the file.\n"
+ + " --mhtmlfile <file> Place the MHTML output into <file>.\n"
+ " -v, --verbose Display informational messages and warnings.\n"
+ " --root <root> Prepends <root> to all relative URLs.\n"
+ " --skip-missing Don't throw an error for missing image files.\n"
+ " --max-uri-length len Maximum length for a data URI. Defaults to 32768.\n"
+ " --max-image-size size Maximum image size (in bytes) to convert.\n"
- + " -o <file> Place the output into <file>. Defaults to stdout.");
+ + " -o <file> Place the CSS output into <file>. Defaults to stdout.");
}
}
View
88 src/net/nczonline/web/cssembed/CSSEmbedTask.java
@@ -1,17 +1,17 @@
/*
* Copyright (c) 2009 Nicholas C. Zakas. All rights reserved.
* http://www.nczonline.net/
- *
+ *
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
- *
+ *
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
- *
+ *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -41,7 +41,7 @@
//Define a custom Ant Task that calls into the CSS Embedder
public class CSSEmbedTask extends Task {
-
+
//attribute options
private String charset = "UTF-8";
private String root;
@@ -53,59 +53,59 @@
private int maxImageSize = 0;
private File srcFile;
private File destFile;
-
+
//support nested resource collections & mappers
private Mapper mapperElement = null;
private Vector rcs = new Vector();
-
+
//Simple Setters
public void setCharset(String charset) {
this.charset = charset;
}
-
+
public void setRoot(String root) {
this.root = root;
}
-
+
public void setMhtml(boolean mhtml) {
this.mhtml = mhtml;
}
-
+
public void setMhtmlRoot(String mhtmlRoot) {
this.mhtmlRoot = mhtmlRoot;
}
-
+
public void setSkipMissing(boolean skipMissing) {
this.skipMissing = skipMissing;
}
-
+
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
-
+
public void setMaxUriLength(int maxUriLength) {
this.maxUriLength = maxUriLength;
}
-
+
public void setMaxImageSize(int maxImageSize) {
this.maxImageSize = maxImageSize;
}
-
+
public void setSrcFile(File srcFile) {
this.srcFile = srcFile;
}
-
+
public void setDestFile(File destFile) {
this.destFile = destFile;
}
-
+
//More complicated setters for nested elements...
-
+
//add a collection of resources to copy
public void add(ResourceCollection res) {
rcs.add(res);
}
-
+
//mapper takes source files & converts them to dest files
public Mapper createMapper() throws BuildException {
if (mapperElement != null) {
@@ -114,12 +114,12 @@ public Mapper createMapper() throws BuildException {
mapperElement = new Mapper(getProject());
return mapperElement;
}
-
+
//support multiple types of filename mappers being added
public void add(FileNameMapper fileNameMapper) {
createMapper().add(fileNameMapper);
}
-
+
//returns the mapper to use based on nested elements, defaults to IdentityMapper
private FileNameMapper getMapper() {
FileNameMapper mapper = null;
@@ -130,7 +130,7 @@ private FileNameMapper getMapper() {
}
return mapper;
}
-
+
//ensure that attributes are legit
protected void validateAttributes() throws BuildException {
//if there's no nested resource containers make sure that a srcFile/destFile are set
@@ -138,31 +138,31 @@ protected void validateAttributes() throws BuildException {
if (this.srcFile == null || !this.srcFile.exists()) {
throw new BuildException("Must specify an input file or at least one nested resource", getLocation());
}
-
+
if(this.destFile == null) {
throw new BuildException("Must specify an output file or at least one nested resource", getLocation());
}
}
-
+
if(this.mhtml && this.mhtmlRoot == null) {
throw new BuildException("Must specify mhtmlRoot in mhtml mode", getLocation());
}
-
+
if(this.mhtmlRoot != null && !this.mhtml) {
log("mhtmlRoot has no effect if mhtml mode is not activated", Project.MSG_WARN);
}
}
-
+
//run the task
public void execute () throws BuildException {
validateAttributes();
-
+
//set options flags
int options = (this.mhtml) ? CSSURLEmbedder.MHTML_OPTION : CSSURLEmbedder.DATAURI_OPTION;
if(skipMissing) {
options = options | CSSURLEmbedder.SKIP_MISSING_OPTION;
}
-
+
if(srcFile != null && srcFile.exists()) {
try {
embed(srcFile, destFile, options);
@@ -170,21 +170,21 @@ public void execute () throws BuildException {
throw new BuildException(ex.getMessage(), ex);
}
}
-
+
FileNameMapper mapper = getMapper();
-
+
for(Iterator it = this.rcs.iterator(); it.hasNext();) {
ResourceCollection rc = (ResourceCollection) it.next();
-
+
for(Iterator rcit = rc.iterator(); rcit.hasNext();) {
FileResource fr = (FileResource) rcit.next();
File in = fr.getFile();
-
+
String[] mapped = mapper.mapFileName(in.getName());
if (mapped != null && mapped.length > 0) {
for(int k = 0; k < mapped.length; k++) {
File out = getProject().resolveFile(in.getParent() + File.separator + mapped[k]);
-
+
try {
embed(in, out, options);
} catch(IOException ex) {
@@ -195,45 +195,45 @@ public void execute () throws BuildException {
}
}
}
-
+
private void embed(File input, File output, int options) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
Reader in = new InputStreamReader(new FileInputStream(input), charset);
Writer out = new OutputStreamWriter(bytes, charset);
String pathRoot = root;
-
+
if(pathRoot == null) {
pathRoot = input.getCanonicalPath();
- pathRoot = pathRoot.substring(0, pathRoot.lastIndexOf(File.separator));
+ pathRoot = pathRoot.substring(0, pathRoot.lastIndexOf(File.separator));
}
-
+
if (!pathRoot.endsWith(File.separator)){
pathRoot += File.separator;
}
-
+
if(verbose) {
log("[INFO] embedding images from '" + input + "'");
}
-
+
CSSURLEmbedder embedder = new CSSURLEmbedder(in, options, verbose, maxUriLength, maxImageSize);
-
+
if(mhtml) {
embedder.setMHTMLRoot(mhtmlRoot);
embedder.setFilename(output.getName());
}
-
+
embedder.embedImages(out, pathRoot);
-
+
in.close();
out.close();
-
+
if(bytes.size() > 0) {
FileOutputStream fos = new FileOutputStream(output);
-
+
if(verbose) {
log("[INFO] Writing to file: " + output);
}
-
+
bytes.writeTo(fos);
fos.close();
}
View
290 src/net/nczonline/web/cssembed/CSSURLEmbedder.java
@@ -1,17 +1,17 @@
/*
* Copyright (c) 2009 Nicholas C. Zakas. All rights reserved.
* http://www.nczonline.net/
- *
+ *
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
- *
+ *
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
- *
+ *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -20,7 +20,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
-
+
package net.nczonline.web.cssembed;
import java.io.BufferedReader;
@@ -41,60 +41,63 @@
* Generator for Data URIs.
* @author Nicholas C. Zakas
*/
-public class CSSURLEmbedder {
-
+public class CSSURLEmbedder {
+
public static final int DATAURI_OPTION = 1;
public static final int MHTML_OPTION = 2;
public static final int SKIP_MISSING_OPTION = 4;
+ public static final int MHTML_FILE_OPTION = 8;
public static final int DEFAULT_MAX_URI_LENGTH = 32768;
-
+
public static final String PROC_DIRECTIVE_PREFIX = "CssEmbed";
public static final String PROC_DIRECTIVE_SKIP = "SKIP";
-
+
protected static String MHTML_SEPARATOR = "CSSEmbed_Image";
-
- private static HashSet<String> imageTypes;
+
+ private static final String LINE_END = "\n";
+
+ private static HashSet<String> imageTypes;
static {
imageTypes = new HashSet<String>();
imageTypes.add("jpg");
imageTypes.add("jpeg");
imageTypes.add("gif");
imageTypes.add("png");
- }
-
+ }
+
private boolean verbose = false;
private String code = null;
private int options = 1;
private String mhtmlRoot = "";
- private String outputFilename = "";
+ private String mhtmlOutputFilename = "";
private int maxUriLength = DEFAULT_MAX_URI_LENGTH; //IE8 only allows dataURIs up to 32KB
private int maxImageSize;
-
+
//--------------------------------------------------------------------------
// Constructors
- //--------------------------------------------------------------------------
-
+ //--------------------------------------------------------------------------
+
public CSSURLEmbedder(Reader in) throws IOException {
this(in, false);
}
-
+
public CSSURLEmbedder(Reader in, int options) throws IOException {
this(in, false);
}
-
+
public CSSURLEmbedder(Reader in, boolean verbose) throws IOException {
this(in, 1, verbose);
}
-
+
public CSSURLEmbedder(Reader in, int options, boolean verbose) throws IOException {
this(in, options, verbose, 0);
}
-
+
public CSSURLEmbedder(Reader in, int options, boolean verbose, int maxUriLength) throws IOException {
this(in, options, verbose, maxUriLength, 0);
}
-
+
public CSSURLEmbedder(Reader in, int options, boolean verbose, int maxUriLength, int maxImageSize) throws IOException {
this.code = readCode(in);
this.verbose = verbose;
@@ -105,28 +108,28 @@ public CSSURLEmbedder(Reader in, int options, boolean verbose, int maxUriLength,
//--------------------------------------------------------------------------
// Get/Set verbose flag
- //--------------------------------------------------------------------------
-
+ //--------------------------------------------------------------------------
+
public boolean getVerbose(){
return verbose;
}
-
+
public void setVerbose(boolean newVerbose){
verbose = newVerbose;
}
-
+
//--------------------------------------------------------------------------
// Determine if an option is set - Options support not yet complete
- //--------------------------------------------------------------------------
-
+ //--------------------------------------------------------------------------
+
private boolean hasOption(int option){
return (options & option) > 0;
}
//--------------------------------------------------------------------------
// MHTML Support
- //--------------------------------------------------------------------------
-
+ //--------------------------------------------------------------------------
+
public String getMHTMLRoot(){
return mhtmlRoot;
}
@@ -134,100 +137,110 @@ public String getMHTMLRoot(){
public void setMHTMLRoot(String mhtmlRoot){
this.mhtmlRoot = mhtmlRoot;
}
-
+
public String getFilename(){
- return outputFilename;
+ return mhtmlOutputFilename;
}
-
+
public void setFilename(String filename){
- this.outputFilename = filename;
+ this.mhtmlOutputFilename = filename;
}
-
+
//--------------------------------------------------------------------------
// Embed images
//--------------------------------------------------------------------------
-
+
/**
* Embeds data URI images into a CSS file.
- * @param out The place to write out the source code.
+ * @param cssOut The place to write out the CSS source code.
* @throws java.io.IOException
*/
- public void embedImages(Writer out) throws IOException {
- embedImages(out, null);
+ public void embedImages(Writer cssOut) throws IOException {
+ embedImages(cssOut, null, null);
}
-
+
/**
* Embeds data URI images into a CSS file.
- * @param out The place to write out the source code.
+ * @param cssOut The place to write out the CSS source code.
* @param root The root to prepend to any relative paths.
* @throws java.io.IOException
*/
- public void embedImages(Writer out, String root) throws IOException {
- BufferedReader reader = new BufferedReader(new StringReader(code));
- StringBuilder builder = new StringBuilder();
- StringBuilder mhtmlHeader = new StringBuilder();
+ public void embedImages(Writer cssOut, String root) throws IOException {
+ embedImages(cssOut, null, root);
+ }
+
+ /**
+ * Embeds data URI images into a CSS file.
+ * @param cssOut The place to write out the CSS source code.
+ * @param mhtmlOut The place to write out the MHTML source code.
+ * @param root The root to prepend to any relative paths.
+ * @throws java.io.IOException
+ */
+ public void embedImages(Writer cssOut, Writer mhtmlOut, String root) throws IOException {
+ BufferedReader reader = new BufferedReader(new StringReader(code));
+ StringBuilder cssBuilder = new StringBuilder();
+ StringBuilder mhtmlBuilder = new StringBuilder();
HashMap<String,Integer> foundMedia = new HashMap<String,Integer>();
String line;
- int lineNum = 1;
+ int lineNum = 1;
int conversions = 0;
-
+
//create initial MHTML code
if (hasOption(MHTML_OPTION)){
- mhtmlHeader.append("/*\n");
- mhtmlHeader.append("Content-Type: multipart/related; boundary=\"");
- mhtmlHeader.append(MHTML_SEPARATOR);
- mhtmlHeader.append("\"\n\n");
+ mhtmlBuilder.append("Content-Type: multipart/related; boundary=\"");
+ mhtmlBuilder.append(MHTML_SEPARATOR);
+ mhtmlBuilder.append("\"").append(LINE_END).append(LINE_END);
}
-
+
while((line = reader.readLine()) != null){
-
+
int start = 0;
int pos = line.indexOf("url(", start);
int npos;
-
+
if (lineNum > 1){
- builder.append("\n");
+ cssBuilder.append(LINE_END);
}
-
+
Pattern checkForSkip = Pattern.compile("\\/\\*.*" + PROC_DIRECTIVE_PREFIX + ".*" + PROC_DIRECTIVE_SKIP + ".*\\*\\/", Pattern.CASE_INSENSITIVE);
Matcher skipMatch = checkForSkip.matcher(line);
if (skipMatch.find()) {
- builder.append(line);
+ cssBuilder.append(line);
if (verbose) {
System.err.println("[INFO] line #" + lineNum + " skipped due to SKIP directive (" + PROC_DIRECTIVE_PREFIX + ": " + PROC_DIRECTIVE_SKIP + ")");
}
} else if (pos > -1){
while (pos > -1){
pos += 4;
- builder.append(line.substring(start, pos));
+ cssBuilder.append(line.substring(start, pos));
npos = line.indexOf(")", pos);
String url = line.substring(pos, npos).trim();
-
+
//eliminate quotes at the beginning and end
if (url.startsWith("\"")){
if (url.endsWith("\"")){
url = url.substring(1, url.length()-1);
} else {
throw new IOException("Invalid CSS URL format (" + url + ") at line " + lineNum + ", col " + pos + ".");
- }
+ }
} else if (url.startsWith("'")){
if (url.endsWith("'")){
url = url.substring(1, url.length()-1);
} else {
throw new IOException("Invalid CSS URL format (" + url + ") at line " + lineNum + ", col " + pos + ".");
- }
+ }
}
-
+
//check for duplicates
if (foundMedia.containsKey(url)){
if (verbose){
System.err.println("[WARNING] Duplicate URL '" + url + "' found at line " + lineNum + ", previously declared at line " + foundMedia.get(url) + ".");
- }
- }
- foundMedia.put(url, lineNum);
-
+ }
+ }
+ foundMedia.put(url, lineNum);
+
//Begin processing URL
- String newUrl = url;
+ String newUrl = url;
if (verbose){
System.err.println("[INFO] Found URL '" + url + "' at line " + lineNum + ", col " + pos + ".");
}
@@ -235,19 +248,19 @@ public void embedImages(Writer out, String root) throws IOException {
newUrl = root + url;
if (verbose){
System.err.println("[INFO] Applying root to URL, URL is now '" + newUrl + "'.");
- }
+ }
}
-
+
//get the data URI format
String uriString = getImageURIString(newUrl, url);
-
+
//if it doesn't begin with data:, it's not a data URI
if (uriString.startsWith("data:")){
if (maxUriLength > 0 && uriString.length() > maxUriLength){
if (verbose){
System.err.println("[WARNING] File " + newUrl + " creates a data URI larger than " + maxUriLength + " bytes. Skipping.");
- }
- builder.append(url);
+ }
+ cssBuilder.append(url);
} else {
/*
@@ -257,43 +270,45 @@ public void embedImages(Writer out, String root) throws IOException {
if (hasOption(MHTML_OPTION)){
String entryName = getFilename(url);
- //create MHTML header entry
- mhtmlHeader.append("--");
- mhtmlHeader.append(MHTML_SEPARATOR);
- mhtmlHeader.append("\nContent-Location:");
- mhtmlHeader.append(entryName);
- mhtmlHeader.append("\nContent-Transfer-Encoding:base64\n\n");
- mhtmlHeader.append(uriString.substring(uriString.indexOf(",")+1));
- mhtmlHeader.append("\n");
+ //add MHTML content part
+ mhtmlBuilder.append(LINE_END);
+ mhtmlBuilder.append("--");
+ mhtmlBuilder.append(MHTML_SEPARATOR).append(LINE_END);
+ mhtmlBuilder.append("Content-Location:");
+ mhtmlBuilder.append(entryName).append(LINE_END);
+ mhtmlBuilder.append("Content-Transfer-Encoding:base64");
+ mhtmlBuilder.append(LINE_END).append(LINE_END);
+ mhtmlBuilder.append(uriString.substring(uriString.indexOf(",")+1));
+ mhtmlBuilder.append(LINE_END);
//output the URI
- builder.append("mhtml:");
- builder.append(getMHTMLPath());
- builder.append("!");
- builder.append(entryName);
+ cssBuilder.append("mhtml:");
+ cssBuilder.append(getMHTMLPath());
+ cssBuilder.append("!");
+ cssBuilder.append(entryName);
conversions++;
} else if (hasOption(DATAURI_OPTION)){
- builder.append(uriString);
+ cssBuilder.append(uriString);
conversions++;
}
}
} else {
//TODO: Clean up, duplicate code
- builder.append(uriString);
+ cssBuilder.append(uriString);
}
- start = npos;
+ start = npos;
pos = line.indexOf("url(", start);
- }
-
+ }
+
//finish out the line
if (start < line.length()){
- builder.append(line.substring(start));
+ cssBuilder.append(line.substring(start));
}
} else {
- builder.append(line);
+ cssBuilder.append(line);
}
-
+
lineNum++;
}
reader.close();
@@ -301,24 +316,31 @@ public void embedImages(Writer out, String root) throws IOException {
if (hasOption(MHTML_OPTION) && conversions > 0){
//Add one more boundary to fix IE/Vista issue
- mhtmlHeader.append("\n--");
- mhtmlHeader.append(MHTML_SEPARATOR);
- mhtmlHeader.append("--\n");
+ mhtmlBuilder.append(LINE_END);
+ mhtmlBuilder.append("--");
+ mhtmlBuilder.append(MHTML_SEPARATOR);
+ mhtmlBuilder.append("--").append(LINE_END);
- //close comment
- mhtmlHeader.append("*/\n");
- out.write(mhtmlHeader.toString());
+ if (hasOption(MHTML_FILE_OPTION)) {
+ // write MHTML output to MHTML file
+ mhtmlOut.write(mhtmlBuilder.toString());
+ } else {
+ // wrap MHTML output in comments, write to CSS file
+ cssOut.write("/*" + LINE_END);
+ cssOut.write(mhtmlBuilder.toString());
+ cssOut.write("*/"+ LINE_END);
+ }
}
-
+
if (verbose){
System.err.println("[INFO] Converted " + conversions + " images to data URIs.");
}
- out.write(builder.toString());
+ cssOut.write(cssBuilder.toString());
}
-
+
/**
- * Returns a URI string for the given URL. If the URL is for an image,
+ * Returns a URI string for the given URL. If the URL is for an image,
* the data URI will be returned. If the URL is not for an image, then the
* original URI is returned.
* @param url The URL to attempt to read.
@@ -327,80 +349,80 @@ public void embedImages(Writer out, String root) throws IOException {
* @throws java.io.IOException
*/
String getImageURIString(String url, String originalUrl) throws IOException {
-
+
//it's an image, so encode it
if (isImage(url)){
-
+
DataURIGenerator.setVerbose(verbose);
-
+
StringWriter writer = new StringWriter();
-
+
try {
if (url.startsWith("http://")){
if (verbose){
System.err.println("[INFO] Downloading '" + url + "' to generate data URI.");
- }
-
- DataURIGenerator.generate(new URL(url), writer);
-
+ }
+
+ DataURIGenerator.generate(new URL(url), writer);
+
} else {
if (verbose){
System.err.println("[INFO] Opening file '" + url + "' to generate data URI.");
- }
-
+ }
+
File file = new File(url);
-
+
if (verbose && !file.isFile()){
System.err.println("[INFO] Could not find file '" + file.getCanonicalPath() + "'.");
}
-
+
//check file size if we've been asked to
if (maxImageSize > 0 && file.length() > maxImageSize){
if (verbose){
System.err.println("[INFO] File '" + originalUrl + "' is larger than " + maxImageSize + " bytes. Skipping.");
}
-
+
writer.write(originalUrl);
-
+
} else {
- DataURIGenerator.generate(new File(url), writer);
+ DataURIGenerator.generate(new File(url), writer);
}
}
if (verbose){
System.err.println("[INFO] Generated data URI for '" + url + "'.");
}
- } catch (FileNotFoundException e){
+ } catch (FileNotFoundException e){
if(hasOption(SKIP_MISSING_OPTION)) {
if (verbose){
System.err.println("[INFO] Could not find file. " + e.getMessage() + " Skipping.");
}
-
+
writer.write(originalUrl);
} else {
throw e;
}
}
-
+
return writer.toString();
-
+
} else {
-
+
if (verbose){
System.err.println("[INFO] URL '" + originalUrl + "' is not an image, skipping.");
}
-
+
//not an image, ignore
return originalUrl;
}
-
+
}
/*
* Detects if the given url represents an image
- * This method simply checks the file extension.
- * A better way to detect an image is via content type response headers or by content sniffing,
- * but both are expensive approaches. We can do without them for now.
+ * This method simply checks the file extension.
+ * A better way to detect an image is via content type response headers or by content sniffing,
+ * but both are expensive approaches. We can do without them for now.
*/
static boolean isImage(String url) {
int startPos = url.lastIndexOf(".") + 1;
@@ -424,28 +446,28 @@ private String getFilename(String path){
return path;
}
}
-
+
private String getMHTMLPath(){
String result = mhtmlRoot;
if (!result.endsWith("/")){
result += "/";
}
-
- result += outputFilename;
-
+
+ result += mhtmlOutputFilename;
+
return result;
}
-
+
private String readCode(Reader in) throws IOException {
StringBuilder builder = new StringBuilder();
int c;
-
+
while ((c = in.read()) != -1){
builder.append((char)c);
}
-
+
in.close();
return builder.toString();
}
-
+
}
View
464 src/net/nczonline/web/datauri/Base64.java
@@ -4,16 +4,16 @@
/**
* <p>Encodes and decodes to and from Base64 notation.</p>
* <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p>
- *
+ *
* <p>Example:</p>
- *
+ *
* <code>String encoded = Base64.encode( myByteArray );</code>
* <br />
* <code>byte[] myByteArray = Base64.decode( encoded );</code>
*
- * <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass
- * several pieces of information to the encoder. In the "higher level" methods such as
- * encodeBytes( bytes, options ) the options parameter can be used to indicate such
+ * <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass
+ * several pieces of information to the encoder. In the "higher level" methods such as
+ * encodeBytes( bytes, options ) the options parameter can be used to indicate such
* things as first gzipping the bytes before encoding them, not inserting linefeeds,
* and encoding using the URL-safe and Ordered dialects.</p>
*
@@ -22,7 +22,7 @@
* to do so. I've got Base64 set to this behavior now, although earlier versions
* broke lines by default.</p>
*
- * <p>The constants defined in Base64 can be OR-ed together to combine options, so you
+ * <p>The constants defined in Base64 can be OR-ed together to combine options, so you
* might make a call like this:</p>
*
* <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code>
@@ -60,7 +60,7 @@
* <li>v2.3 - <strong>This is not a drop-in replacement!</strong> This is two years of comments
* and bug fixes queued up and finally executed. Thanks to everyone who sent
* me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else.
- * Much bad coding was cleaned up including throwing exceptions where necessary
+ * Much bad coding was cleaned up including throwing exceptions where necessary
* instead of returning null values or something similar. Here are some changes
* that may affect you:
* <ul>
@@ -98,24 +98,24 @@
* Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a>
* for contributing the new Base64 dialects.
* </li>
- *
+ *
* <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
* some convenience methods for reading and writing to and from files.</li>
* <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
* with other encodings (like EBCDIC).</li>
* <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
* encoded data was a single byte.</li>
- * <li>v2.0 - I got rid of methods that used booleans to set options.
+ * <li>v2.0 - I got rid of methods that used booleans to set options.
* Now everything is more consolidated and cleaner. The code now detects
* when data that's being decoded is gzip-compressed and will decompress it
* automatically. Generally things are cleaner. You'll probably have to
* change some method calls that you were making to support the new
* options format (<tt>int</tt>s that you "OR" together).</li>
- * <li>v1.5.1 - Fixed bug when decompressing and decoding to a
- * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
- * Added the ability to "suspend" encoding in the Output Stream so
- * you can turn on and off the encoding if you need to embed base64
- * data in an otherwise "normal" stream (like an XML file).</li>
+ * <li>v1.5.1 - Fixed bug when decompressing and decoding to a
+ * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
+ * Added the ability to "suspend" encoding in the Output Stream so
+ * you can turn on and off the encoding if you need to embed base64
+ * data in an otherwise "normal" stream (like an XML file).</li>
* <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
* This helps when using GZIP streams.
* Added the ability to GZip-compress objects before encoding them.</li>
@@ -141,36 +141,36 @@
*/
public class Base64
{
-
-/* ******** P U B L I C F I E L D S ******** */
-
-
+
+/* ******** P U B L I C F I E L D S ******** */
+
+
/** No options specified. Value is zero. */
public final static int NO_OPTIONS = 0;
-
+
/** Specify encoding in first bit. Value is one. */
public final static int ENCODE = 1;
-
-
+
+
/** Specify decoding in first bit. Value is zero. */
public final static int DECODE = 0;
-
+
/** Specify that data should be gzip-compressed in second bit. Value is two. */
public final static int GZIP = 2;
/** Specify that gzipped data should <em>not</em> be automatically gunzipped. */
public final static int DONT_GUNZIP = 4;
-
-
+
+
/** Do break lines when encoding. Value is 8. */
public final static int DO_BREAK_LINES = 8;
-
- /**
+
+ /**
* Encode using Base64-like encoding that is URL- and Filename-safe as described
- * in Section 4 of RFC3548:
+ * in Section 4 of RFC3548:
* <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
- * It is important to note that data encoded this way is <em>not</em> officially valid Base64,
+ * It is important to note that data encoded this way is <em>not</em> officially valid Base64,
* or at the very least should not be called Base64 without also specifying that is
* was encoded using the URL- and Filename-safe dialect.
*/
@@ -182,50 +182,50 @@
* <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
public final static int ORDERED = 32;
-
-
-/* ******** P R I V A T E F I E L D S ******** */
-
-
+
+
+/* ******** P R I V A T E F I E L D S ******** */
+
+
/** Maximum line length (76) of Base64 output. */
private final static int MAX_LINE_LENGTH = 76;
-
-
+
+
/** The equals sign (=) as a byte. */
private final static byte EQUALS_SIGN = (byte)'=';
-
-
+
+
/** The new line character (\n) as a byte. */
private final static byte NEW_LINE = (byte)'\n';
-
-
+
+
/** Preferred encoding. */
private final static String PREFERRED_ENCODING = "US-ASCII";
-
-
+
+
private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
-
-
-/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
-
+
+
+/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
+
/** The 64 valid Base64 values. */
/* Host platform me be something funny like EBCDIC, so we hardcode these values. */
private final static byte[] _STANDARD_ALPHABET = {
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
- (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
+ (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
- (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
+ (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
- (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
+ (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
};
-
-
- /**
+
+
+ /**
* Translates a Base64 value to either its 6-bit reconstruction value
* or a negative number indicating some other meaning.
**/
@@ -262,28 +262,28 @@
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
-
-
+
+
/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
-
+
/**
- * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548:
+ * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548:
* <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
* Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash."
*/
private final static byte[] _URL_SAFE_ALPHABET = {
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
- (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
+ (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
- (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
+ (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
- (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
+ (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_'
};
-
+
/**
* Used in decoding URL- and Filename-safe dialects of Base64.
*/
@@ -348,7 +348,7 @@
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z'
};
-
+
/**
* Used in decoding the "ordered" dialect of Base64.
*/
@@ -390,7 +390,7 @@
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
-
+
/* ******** D E T E R M I N E W H I C H A L H A B E T ******** */
@@ -430,16 +430,16 @@
} // end getAlphabet
-
+
/** Defeats instantiation. */
private Base64(){}
-
-
-
-/* ******** E N C O D I N G M E T H O D S ******** */
-
-
+
+
+
+/* ******** E N C O D I N G M E T H O D S ******** */
+
+
/**
* Encodes up to the first three bytes of array <var>threeBytes</var>
* and returns a four-byte array in Base64 notation.
@@ -460,12 +460,12 @@ private Base64(){}
return b4;
} // end encode3to4
-
+
/**
* <p>Encodes up to three bytes of the array <var>source</var>
* and writes the resulting four Base64 bytes to <var>destination</var>.
* The source and destination arrays can be manipulated
- * anywhere along their length by specifying
+ * anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 3 for
@@ -484,19 +484,19 @@ private Base64(){}
* @return the <var>destination</var> array
* @since 1.3
*/
- private static byte[] encode3to4(
+ private static byte[] encode3to4(
byte[] source, int srcOffset, int numSigBytes,
byte[] destination, int destOffset, int options ) {
-
- byte[] ALPHABET = getAlphabet( options );
-
- // 1 2 3
+
+ byte[] ALPHABET = getAlphabet( options );
+
+ // 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index ALPHABET
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
-
+
// Create buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
@@ -513,21 +513,21 @@ private Base64(){}
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ];
return destination;
-
+
case 2:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
-
+
case 1:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = EQUALS_SIGN;
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
-
+
default:
return destination;
} // end switch
@@ -585,18 +585,18 @@ public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded
}
-
-
+
+
/**
* Serializes an object and returns the Base64-encoded
- * version of that serialized object.
- *
+ * version of that serialized object.
+ *
* <p>As of v 2.3, if the object
* cannot be serialized or there is another error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
- *
+ *
* The object is not GZip-compressed before being encoded.
*
* @param serializableObject The object to encode
@@ -609,19 +609,19 @@ public static String encodeObject( java.io.Serializable serializableObject )
throws java.io.IOException {
return encodeObject( serializableObject, NO_OPTIONS );
} // end encodeObject
-
+
/**
* Serializes an object and returns the Base64-encoded
* version of that serialized object.
- *
+ *
* <p>As of v 2.3, if the object
* cannot be serialized or there is another error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
- *
+ *
* The object is not GZip-compressed before being encoded.
* <p>
* Example options:<pre>
@@ -647,14 +647,14 @@ public static String encodeObject( java.io.Serializable serializableObject, int
if( serializableObject == null ){
throw new NullPointerException( "Cannot serialize a null object." );
} // end if: null
-
+
// Streams
- java.io.ByteArrayOutputStream baos = null;
+ java.io.ByteArrayOutputStream baos = null;
java.io.OutputStream b64os = null;
java.util.zip.GZIPOutputStream gzos = null;
java.io.ObjectOutputStream oos = null;
-
-
+
+
try {
// ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
baos = new java.io.ByteArrayOutputStream();
@@ -680,7 +680,7 @@ public static String encodeObject( java.io.Serializable serializableObject, int
try{ b64os.close(); } catch( Exception e ){}
try{ baos.close(); } catch( Exception e ){}
} // end finally
-
+
// Return value according to relevant encoding.
try {
return new String( baos.toByteArray(), PREFERRED_ENCODING );
@@ -689,15 +689,15 @@ public static String encodeObject( java.io.Serializable serializableObject, int
// Fall back to some Java default
return new String( baos.toByteArray() );
} // end catch
-
+
} // end encode
-
-
+
+
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
- *
+ *
* @param source The data to convert
* @return The data in Base64-encoded form
* @throws NullPointerException if source array is null
@@ -716,7 +716,7 @@ public static String encodeBytes( byte[] source ) {
assert encoded != null;
return encoded;
} // end encodeBytes
-
+
/**
@@ -732,12 +732,12 @@ public static String encodeBytes( byte[] source ) {
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
- *
+ *
* <p>As of v 2.3, if there is an error with the GZIP stream,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
- *
+ *
*
* @param source The data to convert
* @param options Specified options
@@ -751,17 +751,17 @@ public static String encodeBytes( byte[] source ) {
public static String encodeBytes( byte[] source, int options ) throws java.io.IOException {
return encodeBytes( source, 0, source.length, options );
} // end encodeBytes
-
-
+
+
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
- *
+ *
* <p>As of v 2.3, if there is an error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
- *
+ *
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
@@ -784,8 +784,8 @@ public static String encodeBytes( byte[] source, int off, int len ) {
assert encoded != null;
return encoded;
} // end encodeBytes
-
-
+
+
/**
* Encodes a byte array into Base64 notation.
@@ -800,12 +800,12 @@ public static String encodeBytes( byte[] source, int off, int len ) {
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
- *
+ *
* <p>As of v 2.3, if there is an error with the GZIP stream,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
- *
+ *
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
@@ -829,7 +829,7 @@ public static String encodeBytes( byte[] source, int off, int len, int options )
catch (java.io.UnsupportedEncodingException uue) {
return new String( encoded );
} // end catch
-
+
} // end encodeBytes
@@ -975,34 +975,34 @@ public static String encodeBytes( byte[] source, int off, int len, int options )
//System.err.println("No need to resize array.");
return outBuff;
}
-
+
} // end else: don't compress
} // end encodeBytesToBytes
-
-
-
-
+
+
+
+
/* ******** D E C O D I N G M E T H O D S ******** */
-
-
+
+
/**
* Decodes four bytes from array <var>source</var>
* and writes the resulting bytes (up to three of them)
* to <var>destination</var>.
* The source and destination arrays can be manipulated
- * anywhere along their length by specifying
+ * anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 4 for
* the <var>source</var> array or <var>destOffset</var> + 3 for
* the <var>destination</var> array.
- * This method returns the actual number of bytes that
+ * This method returns the actual number of bytes that
* were converted from the Base64 encoding.
* <p>This is the lowest level of the decoding methods with
* all possible parameters.</p>
- *
+ *
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
@@ -1015,10 +1015,10 @@ public static String encodeBytes( byte[] source, int off, int len, int options )
* or there is not enough room in the array.
* @since 1.3
*/
- private static int decode4to3(
- byte[] source, int srcOffset,
+ private static int decode4to3(
+ byte[] source, int srcOffset,
byte[] destination, int destOffset, int options ) {
-
+
// Lots of error checking and exception throwing
if( source == null ){
throw new NullPointerException( "Source array was null." );
@@ -1027,17 +1027,17 @@ private static int decode4to3(
throw new NullPointerException( "Destination array was null." );
} // end if
if( srcOffset < 0 || srcOffset + 3 >= source.length ){
- throw new IllegalArgumentException(
+ throw new IllegalArgumentException(
"Source array with length " + source.length + " cannot have offset of " + srcOffset + " and still process four bytes.");
} // end if
if( destOffset < 0 || destOffset +2 >= destination.length ){
throw new IllegalArgumentException(
"Destination array with length " + destination.length + " cannot have offset of " );
} // end if
-
-
- byte[] DECODABET = getDecodabet( options );
-
+
+
+ byte[] DECODABET = getDecodabet( options );
+
// Example: Dk==
if( source[ srcOffset + 2] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
@@ -1045,11 +1045,11 @@ private static int decode4to3(
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
-
+
destination[ destOffset ] = (byte)( outBuff >>> 16 );
return 1;
}
-
+
// Example: DkL=
else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
@@ -1059,12 +1059,12 @@ else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
-
+
destination[ destOffset ] = (byte)( outBuff >>> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
return 2;
}
-
+
// Example: DkLE
else {
// Two ways to do the same thing. Don't know which way I like best.
@@ -1077,7 +1077,7 @@ else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
| ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
-
+
destination[ destOffset ] = (byte)( outBuff >> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
destination[ destOffset + 2 ] = (byte)( outBuff );
@@ -1085,7 +1085,7 @@ else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
return 3;
}
} // end decodeToBytes
-
+
@@ -1113,8 +1113,8 @@ else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
return decoded;
}
-
-
+
+
/**
* Low-level access to decoding ASCII characters in
* the form of a byte array. <strong>Ignores GUNZIP option, if
@@ -1134,7 +1134,7 @@ else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
*/
public static byte[] decode( byte[] source, int off, int len, int options )
throws java.io.IOException {
-
+
// Lots of error checking and exception throwing
if( source == null ){
throw new NullPointerException( "Cannot decode null source array." );
@@ -1143,31 +1143,31 @@ else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
throw new IllegalArgumentException(
"Source array with length " + source.length + " cannot have offset of " + off + " and process " + len + " bytes." );
} // end if
-
+
if( len == 0 ){
return new byte[0];
}else if( len < 4 ){
- throw new IllegalArgumentException(
+ throw new IllegalArgumentException(
"Base64-encoded string must have at least four characters, but length specified was " + len );
} // end if
-
+
byte[] DECODABET = getDecodabet( options );
-
+
int len34 = len * 3 / 4; // Estimate on array size
byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
int outBuffPosn = 0; // Keep track of where we're writing
-
+
byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space
int b4Posn = 0; // Keep track of four byte input buffer
int i = 0; // Source array counter
byte sbiCrop = 0; // Low seven bits (ASCII) of input
byte sbiDecode = 0; // Special value from DECODABET
-
+
for( i = off; i < off+len; i++ ) { // Loop through source
-
+
sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
sbiDecode = DECODABET[ sbiCrop ]; // Special value
-
+
// White space, Equals sign, or legit Base64 character
// Note the values such as -5 and -9 in the
// DECODABETs at the top of the file.
@@ -1177,7 +1177,7 @@ else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
if( b4Posn > 3 ) { // Time to decode?
outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options );
b4Posn = 0;
-
+
// If that was the equals sign, break out of 'for' loop
if( sbiCrop == EQUALS_SIGN ) {
break;
@@ -1187,19 +1187,19 @@ else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
} // end if: white space, equals sign or better
else {
// There's a bad input character in the Base64 stream.
- throw new java.io.IOException(
+ throw new java.io.IOException(
"Bad Base64 input character '" + source[i] + "' in array position " + i);
- } // end else:
+ } // end else:
} // each input character
-
+
byte[] out = new byte[ outBuffPosn ];
- System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
+ System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
return out;
} // end decode
-
-
-
-
+
+
+
+
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
@@ -1213,8 +1213,8 @@ else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
return decode( s, NO_OPTIONS );
}
-
-
+
+
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
@@ -1227,11 +1227,11 @@ else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
* @since 1.4
*/
public static byte[] decode( String s, int options ) throws java.io.IOException {
-
+
if( s == null ){
throw new NullPointerException( "Input string was null." );
} // end if
-
+
byte[] bytes;
try {
bytes = s.getBytes( PREFERRED_ENCODING );
@@ -1240,15 +1240,15 @@ else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
bytes = s.getBytes();
} // end catch
//</change>
-
+
// Decode
bytes = decode( bytes, 0, bytes.length, options );
-
+
// Check to see if it's gzip-compressed
// GZIP Magic Two-Byte Number: 0x8b1f (35615)
boolean dontGunzip = (options & DONT_GUNZIP) != 0;
if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) {
-
+
int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) {
java.io.ByteArrayInputStream bais = null;
@@ -1282,14 +1282,14 @@ else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
} // end if: gzipped
} // end if: bytes.length >= 2
-
+
return bytes;
} // end decode
-
+
/* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
-
-
-
+
+
+
/**
* A {@link Base64.InputStream} will read data from another
* <tt>java.io.InputStream</tt>, given in the constructor,
@@ -1299,7 +1299,7 @@ else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
* @since 1.3
*/
public static class InputStream extends java.io.FilterInputStream {
-
+
private boolean encode; // Encoding or decoding
private int position; // Current position in the buffer
private byte[] buffer; // Small buffer holding converted data
@@ -1309,8 +1309,8 @@ else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
private boolean breakLines; // Break lines at less than 80 characters
private int options; // Record options used to create the stream.
private byte[] decodabet; // Local copies to avoid extra method calls
-
-
+
+
/**
* Constructs a {@link Base64.InputStream} in DECODE mode.
*
@@ -1320,8 +1320,8 @@ else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
public InputStream( java.io.InputStream in ) {
this( in, DECODE );
} // end constructor
-
-
+
+
/**
* Constructs a {@link Base64.InputStream} in
* either ENCODE or DECODE mode.
@@ -1343,7 +1343,7 @@ public InputStream( java.io.InputStream in ) {
* @since 2.0
*/
public InputStream( java.io.InputStream in, int options ) {
-
+
super( in );
this.options = options; // Record for later
this.breakLines = (options & DO_BREAK_LINES) > 0;
@@ -1354,7 +1354,7 @@ public InputStream( java.io.InputStream in, int options ) {
this.lineLength = 0;
this.decodabet = getDecodabet(options);
} // end constructor
-
+
/**
* Reads enough of the input stream to convert
* to/from Base64 and returns the next byte.
@@ -1363,7 +1363,7 @@ public InputStream( java.io.InputStream in, int options ) {
* @since 1.3
*/
public int read() throws java.io.IOException {
-
+
// Do we need to get data?
if( position < 0 ) {
if( encode ) {
@@ -1379,9 +1379,9 @@ public int read() throws java.io.IOException {
} else {
break; // out of for loop
} // end else: end of stream
-
+
} // end for: each needed input byte
-
+
if( numBinaryBytes > 0 ) {
encode3to4( b3, 0, numBinaryBytes, buffer, 0, options );
position = 0;
@@ -1391,7 +1391,7 @@ public int read() throws java.io.IOException {
return -1; // Must be end of stream
} // end else
} // end if: encoding
-
+
// Else decoding
else {
byte[] b4 = new byte[4];
@@ -1401,14 +1401,14 @@ public int read() throws java.io.IOException {
int b = 0;
do{ b = in.read(); }
while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC );
-
+
if( b < 0 ) {
break; // Reads a -1 if end of stream
} // end if: end of stream
-
+
b4[i] = (byte)b;
} // end for: each needed input byte
-
+
if( i == 4 ) {
numSigBytes = decode4to3( b4, 0, buffer, 0, options );
position = 0;
@@ -1419,18 +1419,18 @@ else if( i == 0 ){
else {
// Must have broken out from above.
throw new java.io.IOException( "Improperly padded Base64 input." );
- } // end
-
+ } // end
+
} // end else: decode
} // end else: get data
-
+
// Got data?
if( position >= 0 ) {
// End of relevant data?
if( /*!encode &&*/ position >= numSigBytes ){
return -1;
} // end if: got data
-
+
if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) {
lineLength = 0;
return '\n';
@@ -1439,7 +1439,7 @@ else if( i == 0 ){
lineLength++; // This isn't important when decoding
// but throwing an extra "if" seems
// just as wasteful.
-
+
int b = buffer[ position++ ];
if( position >= bufferLength ) {
@@ -1450,14 +1450,14 @@ else if( i == 0 ){
// intended to be unsigned.
} // end else
} // end if: position >= 0
-
+
// Else error
else {
throw new java.io.IOException( "Error in Base64 code reading stream." );
} // end else