code
stringlengths
3
1.18M
language
stringclasses
1 value
package com.googlecode.pngtastic.core; import java.io.UnsupportedEncodingException; import java.util.zip.CRC32; /** * Represents a PNG chunk * * @author rayvanderborght */ public class PngChunk { /** critical chunks */ public static final String IMAGE_HEADER = "IHDR"; public static final String PALETTE = "PLTE"; public static final String IMAGE_DATA = "IDAT"; public static final String IMAGE_TRAILER = "IEND"; /** ancilliary chunks */ public static final String TRANSPARANCY = "TRNS"; public static final String COLOR_SPACE_INFO = "CHRM"; public static final String IMAGE_GAMA = "GAMA"; public static final String EMBEDDED_ICCP_PROFILE = "ICCP"; public static final String SIGNIFICANT_BITS = "SBIT"; public static final String STANDARD_RGB = "SRGB"; public static final String TEXTUAL_DATA = "TEXT"; public static final String COMPRESSED_TEXTUAL_DATA = "ZTXT"; public static final String INTERNATIONAL_TEXTUAL_DATA = "ITXT"; public static final String BACKGROUND_COLOR = "BKGD"; public static final String IMAGE_HISTOGRAM = "HIST"; public static final String PHYSICAL_PIXEL_DIMENSIONS = "PHYS"; public static final String SUGGESTED_PALETTE = "SPLT"; public static final String IMAGE_LAST_MODIFICATION_TIME = "TIME"; private final byte[] type; private final byte[] data; /** */ public PngChunk(byte[] type, byte[] data) { this.type = (type == null) ? null : type.clone(); this.data = (data == null) ? null : data.clone(); } /** */ public String getTypeString() { try { return new String(this.type, "UTF8"); } catch(UnsupportedEncodingException e) { return ""; } } /** */ public byte[] getType() { return (this.type == null) ? null : this.type.clone(); } /** */ public byte[] getData() { return (this.data == null) ? null : this.data.clone(); } /** */ public int getLength() { return this.data.length; } /** */ public long getWidth() { return this.getUnsignedInt(0); } /** */ public long getHeight() { return this.getUnsignedInt(4); } /** */ public short getBitDepth() { return this.getUnsignedByte(8); } /** */ public short getColorType() { return this.getUnsignedByte(9); } /** */ public short getCompression() { return this.getUnsignedByte(10); } /** */ public short getFilter() { return this.getUnsignedByte(11); } /** */ public short getInterlace() { return this.getUnsignedByte(12); } /** */ public void setInterlace(byte interlace) { this.data[12] = interlace; } /** */ public long getUnsignedInt(int offset) { long value = 0; for (int i = 0; i < 4; i++) { value += (this.data[offset + i] & 0xff) << ((3 - i) * 8); } return value; } /** */ public short getUnsignedByte(int offset) { return (short) (this.data[offset] & 0x00ff); } /** */ public boolean isCritical() { String type = this.getTypeString().toUpperCase(); return type.equals(IMAGE_HEADER) || type.equals(PALETTE) || type.equals(IMAGE_DATA) || type.equals(IMAGE_TRAILER); } /** */ public boolean isRequired() { return this.isCritical() || TRANSPARANCY.equals(this.getTypeString().toUpperCase()) || IMAGE_GAMA.equals(this.getTypeString().toUpperCase()) || COLOR_SPACE_INFO.equals(this.getTypeString().toUpperCase()); } /** */ public boolean verifyCRC(long crc) { return (this.getCRC() == crc); } /** */ public long getCRC() { CRC32 crc32 = new CRC32(); crc32.update(this.type); crc32.update(this.data); return crc32.getValue(); } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder result = new StringBuilder(); result.append('[').append(this.getTypeString()).append(']').append('\n'); if (PngChunk.IMAGE_HEADER.equals(this.getTypeString().toUpperCase())) { result.append("Size: ").append(this.getWidth()).append('x').append(this.getHeight()).append('\n'); result.append("Bit depth: ").append(this.getBitDepth()).append('\n'); result.append("Image type: ").append(this.getColorType()).append(" (").append(PngImageType.forColorType(this.getColorType())).append(")\n"); result.append("Color type: ").append(this.getColorType()).append('\n'); result.append("Compression: ").append(this.getCompression()).append('\n'); result.append("Filter: ").append(this.getFilter()).append('\n'); result.append("Interlace: ").append(this.getInterlace()); } if (PngChunk.TEXTUAL_DATA.equals(this.getTypeString().toUpperCase())) { result.append("Text: ").append(new String(this.data)); } if (PngChunk.IMAGE_DATA.equals(this.getTypeString().toUpperCase())) { result.append("Image Data: ") .append("length=").append(this.getLength()).append(", data="); // for (byte b : this.data) // result.append(String.format("%x", b)); result.append(", crc=").append(this.getCRC()); } return result.toString(); } }
Java
package com.googlecode.pngtastic.core; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; /** * Represents a png image * * @author rayvanderborght */ public class PngImage { private final Logger log; public static final long SIGNATURE = 0x89504e470d0a1a0aL; /** */ private String fileName; public String getFileName() { return this.fileName; } public void setFileName(String fileName) { this.fileName = fileName; } /** */ private List<PngChunk> chunks = new ArrayList<PngChunk>(); public List<PngChunk> getChunks() { return this.chunks; } /** */ private long width; public long getWidth() { return this.width; } /** */ private long height; public long getHeight() { return this.height; } /** */ private short bitDepth; public short getBitDepth() { return this.bitDepth; } /** */ private short colorType; public short getColorType() { return this.colorType; } /** */ private short interlace; public short getInterlace() { return this.interlace; } public void setInterlace(short interlace) { this.interlace = interlace; } /** */ private PngImageType imageType; /** */ public PngImage() { this.log = new Logger(Logger.NONE); } /** */ public PngImage(Logger log) { this.log = log; } /** */ public PngImage(String fileName) throws FileNotFoundException { this(new BufferedInputStream(new FileInputStream(fileName))); this.fileName = fileName; } /** */ public PngImage(InputStream ins) { this(); try { DataInputStream dis = new DataInputStream(ins); readSignature(dis); int length = 0; PngChunk chunk = null; do { length = getChunkLength(dis); byte[] type = getChunkType(dis); byte[] data = getChunkData(dis, length); long crc = getChunkCrc(dis); chunk = new PngChunk(type, data); if (!chunk.verifyCRC(crc)) { throw new PngException("Corrupted file, crc check failed"); } addChunk(chunk); } while (length > 0 && !PngChunk.IMAGE_TRAILER.equals(chunk.getTypeString())); } catch (IOException e) { this.log.error("Error: %s", e.getMessage()); } catch (PngException e) { this.log.error("Error: %s", e.getMessage()); } } /** */ public File export(String fileName, byte[] bytes) throws FileNotFoundException, IOException { File out = new File(fileName); writeFileOutputStream(out, bytes); return out; } /** */ FileOutputStream writeFileOutputStream(File out, byte[] bytes) throws FileNotFoundException, IOException { FileOutputStream outs = null; try { outs = new FileOutputStream(out); outs.write(bytes); } finally { if (outs != null) { outs.close(); } } return outs; } /** */ public DataOutputStream writeDataOutputStream(OutputStream output) throws IOException { DataOutputStream outs = new DataOutputStream(output); outs.writeLong(PngImage.SIGNATURE); for (PngChunk chunk : chunks) { log.debug("export: %s", chunk.toString()); outs.writeInt(chunk.getLength()); outs.write(chunk.getType()); outs.write(chunk.getData()); int i = (int)chunk.getCRC(); outs.writeInt(i); } outs.close(); return outs; } /** */ public void addChunk(PngChunk chunk) { if (PngChunk.IMAGE_HEADER.equals(chunk.getTypeString())) { this.width = chunk.getWidth(); this.height = chunk.getHeight(); this.bitDepth = chunk.getBitDepth(); this.colorType = chunk.getColorType(); this.interlace = chunk.getInterlace(); } this.chunks.add(chunk); } /** */ public byte[] getImageData() { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); // Write all the IDAT data for (PngChunk chunk : chunks) { if (chunk.getTypeString().equals("IDAT")) { out.write(chunk.getData()); } } return out.toByteArray(); } catch (IOException e) { System.out.println("Couldn't get image data: " + e); } return null; } /** */ public int getSampleBitCount() { this.imageType = (this.imageType == null) ? PngImageType.forColorType(this.colorType) : this.imageType; return this.imageType.channelCount() * this.bitDepth; } /* */ private int getChunkLength(DataInputStream ins) throws IOException { return ins.readInt(); } /* */ private byte[] getChunkType(InputStream ins) throws PngException { return getChunkData(ins, 4); } /* */ private byte[] getChunkData(InputStream ins, int length) throws PngException { byte[] data = new byte[length]; try { int actual = ins.read(data); if (actual < length) { throw new PngException(String.format("Expected %d bytes but got %d", length, actual)); } } catch(IOException e) { throw new PngException("Error reading chunk data", e); } return data; } /* */ private long getChunkCrc(DataInputStream ins) throws IOException { int i = ins.readInt(); long crc = i & 0x00000000ffffffffL; // Make it unsigned. return crc; } /* */ private static void readSignature(DataInputStream ins) throws PngException, IOException { long signature = ins.readLong(); if (signature != PngImage.SIGNATURE) { throw new PngException("Bad png signature"); } } }
Java
package com.googlecode.pngtastic.core; import java.util.Arrays; import java.util.List; /** * Custom logger because I want to have zero dependancies; perhaps to be replaced with java.util logging. * * @author rayvanderborght */ public class Logger { static final String NONE = "NONE"; static final String DEBUG = "DEBUG"; static final String INFO = "INFO"; static final String ERROR = "ERROR"; private static final List<String> LOG_LEVELS = Arrays.asList(NONE, DEBUG, INFO, ERROR); private final String logLevel; /** */ Logger(String logLevel) { this.logLevel = (logLevel == null || !LOG_LEVELS.contains(logLevel.toUpperCase())) ? INFO : logLevel.toUpperCase(); } /** * Write debug messages. * Takes a varags list of args so that string concatenation only happens if the logging level applies. */ public void debug(String message, Object... args) { if (DEBUG.equals(this.logLevel)) { System.out.println(String.format(message, args)); } } /** * Write info messages. * Takes a varags list of args so that string concatenation only happens if the logging level applies. */ public void info(String message, Object... args) { if (DEBUG.equals(this.logLevel) || INFO.equals(this.logLevel)) { System.out.println(String.format(message, args)); } } /** * Write error messages. * Takes a varags list of args so that string concatenation only happens if the logging level applies. */ public void error(String message, Object... args) { if (!NONE.equals(this.logLevel)) { System.out.println(String.format(message, args)); } } }
Java
package com.googlecode.pngtastic.core; /** * Exception type for pngtastic code * * @author rayvanderborght */ @SuppressWarnings("serial") public class PngException extends Exception { /** */ public PngException() { } /** */ public PngException(String message) { super(message); } /** */ public PngException(String message, Throwable cause) { super(message, cause); } }
Java
package com.googlecode.pngtastic.core; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.googlecode.pngtastic.core.PngOptimizer.Stats; import com.googlecode.pngtastic.core.processing.PngCompressionHandler; import com.googlecode.pngtastic.core.processing.PngFilterHandler; import com.googlecode.pngtastic.core.processing.PngInterlaceHandler; import com.googlecode.pngtastic.core.processing.PngtasticCompressionHandler; import com.googlecode.pngtastic.core.processing.PngtasticFilterHandler; import com.googlecode.pngtastic.core.processing.PngtasticInterlaceHandler; /** * Layers PNG images on top of one another. Currently expects two images of the * same size. Both images must be truecolor images, and the layer image * (foreground) must have an alpha channel. * * @author rayvanderborght */ public class PngLayerer { private final Logger log; private PngFilterHandler pngFilterHandler; private PngInterlaceHandler pngInterlaceHander; private PngCompressionHandler pngCompressionHandler; private final List<Stats> stats = new ArrayList<Stats>(); public List<Stats> getStats() { return this.stats; } /** */ public PngLayerer() { this(Logger.NONE); } /** */ public PngLayerer(String logLevel) { this.log = new Logger(logLevel); this.pngFilterHandler = new PngtasticFilterHandler(this.log); this.pngInterlaceHander = new PngtasticInterlaceHandler(this.log, this.pngFilterHandler); this.pngCompressionHandler = new PngtasticCompressionHandler(this.log); } /** */ public PngImage layer(PngImage baseImage, PngImage layerImage, Integer compressionLevel, boolean concurrent) throws IOException { this.log.debug("=== LAYERING: " + baseImage.getFileName() + ", " + layerImage.getFileName() + " ==="); long start = System.currentTimeMillis(); // FIXME: support low bit depth interlaced images if (baseImage.getInterlace() == 1 && baseImage.getSampleBitCount() < 8) { return baseImage; } PngImage result = new PngImage(this.log); result.setInterlace((short) 0); Iterator<PngChunk> itBaseChunks = baseImage.getChunks().iterator(); PngChunk lastBaseChunk = this.processHeadChunks(new PngImage(), itBaseChunks); byte[] inflatedBaseImageData = this.getInflatedImageData(lastBaseChunk, itBaseChunks); List<byte[]> baseImageScanlines = this.getScanlines(baseImage, inflatedBaseImageData); Iterator<PngChunk> itLayerChunks = layerImage.getChunks().iterator(); PngChunk lastLayerChunk = this.processHeadChunks(result, itLayerChunks); byte[] inflatedLayerImageData = this.getInflatedImageData(lastLayerChunk, itLayerChunks); List<byte[]> layerImageScanlines = this.getScanlines(layerImage, inflatedLayerImageData); List<byte[]> newImageScanlines = this.doLayering(baseImage, layerImage, baseImageScanlines, layerImageScanlines); PngFilterType filterType = PngFilterType.NONE; this.pngFilterHandler.applyFiltering(filterType, newImageScanlines, layerImage.getSampleBitCount()); byte[] imageResult = this.pngCompressionHandler.deflate(this.serialize(newImageScanlines), compressionLevel, concurrent); PngChunk imageChunk = new PngChunk(PngChunk.IMAGE_DATA.getBytes(), imageResult); result.addChunk(imageChunk); this.processTailChunks(result, itBaseChunks, lastBaseChunk); long time = System.currentTimeMillis() - start; this.log.debug("Layered in %d milliseconds", time); return result; } /* */ private List<byte[]> getScanlines(PngImage image, byte[] inflatedImageData) { int scanlineLength = Double.valueOf(Math.ceil(Long.valueOf(image.getWidth() * image.getSampleBitCount()) / 8F)).intValue() + 1; List<byte[]> originalScanlines = (image.getInterlace() == 1) ? this.pngInterlaceHander.deInterlace((int)image.getWidth(), (int)image.getHeight(), image.getSampleBitCount(), inflatedImageData) : this.getScanlines(inflatedImageData, image.getSampleBitCount(), scanlineLength, image.getHeight()); return originalScanlines; } /* */ private PngChunk processHeadChunks(PngImage result, Iterator<PngChunk> itChunks) throws IOException { PngChunk chunk = null; while (itChunks.hasNext()) { chunk = itChunks.next(); if (PngChunk.IMAGE_DATA.equals(chunk.getTypeString())) { break; } if (chunk.isRequired()) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(chunk.getLength()); DataOutputStream data = new DataOutputStream(bytes); data.write(chunk.getData()); data.close(); PngChunk newChunk = new PngChunk(chunk.getType(), bytes.toByteArray()); if (PngChunk.IMAGE_HEADER.equals(chunk.getTypeString())) { newChunk.setInterlace((byte)0); } result.addChunk(newChunk); } } return chunk; } /* */ private PngChunk processTailChunks(PngImage result, Iterator<PngChunk> itBaseChunks, PngChunk lastBaseChunk) throws IOException { while (lastBaseChunk != null) { if (lastBaseChunk.isCritical()) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(lastBaseChunk.getLength()); DataOutputStream data = new DataOutputStream(bytes); data.write(lastBaseChunk.getData()); data.close(); PngChunk newChunk = new PngChunk(lastBaseChunk.getType(), bytes.toByteArray()); result.addChunk(newChunk); } lastBaseChunk = itBaseChunks.hasNext() ? itBaseChunks.next() : null; } return lastBaseChunk; } /* */ private byte[] getInflatedImageData(PngChunk chunk, Iterator<PngChunk> itChunks) throws IOException { ByteArrayOutputStream imageBytes = new ByteArrayOutputStream(chunk == null ? 0 : chunk.getLength()); DataOutputStream imageData = new DataOutputStream(imageBytes); while (chunk != null) { if (PngChunk.IMAGE_DATA.equals(chunk.getTypeString())) { imageData.write(chunk.getData()); } else { break; } chunk = itChunks.hasNext() ? itChunks.next() : null; } imageData.close(); return this.pngCompressionHandler.inflate(imageBytes); } /* */ private List<byte[]> getScanlines(byte[] inflatedImageData, int sampleBitCount, int rowLength, long height) { this.log.debug("Getting scanlines"); List<byte[]> rows = new ArrayList<byte[]>(Math.max((int)height, 0)); byte[] previousRow = new byte[rowLength]; for (int i = 0; i < height; i++) { int offset = i * rowLength; byte[] row = new byte[rowLength]; System.arraycopy(inflatedImageData, offset, row, 0, rowLength); try { this.pngFilterHandler.deFilter(row, previousRow, sampleBitCount); rows.add(row); previousRow = row.clone(); } catch (PngException e) { this.log.error("Error: %s", e.getMessage()); } } return rows; } /* */ private byte[] serialize(List<byte[]> scanlines) { int scanlineLength = scanlines.get(0).length; byte[] imageData = new byte[scanlineLength * scanlines.size()]; for (int i = 0; i < scanlines.size(); i++) { int offset = i * scanlineLength; byte[] scanline = scanlines.get(i); System.arraycopy(scanline, 0, imageData, offset, scanlineLength); } return imageData; } /* */ private List<byte[]> doLayering(PngImage baseImage, PngImage layerImage, List<byte[]> baseRows, List<byte[]> layerRows) throws IOException { List<byte[]> result = new ArrayList<byte[]>(baseRows.size()); PngImageType baseImageType = PngImageType.forColorType(baseImage.getColorType()); PngImageType layerImageType = PngImageType.forColorType(layerImage.getColorType()); int sampleSize = baseImage.getSampleBitCount(); for (int rowIndex = 0; rowIndex < baseRows.size(); rowIndex++) { byte[] baseRow = baseRows.get(rowIndex); byte[] layerRow = layerRows.get(rowIndex); int sampleCount = ((baseRow.length - 1) * 8) / sampleSize; ByteArrayInputStream baseIn = new ByteArrayInputStream(baseRow); DataInputStream baseDin = new DataInputStream(baseIn); int filterByte = baseDin.readUnsignedByte(); ByteArrayInputStream layerIn = new ByteArrayInputStream(layerRow); DataInputStream layerDin = new DataInputStream(layerIn); layerDin.readUnsignedByte(); // skip filter byte ByteArrayOutputStream outs = new ByteArrayOutputStream(baseRow.length); DataOutputStream dos = new DataOutputStream(outs); dos.writeByte(filterByte); for (int i = 0; i < sampleCount; i++) { // Zero alpha represents a completely transparent pixel, // maximum alpha represents a completely opaque pixel. int baseRed, baseGreen, baseBlue, baseAlpha = 0; int layerRed, layerGreen, layerBlue, layerAlpha = 0; if (baseImage.getBitDepth() == 8) { baseRed = baseDin.readUnsignedByte(); baseGreen = baseDin.readUnsignedByte(); baseBlue = baseDin.readUnsignedByte(); } else { baseRed = baseDin.readUnsignedShort(); baseGreen = baseDin.readUnsignedShort(); baseBlue = baseDin.readUnsignedShort(); } if (baseImageType == PngImageType.TRUECOLOR_ALPHA) { baseAlpha = (baseImage.getBitDepth() == 8) ? baseDin.readUnsignedByte() : baseDin.readUnsignedShort(); } else { baseAlpha = 255; } if (layerImage.getBitDepth() == 8) { layerRed = layerDin.readUnsignedByte(); layerGreen = layerDin.readUnsignedByte(); layerBlue = layerDin.readUnsignedByte(); } else { layerRed = layerDin.readUnsignedShort(); layerGreen = layerDin.readUnsignedShort(); layerBlue = layerDin.readUnsignedShort(); } if (layerImageType == PngImageType.TRUECOLOR_ALPHA) { layerAlpha = (layerImage.getBitDepth() == 8) ? layerDin.readUnsignedByte() : layerDin.readUnsignedShort(); } if (layerAlpha == 0) { dos.writeByte(baseRed); dos.writeByte(baseGreen); dos.writeByte(baseBlue); dos.writeByte(baseAlpha); } else { dos.writeByte((baseRed * (255 - layerAlpha) + layerRed * layerAlpha) / 255); dos.writeByte((baseGreen * (255 - layerAlpha) + layerGreen * layerAlpha) / 255); dos.writeByte((baseBlue * (255 - layerAlpha) + layerBlue * layerAlpha) / 255); dos.writeByte(255); } } dos.flush(); result.add(outs.toByteArray()); } return result; } }
Java
package com.googlecode.pngtastic.core.processing; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * Apply PNG compression and decompression. Implies zlib format, aka LZ77. * * @author rayvanderborght */ public interface PngCompressionHandler { /** * Inflate (decompress) the compressed image data * * @param deflatedImageData A stream containing the compressed image data * @return A byte array containing the uncompressed data */ public byte[] inflate(ByteArrayOutputStream deflatedImageData) throws IOException; /** * Deflate (compress) the inflated data using the given compression level. * If compressionLevel is null then do a brute force trial of all * compression levels to find the best one. * * @param inflatedImageData A byte array containing the uncompressed image data * @param compressionLevel The compression level to use * @param concurrent Whether to test scanlines for best compressing filter type * concurrently. Should be set to true for performance, or false in * environments like google app engine that don't allow thread creation. * @return A byte array containing the compressed image data */ public byte[] deflate(byte[] inflatedImageData, Integer compressionLevel, boolean concurrent) throws IOException; }
Java
package com.googlecode.pngtastic.core.processing; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.zip.InflaterInputStream; import com.googlecode.pngtastic.core.Logger; /** * Implements PNG compression and decompression * Uses zopfli to compress: https://code.google.com/p/zopfli/ * * @author rayvanderborght */ public class ZopfliCompressionHandler implements PngCompressionHandler { private final Logger log; private final String compressor; // e.g. /Users/ray/projects/pngtastic/lib/zopfli public ZopfliCompressionHandler(Logger log, String compressor) { this.log = log; this.compressor = compressor; } /** * {@inheritDoc} */ @Override public byte[] inflate(ByteArrayOutputStream imageBytes) throws IOException { InflaterInputStream inflater = new InflaterInputStream(new ByteArrayInputStream(imageBytes.toByteArray())); ByteArrayOutputStream inflatedOut = new ByteArrayOutputStream(); int readLength; byte[] block = new byte[8192]; while ((readLength = inflater.read(block)) != -1) { inflatedOut.write(block, 0, readLength); } byte[] inflatedImageData = inflatedOut.toByteArray(); return inflatedImageData; } /** * {@inheritDoc} */ @Override public byte[] deflate(byte[] inflatedImageData, Integer compressionLevel, boolean concurrent) throws IOException { List<byte[]> results = deflateImageDataSerially(inflatedImageData, compressionLevel); byte[] result = null; for (int i = 0; i < results.size(); i++) { byte[] data = results.get(i); if (result == null || (data.length < result.length)) { result = data; } } this.log.debug("Image bytes=%d", (result == null) ? -1 : result.length); return result; } /* */ private List<byte[]> deflateImageDataSerially(byte[] inflatedImageData, Integer compressionLevel) { List<byte[]> results = new ArrayList<byte[]>(); try { results.add(deflateImageData(inflatedImageData, compressionLevel)); } catch (Throwable e) { log.error("Uncaught Exception: %s", e.getMessage()); } return results; } /* */ private byte[] deflateImageData(byte[] inflatedImageData, Integer compressionLevel) throws IOException { byte[] result = deflate(inflatedImageData).toByteArray(); log.debug("Compression strategy: zopfli, compression level=%d, bytes=%d", compressionLevel, (result == null) ? -1 : result.length); return result; } /* */ private ByteArrayOutputStream deflate(byte[] inflatedImageData) throws IOException { File imageData = null; try { imageData = File.createTempFile("imagedata", ".zopfli"); writeFileOutputStream(imageData, inflatedImageData); ProcessBuilder p = new ProcessBuilder(compressor, "-c", "--zlib", imageData.getCanonicalPath()); Process process = p.start(); ByteArrayOutputStream deflatedOut = new ByteArrayOutputStream(); int byteCount; byte[] data = new byte[8192]; InputStream s = process.getInputStream(); while ((byteCount = s.read(data, 0, data.length)) != -1) { deflatedOut.write(data, 0, byteCount); } deflatedOut.flush(); return deflatedOut; } finally { if (imageData != null) { imageData.delete(); } } } private FileOutputStream writeFileOutputStream(File out, byte[] bytes) throws IOException { FileOutputStream outs = null; try { outs = new FileOutputStream(out); outs.write(bytes); } finally { if (outs != null) { outs.close(); } } return outs; } }
Java
package com.googlecode.pngtastic.core.processing; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectStreamClass; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.CharBuffer; /** * <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 * things as first gzipping the bytes before encoding them, not inserting linefeeds, * and encoding using the URL-safe and Ordered dialects.</p> * * <p>Note, according to <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>, * Section 2.1, implementations should not add line feeds unless explicitly told * 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 * might make a call like this:</p> * * <code>String encoded = Base64.encodeBytes(mybytes, Base64.GZIP | Base64.DO_BREAK_LINES);</code> * <p>to compress the data before encoding it and then making the output have newline characters.</p> * <p>Also...</p> * <code>String encoded = Base64.encodeBytes( crazyString.getBytes() );</code> * <p> * Change Log: * </p> * <ul> * <li>v2.3.7 - Fixed subtle bug when base 64 input stream contained the * value 01111111, which is an invalid base 64 character but should not * throw an ArrayIndexOutOfBoundsException either. Led to discovery of * mishandling (or potential for better handling) of other bad input * characters. You should now get an IOException if you try decoding * something that has bad characters in it.</li> * <li>v2.3.6 - Fixed bug when breaking lines and the final byte of the encoded * string ended in the last column; the buffer was not properly shrunk and * contained an extra (null) byte that made it into the string.</li> * <li>v2.3.5 - Fixed bug in {@link #encodeFromFile} where estimated buffer size * was wrong for files of size 31, 34, and 37 bytes.</li> * <li>v2.3.4 - Fixed bug when working with gzipped streams whereby flushing * the Base64.OutputStream closed the Base64 encoding (by padding with equals * signs) too soon. Also added an option to suppress the automatic decoding * of gzipped streams. Also added experimental support for specifying a * class loader when using the * {@link #decodeToObject(java.lang.String, int, java.lang.ClassLoader)} * method.</li> * <li>v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java * footprint with its CharEncoders and so forth. Fixed some javadocs that were * inconsistent. Removed imports and specified things like java.io.IOException * explicitly inline.</li> * <li>v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the * final encoded data will be so that the code doesn't have to create two output * arrays: an oversized initial one and then a final, exact-sized one. Big win * when using the {@link #encodeBytesToBytes(byte[])} family of methods (and not * using the gzip options which uses a different mechanism with streams and stuff).</li> * <li>v2.3.1 - Added {@link #encodeBytesToBytes(byte[], int, int, int)} and some * similar helper methods to be more efficient with memory by not returning a * String but just a byte array.</li> * <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 * instead of returning null values or something similar. Here are some changes * that may affect you: * <ul> * <li><em>Does not break lines, by default.</em> This is to keep in compliance with * <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>.</li> * <li><em>Throws exceptions instead of returning null values.</em> Because some operations * (especially those that may permit the GZIP option) use IO streams, there * is a possiblity of an java.io.IOException being thrown. After some discussion and * thought, I've changed the behavior of the methods to throw java.io.IOExceptions * rather than return null if ever there's an error. I think this is more * appropriate, though it will require some changes to your code. Sorry, * it should have been done this way to begin with.</li> * <li><em>Removed all references to System.out, System.err, and the like.</em> * Shame on me. All I can say is sorry they were ever there.</li> * <li><em>Throws NullPointerExceptions and IllegalArgumentExceptions</em> as needed * such as when passed arrays are null or offsets are invalid.</li> * <li>Cleaned up as much javadoc as I could to avoid any javadoc warnings. * This was especially annoying before for people who were thorough in their * own projects and then had gobs of javadoc warnings on this file.</li> * </ul> * <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug * when using very small files (~&lt; 40 bytes).</li> * <li>v2.2 - Added some helper methods for encoding/decoding directly from * one file to the next. Also added a main() method to support command line * encoding/decoding from one file to the next. Also added these Base64 dialects: * <ol> * <li>The default is RFC3548 format.</li> * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates * URL and file name friendly format as described in Section 4 of RFC3548. * http://www.faqs.org/rfcs/rfc3548.html</li> * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates * URL and file name friendly format that preserves lexical ordering as described * in http://www.faqs.org/qa/rfcc-1940.html</li> * </ol> * 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. * 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 - 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> * <li>v1.4 - Added helper methods to read/write files.</li> * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li> * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream * where last buffer being read, if not completely full, was not returned.</li> * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li> * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li> * </ul> * * <p> * I am placing this code in the Public Domain. Do with it as you will. * This software comes with no guarantees or warranties but with * plenty of well-wishing instead! * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a> * periodically to check for updates or to contribute improvements. * </p> * * @author Robert Harder * @author rob@iharder.net * @version 2.3.7 */ public class Base64 { /** 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: * <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, * or at the very least should not be called Base64 without also specifying that is * was encoded using the URL- and Filename-safe dialect. */ public final static int URL_SAFE = 16; /** * Encode using the special "ordered" dialect of Base64 described here: * <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; /** 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 /** 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)'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)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (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. */ private final static byte[] _STANDARD_DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9,-9,-9, // Decimal 44 - 46 63, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 127 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -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 }; /** * 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)'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)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (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. */ private final static byte[] _URL_SAFE_DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 -9, // Plus sign at decimal 43 -9, // Decimal 44 62, // Minus sign at decimal 45 -9, // Decimal 46 -9, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9, // Decimal 91 - 94 63, // Underscore at decimal 95 -9, // Decimal 96 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 127 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -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 }; /** * I don't get the point of this technique, but someone requested it, * and it is described here: * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>. */ private final static byte[] _ORDERED_ALPHABET = { (byte)'-', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (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)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'_', (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)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z' }; /** * Used in decoding the "ordered" dialect of Base64. */ private final static byte[] _ORDERED_DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 -9, // Plus sign at decimal 43 -9, // Decimal 44 0, // Minus sign at decimal 45 -9, // Decimal 46 -9, // Slash at decimal 47 1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M' 24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z' -9,-9,-9,-9, // Decimal 91 - 94 37, // Underscore at decimal 95 -9, // Decimal 96 38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm' 51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z' -9,-9,-9,-9,-9, // Decimal 123 - 127 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -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 }; /** * Returns one of the _SOMETHING_ALPHABET byte arrays depending on * the options specified. * It's possible, though silly, to specify ORDERED <b>and</b> URLSAFE * in which case one of them will be picked, though there is * no guarantee as to which one will be picked. */ private final static byte[] getAlphabet(int options) { if ((options & URL_SAFE) == URL_SAFE) { return _URL_SAFE_ALPHABET; } else if ((options & ORDERED) == ORDERED) { return _ORDERED_ALPHABET; } else { return _STANDARD_ALPHABET; } } // end getAlphabet /** * Returns one of the _SOMETHING_DECODABET byte arrays depending on * the options specified. * It's possible, though silly, to specify ORDERED and URL_SAFE * in which case one of them will be picked, though there is * no guarantee as to which one will be picked. */ private final static byte[] getDecodabet(int options) { if ((options & URL_SAFE) == URL_SAFE) { return _URL_SAFE_DECODABET; } else if ((options & ORDERED) == ORDERED) { return _ORDERED_DECODABET; } else { return _STANDARD_DECODABET; } } /** Defeats instantiation. */ private Base64() { } /** * Encodes up to the first three bytes of array <var>threeBytes</var> * and returns a four-byte array in Base64 notation. * The actual number of significant bytes in your array is given by <var>numSigBytes</var>. * The array <var>threeBytes</var> needs only be as big as <var>numSigBytes</var>. * Code can reuse a byte array by passing a four-byte array as <var>b4</var>. * * @param b4 A reusable byte array to reduce array instantiation * @param threeBytes the array to convert * @param numSigBytes the number of significant bytes in your array * @return four byte array in Base64 notation. * @since 1.5.1 */ private static byte[] encode3to4(byte[] b4, byte[] threeBytes, int numSigBytes, int options) { encode3to4(threeBytes, 0, numSigBytes, b4, 0, options); return b4; } /** * <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 <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 the <var>source</var> array or <var>destOffset</var> + 4 for * the <var>destination</var> array. * The actual number of significant bytes in your array is given by <var>numSigBytes</var>.</p> * <p>This is the lowest level of the encoding methods with all possible parameters.</p> * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset, int options) { 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 // when Java treats a value as negative that is cast from a byte to an int. int inBuff = (numSigBytes > 0 ? ((source[srcOffset ] << 24) >>> 8) : 0) | (numSigBytes > 1 ? ((source[srcOffset + 1 ] << 24) >>> 16) : 0) | (numSigBytes > 2 ? ((source[srcOffset + 2 ] << 24) >>> 24) : 0); switch (numSigBytes) { case 3: destination[destOffset ] = ALPHABET[(inBuff >>> 18) ]; destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; 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; } } /** * Performs Base64 encoding on the <code>raw</code> ByteBuffer, writing it to the * <code>encoded</code> ByteBuffer. This is an experimental feature. Currently it does not * pass along any options (such as {@link #DO_BREAK_LINES} or {@link #GZIP}. * * @param raw input buffer * @param encoded output buffer * @since 2.3 */ public static void encode(ByteBuffer raw, ByteBuffer encoded) { byte[] raw3 = new byte[3]; byte[] enc4 = new byte[4]; while (raw.hasRemaining()) { int rem = Math.min(3,raw.remaining()); raw.get(raw3,0,rem); Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS); encoded.put(enc4); } } /** * Performs Base64 encoding on the <code>raw</code> ByteBuffer, writing it to the * <code>encoded</code> CharBuffer. This is an experimental feature. Currently it does not * pass along any options (such as {@link #DO_BREAK_LINES} or {@link #GZIP}. * * @param raw input buffer * @param encoded output buffer * @since 2.3 */ public static void encode(ByteBuffer raw, CharBuffer encoded) { byte[] raw3 = new byte[3]; byte[] enc4 = new byte[4]; while (raw.hasRemaining()) { int rem = Math.min(3,raw.remaining()); raw.get(raw3, 0, rem); Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS); for (int i = 0; i < 4; i++) { encoded.put((char) (enc4[i] & 0xFF)); } } } /** * 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. * * @param serializableObject The object to encode * @return The Base64-encoded object * @throws java.io.IOException if there is an error * @throws NullPointerException if serializedObject is null * @since 1.4 */ public static String encodeObject(Serializable serializableObject) throws IOException { return encodeObject(serializableObject, NO_OPTIONS); } /** * 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> * GZIP: gzip-compresses object before encoding it. * DO_BREAK_LINES: break lines at 76 characters * </pre> * <p> * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or * <p> * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code> * * @param serializableObject The object to encode * @param options Specified options * @return The Base64-encoded object * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @since 2.0 */ public static String encodeObject(Serializable serializableObject, int options) throws IOException { if (serializableObject == null){ throw new NullPointerException("Cannot serialize a null object."); } // Streams 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(); b64os = new Base64.OutputStream(baos, ENCODE | options); if ((options & GZIP) != 0) { // Gzip gzos = new java.util.zip.GZIPOutputStream(b64os); oos = new java.io.ObjectOutputStream(gzos); } else { // Not gzipped oos = new java.io.ObjectOutputStream(b64os); } oos.writeObject(serializableObject); } catch (IOException e) { // Catch it and then throw it immediately so that the finally{} block is called for cleanup. throw e; } finally { try { if (oos != null) { oos.close(); } } catch (Exception e) { } try { if (gzos != null) { gzos.close(); } } catch (Exception e) { } try { if (b64os != null) { b64os.close(); } } catch (Exception e) { } try { if (baos != null) { baos.close(); } } catch (Exception e) { } } // Return value according to relevant encoding. try { return (baos == null) ? null : new String(baos.toByteArray(), PREFERRED_ENCODING); } catch (UnsupportedEncodingException e) { // Fall back to some Java default return new String(baos.toByteArray()); } } /** * 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 * @since 1.4 */ public static String encodeBytes( byte[] source ) { // Since we're not going to have the GZIP encoding turned on, we're not going to have an // IOException thrown, so we should not force the user to have to catch it. String encoded = null; try { encoded = encodeBytes(source, 0, source.length, NO_OPTIONS); } catch (java.io.IOException ex) { assert false : ex.getMessage(); } assert encoded != null; return encoded; } /** * Encodes a byte array into Base64 notation. * <p> * Example options:<pre> * GZIP: gzip-compresses object before encoding it. * DO_BREAK_LINES: break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes(myData, Base64.GZIP)</code> or * <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 * @return The Base64-encoded data as a String * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @throws NullPointerException if source array is null * @since 2.0 */ public static String encodeBytes(byte[] source, int options) throws IOException { return encodeBytes(source, 0, source.length, options); } /** * 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 * @param len Length of data to convert * @return The Base64-encoded data as a String * @throws NullPointerException if source array is null * @throws IllegalArgumentException if source array, offset, or length are invalid * @since 1.4 */ public static String encodeBytes(byte[] source, int off, int len) { // Since we're not going to have the GZIP encoding turned on, we're not going to have an // IOException thrown, so we should not force the user to have to catch it. String encoded = null; try { encoded = encodeBytes(source, off, len, NO_OPTIONS); } catch (IOException ex) { assert false : ex.getMessage(); } assert encoded != null; return encoded; } /** * Encodes a byte array into Base64 notation. * <p> * Example options:<pre> * GZIP: gzip-compresses object before encoding it. * DO_BREAK_LINES: break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes(myData, Base64.GZIP)</code> or * <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 * 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 * @param len Length of data to convert * @param options Specified options * @return The Base64-encoded data as a String * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @throws NullPointerException if source array is null * @throws IllegalArgumentException if source array, offset, or length are invalid * @since 2.0 */ public static String encodeBytes(byte[] source, int off, int len, int options) throws IOException { byte[] encoded = encodeBytesToBytes(source, off, len, options); // Return value according to relevant encoding. try { return new String(encoded, PREFERRED_ENCODING); } catch (UnsupportedEncodingException uue) { return new String(encoded); } } /** * Similar to {@link #encodeBytes(byte[])} but returns a byte array instead of instantiating a * String. This is more efficient if you're working with I/O streams and have large data sets * to encode. * * @param source The data to convert * @return The Base64-encoded data as a byte[] (of ASCII characters) * @throws NullPointerException if source array is null * @since 2.3.1 */ public static byte[] encodeBytesToBytes(byte[] source) { byte[] encoded = null; try { encoded = encodeBytesToBytes(source, 0, source.length, Base64.NO_OPTIONS); } catch(IOException ex) { assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); } return encoded; } /** * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns a byte array instead of * instantiating a String. This is more efficient if you're working with I/O streams and have * large data sets to encode. * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @param options Specified options * @return The Base64-encoded data as a String * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @throws NullPointerException if source array is null * @throws IllegalArgumentException if source array, offset, or length are invalid * @since 2.3.1 */ public static byte[] encodeBytesToBytes(byte[] source, int off, int len, int options) throws IOException { if (source == null) { throw new NullPointerException("Cannot serialize a null array."); } if (off < 0) { throw new IllegalArgumentException("Cannot have negative offset: " + off); } if (len < 0) { throw new IllegalArgumentException("Cannot have length offset: " + len); } if (off + len > source.length) { throw new IllegalArgumentException(String.format( "Cannot have offset of %d and length of %d with array of length %d", off, len, source.length)); } // Compress? if ((options & GZIP) != 0) { ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; try { // GZip -> Base64 -> ByteArray baos = new ByteArrayOutputStream(); b64os = new Base64.OutputStream(baos, ENCODE | options); gzos = new java.util.zip.GZIPOutputStream(b64os); gzos.write(source, off, len); gzos.close(); } catch (IOException e) { // Catch it and then throw it immediately so that the finally{} block is called for cleanup. throw e; } finally { try { if (gzos != null) { gzos.close(); } } catch (Exception e) { } try { if (b64os != null) { b64os.close(); } } catch (Exception e) { } try { if (baos != null) { baos.close(); } } catch (Exception e) { } } return (baos == null) ? null : baos.toByteArray(); } else { // Else, don't compress. Better not to use streams at all then. boolean breakLines = (options & DO_BREAK_LINES) != 0; //int len43 = len * 4 / 3; //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines // Try to determine more precisely how big the array needs to be. // If we get it right, we don't have to do an array copy, and // we save a bunch of memory. int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0); // Bytes needed for actual encoding if (breakLines) { encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters } byte[] outBuff = new byte[encLen]; int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for (; d < len2; d+=3, e+=4) { encode3to4(source, d + off, 3, outBuff, e, options); lineLength += 4; if (breakLines && lineLength >= MAX_LINE_LENGTH) { outBuff[e + 4] = NEW_LINE; e++; lineLength = 0; } } if (d < len) { encode3to4(source, d+off, len - d, outBuff, e, options); e += 4; } // Only resize array if we didn't guess it right. if (e <= outBuff.length - 1) { // If breaking lines and the last byte falls right at the line length // (76 bytes per line), there will be one extra byte, and the array will need to be resized. // Not too bad of an estimate on array size, I'd say. byte[] finalOut = new byte[e]; System.arraycopy(outBuff, 0, finalOut, 0, e); return finalOut; } else { return outBuff; } } } /** * 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 <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 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 * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param options alphabet type is pulled from this (standard, url-safe, ordered) * @return the number of decoded bytes converted * @throws NullPointerException if source or destination arrays are null * @throws IllegalArgumentException if srcOffset or destOffset are invalid * or there is not enough room in the array. * @since 1.3 */ 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."); } if (destination == null) { throw new NullPointerException("Destination array was null."); } if (srcOffset < 0 || srcOffset + 3 >= source.length) { throw new IllegalArgumentException(String.format( "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset)); } if (destOffset < 0 || destOffset +2 >= destination.length) { throw new IllegalArgumentException(String.format( "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset)); } 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. //int outBuff = ((DECODABET[source[srcOffset ]] << 24 ) >>> 6) // | ((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; } else if (source[srcOffset + 3] == EQUALS_SIGN) { // Example: DkL= // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ((DECODABET[source[srcOffset ]] << 24) >>> 6) // | ((DECODABET[source[srcOffset + 1]] << 24) >>> 12) // | ((DECODABET[source[srcOffset + 2]] << 24) >>> 18); 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; } else { // Example: DkLE // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ((DECODABET[source[srcOffset ]] << 24) >>> 6) // | ((DECODABET[source[srcOffset + 1]] << 24) >>> 12) // | ((DECODABET[source[srcOffset + 2]] << 24) >>> 18) // | ((DECODABET[source[srcOffset + 3]] << 24) >>> 24); int outBuff = ((DECODABET[source[srcOffset ]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12) | ((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 ); return 3; } } /** * Low-level access to decoding ASCII characters in the form of a byte array. * <strong>Ignores GUNZIP option, if it's set.</strong> This is not generally a recommended * method, although it is used internally as part of the decoding process. Special case: * if len = 0, an empty array is returned. Still, if you need more speed and reduced memory * footprint (and aren't gzipping), consider this method. * * @param source The Base64 encoded data * @return decoded data * @since 2.3.1 */ public static byte[] decode(byte[] source) throws IOException { byte[] decoded = null; // try { decoded = decode(source, 0, source.length, Base64.NO_OPTIONS); // } catch (IOException ex) { // assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); // } return decoded; } /** * Low-level access to decoding ASCII characters in the form of a byte array. * <strong>Ignores GUNZIP option, if it's set.</strong> This is not generally a recommended * method, although it is used internally as part of the decoding process. Special case: * if len = 0, an empty array is returned. Still, if you need more speed and reduced memory * footprint (and aren't gzipping), consider this method. * * @param source The Base64 encoded data * @param off The offset of where to begin decoding * @param len The length of characters to decode * @param options Can specify options such as alphabet type to use * @return decoded data * @throws IOException If bogus characters exist in source data * @since 1.3 */ public static byte[] decode(byte[] source, int off, int len, int options) throws IOException { // Lots of error checking and exception throwing if (source == null) { throw new NullPointerException("Cannot decode null source array."); } if (off < 0 || off + len > source.length) { throw new IllegalArgumentException(String.format( "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len)); } if (len == 0) { return new byte[0]; } else if (len < 4) { throw new IllegalArgumentException( "Base64-encoded string must have at least four characters, but length specified was " + len); } 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 sbiDecode = 0; // Special value from DECODABET for (i = off; i < off+len; i++) { // Loop through source sbiDecode = DECODABET[source[i]&0xFF ]; // 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. if (sbiDecode >= WHITE_SPACE_ENC) { if (sbiDecode >= EQUALS_SIGN_ENC) { b4[b4Posn++] = source[i]; // Save non-whitespace 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 (source[i] == EQUALS_SIGN) { break; } } } // end if: equals sign or better } else { // There's a bad input character in the Base64 stream. throw new IOException(String.format( "Bad Base64 input character decimal %d in array position %d", (source[i]) &0xFF, i)); } } byte[] out = new byte[outBuffPosn]; System.arraycopy(outBuff, 0, out, 0, outBuffPosn); return out; } /** * Decodes data from Base64 notation, automatically detecting gzip-compressed data and decompressing it. * * @param s the string to decode * @return the decoded data * @throws IOException If there is a problem * @since 1.4 */ public static byte[] decode(String s) throws IOException { return decode(s, NO_OPTIONS); } /** * Decodes data from Base64 notation, automatically detecting gzip-compressed data and decompressing it. * * @param s the string to decode * @param options encode options such as URL_SAFE * @return the decoded data * @throws IOException if there is an error * @throws NullPointerException if <tt>s</tt> is null * @since 1.4 */ public static byte[] decode(String s, int options) throws IOException { if (s == null) { throw new NullPointerException("Input string was null."); } byte[] bytes; try { bytes = s.getBytes(PREFERRED_ENCODING); } catch (UnsupportedEncodingException e) { bytes = s.getBytes(); } // 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 = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) { ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new ByteArrayOutputStream(); bais = new ByteArrayInputStream(bytes); gzis = new java.util.zip.GZIPInputStream(bais); while ((length = gzis.read(buffer)) >= 0) { baos.write(buffer,0,length); } // No error? Get new bytes. bytes = baos.toByteArray(); } catch (IOException e) { e.printStackTrace(); // Just return originally-decoded bytes } finally { try { if (baos != null) { baos.close(); } } catch (Exception e) { } try { if (gzis != null) { gzis.close(); } } catch (Exception e) { } try { if (bais != null) { bais.close(); } } catch (Exception e) { } } } } return bytes; } /** * Attempts to decode Base64 data and deserialize a Java * Object within. Returns <tt>null</tt> if there was an error. * * @param encodedObject The Base64 data to decode * @return The decoded and deserialized object * @throws NullPointerException if encodedObject is null * @throws IOException if there is a general error * @throws ClassNotFoundException if the decoded object is of a class that cannot be found by the JVM * @since 1.5 */ public static Object decodeToObject(String encodedObject) throws IOException, ClassNotFoundException { return decodeToObject(encodedObject, NO_OPTIONS, null); } /** * Attempts to decode Base64 data and deserialize a Java Object within. Returns <tt>null</tt> * if there was an error. If <tt>loader</tt> is not null, it will be the class loader * used when deserializing. * * @param encodedObject The Base64 data to decode * @param options Various parameters related to decoding * @param loader Optional class loader to use in deserializing classes. * @return The decoded and deserialized object * @throws NullPointerException if encodedObject is null * @throws java.io.IOException if there is a general error * @throws ClassNotFoundException if the decoded object is of a class that cannot be found by the JVM * @since 2.3.4 */ public static Object decodeToObject(String encodedObject, int options, final ClassLoader loader) throws IOException, ClassNotFoundException { // Decode and gunzip if necessary byte[] objBytes = decode(encodedObject, options); ByteArrayInputStream bais = null; ObjectInputStream ois = null; Object obj = null; try { bais = new ByteArrayInputStream(objBytes); // If no custom class loader is provided, use Java's builtin OIS. if (loader == null) { ois = new ObjectInputStream(bais); } else { // Else make a customized object input stream that uses the provided class loader. ois = new ObjectInputStream(bais) { @Override public Class<?> resolveClass(ObjectStreamClass streamClass) throws IOException, ClassNotFoundException { Class c = Class.forName(streamClass.getName(), false, loader); if (c == null) { return super.resolveClass(streamClass); } else { return c; // Class loader knows of this class. } } }; } obj = ois.readObject(); } catch (IOException e) { throw e; // Catch and throw in order to execute finally{} } catch (ClassNotFoundException e) { throw e; // Catch and throw in order to execute finally{} } finally { try { if (bais != null) { bais.close(); } } catch (Exception e) { } try { if (ois != null) { ois.close(); } } catch (Exception e) { } } return obj; } /** * Convenience method for encoding data to a file. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param dataToEncode byte array of data to encode in base64 form * @param filename Filename for saving encoded data * @throws IOException if there is an error * @throws NullPointerException if dataToEncode is null * @since 2.1 */ public static void encodeToFile(byte[] dataToEncode, String filename) throws IOException { if (dataToEncode == null) { throw new NullPointerException("Data to encode was null."); } Base64.OutputStream bos = null; try { bos = new Base64.OutputStream(new java.io.FileOutputStream(filename), Base64.ENCODE); bos.write(dataToEncode); } catch (IOException e) { throw e; // Catch and throw to execute finally{} block } finally { try { if (bos != null) { bos.close(); } } catch (Exception e) { } } } /** * Convenience method for decoding data to a file. * * <p>As of v 2.3, if there is a error, the method will throw an IOException. * <b>This is new to v2.3!</b> In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param dataToDecode Base64-encoded data as a string * @param filename Filename for saving decoded data * @throws java.io.IOException if there is an error * @since 2.1 */ public static void decodeToFile(String dataToDecode, String filename) throws IOException { Base64.OutputStream bos = null; try { bos = new Base64.OutputStream(new FileOutputStream(filename), Base64.DECODE); bos.write(dataToDecode.getBytes(PREFERRED_ENCODING)); } catch (IOException e) { throw e; // Catch and throw to execute finally{} block } finally { try { if (bos != null) { bos.close(); } } catch(Exception e) { } } } /** * Convenience method for reading a base64-encoded file and decoding it. * * <p>As of v 2.3, if there is a error, the method will throw an IOException. * <b>This is new to v2.3!</b> In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param filename Filename for reading encoded data * @return decoded byte array * @throws java.io.IOException if there is an error * @since 2.1 */ public static byte[] decodeFromFile(String filename) throws IOException { byte[] decodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables File file = new File(filename); byte[] buffer = null; int length = 0; int numBytes = 0; // Check for size of file if (file.length() > Integer.MAX_VALUE) { throw new IOException("File is too big for this convenience method (" + file.length() + " bytes)."); } buffer = new byte[ (int)file.length() ]; // Open a stream bis = new Base64.InputStream(new BufferedInputStream(new FileInputStream(file)), Base64.DECODE); // Read until done while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { length += numBytes; } // Save in a variable to return decodedData = new byte[length]; System.arraycopy(buffer, 0, decodedData, 0, length); } catch (IOException e) { throw e; // Catch and release to execute finally{} } finally { try { if (bis != null) { bis.close(); } } catch (Exception e) { } } return decodedData; } /** * Convenience method for reading a binary file and base64-encoding it. * * <p>As of v 2.3, if there is a error, the method will throw an java.io.IOException. * <b>This is new to v2.3!</b> In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param filename Filename for reading binary data * @return base64-encoded string * @throws IOException if there is an error * @since 2.1 */ public static String encodeFromFile(String filename) throws IOException { String encodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables File file = new File(filename); byte[] buffer = new byte[Math.max((int) (file.length() * 1.4 + 1), 40)]; // Need max() for math on small files (v2.2.1); Need +1 for a few corner cases (v2.3.5) int length = 0; int numBytes = 0; // Open a stream bis = new Base64.InputStream(new BufferedInputStream(new FileInputStream(file)), Base64.ENCODE); // Read until done while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { length += numBytes; } // Save in a variable to return encodedData = new String(buffer, 0, length, Base64.PREFERRED_ENCODING); } catch (IOException e) { throw e; // Catch and release to execute finally{} } finally { try { if (bis != null) { bis.close(); } } catch (Exception e) { } } return encodedData; } /** * Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>. * * @param infile Input file * @param outfile Output file * @throws java.io.IOException if there is an error * @since 2.2 */ public static void encodeFileToFile(String infile, String outfile) throws IOException { String encoded = Base64.encodeFromFile(infile); java.io.OutputStream out = null; try { out = new java.io.BufferedOutputStream(new FileOutputStream(outfile)); out.write(encoded.getBytes("US-ASCII")); // Strict, 7-bit output. } catch (IOException e) { throw e; // Catch and release to execute finally{} } finally { try { if (out != null) { out.close(); } } catch (Exception ex) { } } } /** * Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>. * * @param infile Input file * @param outfile Output file * @throws java.io.IOException if there is an error * @since 2.2 */ public static void decodeFileToFile(String infile, String outfile) throws IOException { byte[] decoded = Base64.decodeFromFile(infile); java.io.OutputStream out = null; try{ out = new java.io.BufferedOutputStream(new FileOutputStream(outfile)); out.write(decoded); } catch (IOException e) { throw e; // Catch and release to execute finally{} } finally { try { if (out != null) { out.close(); } } catch (Exception ex) { } } } /** * A {@link Base64.InputStream} will read data from another <tt>java.io.InputStream</tt>, * given in the constructor, and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @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 private int bufferLength; // Length of buffer (3 or 4) private int numSigBytes; // Number of meaningful bytes in the buffer private int lineLength; 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. * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @since 1.3 */ public InputStream(InputStream in) { this(in, DECODE); } /** * Constructs a {@link Base64.InputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DO_BREAK_LINES: break lines at 76 characters (only meaningful when encoding)</i> * </pre> * <p> * Example: <code>new Base64.InputStream(in, Base64.DECODE)</code> * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @param options Specified options * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DO_BREAK_LINES * @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; this.encode = (options & ENCODE) > 0; this.bufferLength = encode ? 4 : 3; this.buffer = new byte[bufferLength]; this.position = -1; this.lineLength = 0; this.decodabet = getDecodabet(options); } /** * Reads enough of the input stream to convert to/from Base64 and returns the next byte. * * @return next byte * @since 1.3 */ @Override public int read() throws IOException { // Do we need to get data? if (position < 0) { if (encode) { byte[] b3 = new byte[3]; int numBinaryBytes = 0; for (int i = 0; i < 3; i++) { int b = in.read(); // If end of stream, b is -1. if (b >= 0) { b3[i] = (byte) b; numBinaryBytes++; } 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; numSigBytes = 4; } else { return -1; // Must be end of stream } } else { // Else decoding byte[] b4 = new byte[4]; int i = 0; for (i = 0; i < 4; i++) { // Read four "meaningful" bytes: 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 } b4[i] = (byte)b; } // end for: each needed input byte if( i == 4 ) { numSigBytes = decode4to3(b4, 0, buffer, 0, options); position = 0; } // end if: got four characters else if( i == 0 ){ return -1; } // end else if: also padded correctly else { // Must have broken out from above. throw new IOException("Improperly padded Base64 input."); } } } // Got data? if (position >= 0) { // End of relevant data? if (/*!encode &&*/ position >= numSigBytes) { return -1; } if (encode && breakLines && lineLength >= MAX_LINE_LENGTH) { lineLength = 0; return '\n'; } else { // This isn't important when decoding but throwing an extra "if" seems just as wasteful. lineLength++; int b = buffer[position++]; if (position >= bufferLength) { position = -1; } return b & 0xFF; // This is how you "cast" a byte that's intended to be unsigned. } } else { // Else error throw new IOException("Error in Base64 code reading stream."); } } /** * Calls {@link #read()} repeatedly until the end of stream * is reached or <var>len</var> bytes are read. * Returns number of bytes read into array or -1 if * end of stream is encountered. * * @param dest array to hold values * @param off offset for array * @param len max number of bytes to read into array * @return bytes read into array or -1 if end of stream is encountered. * @since 1.3 */ @Override public int read(byte[] dest, int off, int len) throws IOException { int i; int b; for (i = 0; i < len; i++) { b = read(); if (b >= 0) { dest[off + i] = (byte) b; } else if (i == 0) { return -1; } else { break; // Out of 'for' loop } } return i; } } /** * A {@link Base64.OutputStream} will write data to another <tt>java.io.OutputStream</tt>, * given in the constructor, and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class OutputStream extends FilterOutputStream { private boolean encode; private int position; private byte[] buffer; private int bufferLength; private int lineLength; private boolean breakLines; private byte[] b4; // Scratch used in a few places private boolean suspendEncoding; private int options; // Record for later private byte[] decodabet; // Local copies to avoid extra method calls /** * Constructs a {@link Base64.OutputStream} in ENCODE mode. * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @since 1.3 */ public OutputStream(java.io.OutputStream out) { this(out, ENCODE); } /** * Constructs a {@link Base64.OutputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DO_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding)</i> * </pre> * <p> * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code> * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @param options Specified options. * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DO_BREAK_LINES * @since 1.3 */ public OutputStream(java.io.OutputStream out, int options) { super( out ); this.breakLines = (options & DO_BREAK_LINES) != 0; this.encode = (options & ENCODE) != 0; this.bufferLength = encode ? 3 : 4; this.buffer = new byte[bufferLength]; this.position = 0; this.lineLength = 0; this.suspendEncoding = false; this.b4 = new byte[4]; this.options = options; this.decodabet = getDecodabet(options); } /** * Writes the byte to the output stream after converting to/from Base64 notation. * When encoding, bytes are buffered three at a time before the output stream actually * gets a write() call. When decoding, bytes are buffered four at a time. * * @param theByte the byte to write * @since 1.3 */ @Override public void write(int theByte) throws IOException { // Encoding suspended? if (suspendEncoding) { this.out.write(theByte); return; } // Encode? if (encode) { buffer[position++] = (byte) theByte; if (position >= bufferLength) { // Enough to encode. this.out.write(encode3to4(b4, buffer, bufferLength, options)); lineLength += 4; if (breakLines && lineLength >= MAX_LINE_LENGTH) { this.out.write(NEW_LINE); lineLength = 0; } position = 0; } } else { // Else, Decoding // Meaningful Base64 character? if (decodabet[theByte & 0x7f] > WHITE_SPACE_ENC) { buffer[position++] = (byte) theByte; if (position >= bufferLength) { // Enough to output. int len = Base64.decode4to3(buffer, 0, b4, 0, options); out.write(b4, 0, len); position = 0; } } else if (decodabet[theByte & 0x7f] != WHITE_SPACE_ENC) { throw new IOException("Invalid character in Base64 data."); } } } /** * Calls {@link #write(int)} repeatedly until <var>len</var> bytes are written. * * @param theBytes array from which to read bytes * @param off offset for array * @param len max number of bytes to read into array * @since 1.3 */ @Override public void write(byte[] theBytes, int off, int len) throws IOException { // Encoding suspended? if (suspendEncoding) { this.out.write(theBytes, off, len); return; } for (int i = 0; i < len; i++) { write(theBytes[off + i]); } } /** * Method added by PHIL. [Thanks, PHIL. -Rob] * This pads the buffer without closing the stream. * @throws java.io.IOException if there's an error. */ public void flushBase64() throws IOException { if (position > 0) { if (encode) { out.write(encode3to4(b4, buffer, position, options)); position = 0; } else { throw new IOException("Base64 input not properly padded."); } } } /** * Flushes and closes (I think, in the superclass) the stream. * * @since 1.3 */ @Override public void close() throws IOException { // 1. Ensure that pending characters are written flushBase64(); // 2. Actually close the stream // Base class both flushes and closes. super.close(); buffer = null; out = null; } /** * Suspends encoding of the stream. * May be helpful if you need to embed a piece of base64-encoded data in a stream. * * @throws java.io.IOException if there's an error flushing * @since 1.5.1 */ public void suspendEncoding() throws IOException { flushBase64(); this.suspendEncoding = true; } /** * Resumes encoding of the stream. * May be helpful if you need to embed a piece of base64-encoded data in a stream. * * @since 1.5.1 */ public void resumeEncoding() { this.suspendEncoding = false; } } }
Java
package com.googlecode.pngtastic.core.processing; import java.util.ArrayList; import java.util.List; import com.googlecode.pngtastic.core.Logger; import com.googlecode.pngtastic.core.PngException; /** * Implement PNG interlacing and deinterlacing * * @author rayvanderborght */ public class PngtasticInterlaceHandler implements PngInterlaceHandler { /** */ private final Logger log; /** */ private PngFilterHandler pngFilterHandler; /** */ private static final int[] interlaceColumnFrequency = new int[] { 8, 8, 4, 4, 2, 2, 1 }; private static final int[] interlaceColumnOffset = new int[] { 0, 4, 0, 2, 0, 1, 0 }; private static final int[] interlaceRowFrequency = new int[] { 8, 8, 8, 4, 4, 2, 2 }; private static final int[] interlaceRowOffset = new int[] { 0, 0, 4, 0, 2, 0, 1 }; /** */ public PngtasticInterlaceHandler(Logger log, PngFilterHandler pngFilterHandler) { this.log = log; this.pngFilterHandler = pngFilterHandler; } /** * {@inheritDoc} * * Throws a runtime exception. * <p> * NOTE: This is left unimplemented currently. Interlacing should make * most images larger in filesize, so pngtastic currently deinterlaces * all images passed through it. There may be rare exceptions that * actually benefit from interlacing, so there may come a time to revisit * this. */ @Override public List<byte[]> interlace(int width, int height, int sampleBitCount, byte[] inflatedImageData) { throw new RuntimeException("Not implemented"); } /** * {@inheritDoc} */ @Override public List<byte[]> deInterlace(int width, int height, int sampleBitCount, byte[] inflatedImageData) { this.log.debug("Deinterlacing"); List<byte[]> results = new ArrayList<byte[]>(); int sampleSize = Math.max(1, sampleBitCount / 8); byte[][] rows = new byte[height][Double.valueOf(Math.ceil(width * sampleBitCount / 8D)).intValue() + 1]; int subImageOffset = 0; for (int pass = 0; pass < 7; pass++) { int subImageRows = height / interlaceRowFrequency[pass]; int subImageColumns = width / interlaceColumnFrequency[pass]; int rowLength = Double.valueOf(Math.ceil(subImageColumns * sampleBitCount / 8D)).intValue() + 1; byte[] previousRow = new byte[rowLength]; int offset = 0; for (int i = 0; i < subImageRows; i++) { offset = subImageOffset + i * rowLength; byte[] row = new byte[rowLength]; System.arraycopy(inflatedImageData, offset, row, 0, rowLength); try { this.pngFilterHandler.deFilter(row, previousRow, sampleBitCount); } catch (PngException e) { this.log.error("Error: %s", e.getMessage()); } int samples = (row.length - 1) / sampleSize; for (int sample = 0; sample < samples; sample++) { for (int b = 0; b < sampleSize; b++) { int cf = interlaceColumnFrequency[pass] * sampleSize; int co = interlaceColumnOffset[pass] * sampleSize; int rf = interlaceRowFrequency[pass]; int ro = interlaceRowOffset[pass]; rows[i * rf + ro][sample * cf + co + b + 1] = row[(sample * sampleSize) + b + 1]; } } previousRow = row.clone(); } subImageOffset = offset + rowLength; } for (int i = 0; i < rows.length; i++) { results.add(rows[i]); } return results; } }
Java
package com.googlecode.pngtastic.core.processing; import java.util.List; /** * Apply PNG interlacing and deinterlacing * * @author rayvanderborght */ public interface PngInterlaceHandler { /** * Do png interlacing on the data given * * @param width The image width * @param height The image height * @param sampleBitCount The number of bits per sample * @param inflatedImageData The uncompressed image data, not interlaced * @return A list of scanlines, each row represented as a byte array */ public List<byte[]> interlace(int width, int height, int sampleBitCount, byte[] inflatedImageData); /** * Do png deinterlacing on the given data * * @param width The image width * @param height The image height * @param sampleBitCount The number of bits per sample * @param inflatedImageData The uncompressed image data, in interlaced form * @return A list of scanlines, each row represented as a byte array */ public List<byte[]> deInterlace(int width, int height, int sampleBitCount, byte[] inflatedImageData); }
Java
package com.googlecode.pngtastic.core.processing; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; import com.googlecode.pngtastic.core.Logger; /** * Implements PNG compression and decompression * * @author rayvanderborght */ public class PngtasticCompressionHandler implements PngCompressionHandler { private final Logger log; private static final List<Integer> compressionStrategies = Arrays.asList( Deflater.DEFAULT_STRATEGY, Deflater.FILTERED, Deflater.HUFFMAN_ONLY); /** */ public PngtasticCompressionHandler(Logger log) { this.log = log; } /** * {@inheritDoc} */ @Override public byte[] inflate(ByteArrayOutputStream imageBytes) throws IOException { InflaterInputStream inflater = new InflaterInputStream(new ByteArrayInputStream(imageBytes.toByteArray())); ByteArrayOutputStream inflatedOut = new ByteArrayOutputStream(); int readLength; byte[] block = new byte[8192]; while ((readLength = inflater.read(block)) != -1) { inflatedOut.write(block, 0, readLength); } byte[] inflatedImageData = inflatedOut.toByteArray(); return inflatedImageData; } /** * {@inheritDoc} */ @Override public byte[] deflate(byte[] inflatedImageData, Integer compressionLevel, boolean concurrent) throws IOException { List<byte[]> results = (concurrent) ? this.deflateImageDataConcurrently(inflatedImageData, compressionLevel) : this.deflateImageDataSerially(inflatedImageData, compressionLevel, Deflater.DEFAULT_STRATEGY); byte[] result = null; for (int i = 0; i < results.size(); i++) { byte[] data = results.get(i); if (result == null || (data.length < result.length)) { result = data; } } this.log.debug("Image bytes=%d", (result == null) ? -1 : result.length); return result; } /* * Do the work of deflating (compressing) the image data with the * different compression strategies in separate threads to take * advantage of multiple core architectures. */ private List<byte[]> deflateImageDataConcurrently(final byte[] inflatedImageData, final Integer compressionLevel) { final Collection<byte[]> results = new ConcurrentLinkedQueue<byte[]>(); final Collection<Callable<Object>> tasks = new ArrayList<Callable<Object>>(); for (final int strategy : compressionStrategies) { tasks.add(Executors.callable(new Runnable() { @Override public void run() { try { results.add(PngtasticCompressionHandler.this.deflateImageData(inflatedImageData, strategy, compressionLevel)); } catch (Throwable e) { PngtasticCompressionHandler.this.log.error("Uncaught Exception: %s", e.getMessage()); } } })); } ExecutorService compressionThreadPool = Executors.newFixedThreadPool(compressionStrategies.size()); try { compressionThreadPool.invokeAll(tasks); } catch (InterruptedException ex) { } finally { compressionThreadPool.shutdown(); } return new ArrayList<byte[]>(results); } /* */ private List<byte[]> deflateImageDataSerially(byte[] inflatedImageData, Integer compressionLevel, Integer compressionStrategy) { List<byte[]> results = new ArrayList<byte[]>(); List<Integer> strategies = (compressionStrategy == null) ? compressionStrategies : Collections.singletonList(compressionStrategy); for (final int strategy : strategies) { try { results.add(PngtasticCompressionHandler.this.deflateImageData(inflatedImageData, strategy, compressionLevel)); } catch (Throwable e) { PngtasticCompressionHandler.this.log.error("Uncaught Exception: %s", e.getMessage()); } } return results; } /* */ private byte[] deflateImageData(byte[] inflatedImageData, int strategy, Integer compressionLevel) throws IOException { byte[] result = null; int bestCompression = Deflater.BEST_COMPRESSION; if (compressionLevel == null || compressionLevel > Deflater.BEST_COMPRESSION || compressionLevel < Deflater.NO_COMPRESSION) { for (int compression = Deflater.BEST_COMPRESSION; compression > Deflater.NO_COMPRESSION; compression--) { ByteArrayOutputStream deflatedOut = this.deflate(inflatedImageData, strategy, compression); if (result == null || (result.length > deflatedOut.size())) { result = deflatedOut.toByteArray(); bestCompression = compression; } } } else { result = this.deflate(inflatedImageData, strategy, compressionLevel).toByteArray(); bestCompression = compressionLevel; } this.log.debug("Compression strategy: %s, compression level=%d, bytes=%d", strategy, bestCompression, (result == null) ? -1 : result.length); return result; } /* */ private ByteArrayOutputStream deflate(byte[] inflatedImageData, int strategy, int compression) throws IOException { ByteArrayOutputStream deflatedOut = new ByteArrayOutputStream(); Deflater deflater = new Deflater(compression); deflater.setStrategy(strategy); DeflaterOutputStream stream = new DeflaterOutputStream(deflatedOut, deflater); stream.write(inflatedImageData); stream.close(); return deflatedOut; } }
Java
package com.googlecode.pngtastic.core.processing; import java.io.IOException; import java.util.List; import java.util.Map; import com.googlecode.pngtastic.core.PngException; import com.googlecode.pngtastic.core.PngFilterType; /** * Apply PNG filtering and defiltering * * @author rayvanderborght */ public interface PngFilterHandler { /** * Apply the given filter type to the scanlines provided. */ public void applyFiltering(PngFilterType filterType, List<byte[]> scanlines, int sampleBitCount); /** * Apply adaptive filtering as described in the png spec. */ public void applyAdaptiveFiltering(byte[] inflatedImageData, List<byte[]> scanlines, Map<PngFilterType, List<byte[]>> filteredScanLines, int sampleSize) throws IOException; /** * Do filtering as described in the png spec: * The scanline starts with a filter type byte, then continues with the image data. */ public void filter(byte[] line, byte[] previousLine, int sampleBitCount) throws PngException; /** * Do the opposite of PNG filtering: * @see #filter(byte[], byte[], int) */ public void deFilter(byte[] line, byte[] previousLine, int sampleBitCount) throws PngException; }
Java
package com.googlecode.pngtastic.core.processing; import java.io.IOException; import java.util.List; import java.util.Map; import com.googlecode.pngtastic.core.Logger; import com.googlecode.pngtastic.core.PngException; import com.googlecode.pngtastic.core.PngFilterType; /** * Implement PNG filtering and defiltering * * @author rayvanderborght */ public class PngtasticFilterHandler implements PngFilterHandler { /** */ private final Logger log; /** */ public PngtasticFilterHandler(Logger log) { this.log = log; } /** * {@inheritDoc} */ @Override public void applyFiltering(PngFilterType filterType, List<byte[]> scanlines, int sampleBitCount) { int scanlineLength = scanlines.get(0).length; byte[] previousRow = new byte[scanlineLength]; for (byte[] scanline : scanlines) { if (filterType != null) { scanline[0] = filterType.getValue(); } byte[] previous = scanline.clone(); try { this.filter(scanline, previousRow, sampleBitCount); } catch (PngException e) { this.log.error("Error during filtering: %s", e.getMessage()); } previousRow = previous; } } /** * {@inheritDoc} */ @Override public void applyAdaptiveFiltering(byte[] inflatedImageData, List<byte[]> scanlines, Map<PngFilterType, List<byte[]>> filteredScanLines, int sampleSize) throws IOException { for (int s = 0; s < scanlines.size(); s++) { long bestSum = Long.MAX_VALUE; PngFilterType bestFilterType = null; for (Map.Entry<PngFilterType, List<byte[]>> entry : filteredScanLines.entrySet()) { long sum = 0; byte[] scanline = entry.getValue().get(s); for (int i = 1; i < scanline.length; i++) { sum += Math.abs(scanline[i]); } if (sum < bestSum) { bestFilterType = entry.getKey(); bestSum = sum; } } if (bestFilterType != null) { scanlines.get(s)[0] = bestFilterType.getValue(); } } this.applyFiltering(null, scanlines, sampleSize); } /** * {@inheritDoc} * * The bytes are named as follows (x = current, a = previous, b = above, c = previous and above) * <pre> * c b * a x * </pre> */ @Override public void filter(byte[] line, byte[] previousLine, int sampleBitCount) throws PngException { PngFilterType filterType = PngFilterType.forValue(line[0]); line[0] = 0; PngFilterType previousFilterType = PngFilterType.forValue(previousLine[0]); previousLine[0] = 0; switch (filterType) { case NONE: break; case SUB: { byte[] original = line.clone(); int previous = -(Math.max(1, sampleBitCount / 8) - 1); for (int x = 1, a = previous; x < line.length; x++, a++) { line[x] = (byte) (original[x] - ((a < 0) ? 0 : original[a])); } break; } case UP: { for (int x = 1; x < line.length; x++) { line[x] = (byte) (line[x] - previousLine[x]); } break; } case AVERAGE: { byte[] original = line.clone(); int previous = -(Math.max(1, sampleBitCount / 8) - 1); for (int x = 1, a = previous; x < line.length; x++, a++) { line[x] = (byte) (original[x] - ((0xFF & original[(a < 0) ? 0 : a]) + (0xFF & previousLine[x])) / 2); } break; } case PAETH: { byte[] original = line.clone(); int previous = -(Math.max(1, sampleBitCount / 8) - 1); for (int x = 1, a = previous; x < line.length; x++, a++) { int result = this.paethPredictor(original, previousLine, x, a); line[x] = (byte) (original[x] - result); } break; } default: throw new PngException("Unrecognized filter type " + filterType); } line[0] = filterType.getValue(); previousLine[0] = previousFilterType.getValue(); } /** * {@inheritDoc} */ @Override public void deFilter(byte[] line, byte[] previousLine, int sampleBitCount) throws PngException { PngFilterType filterType = PngFilterType.forValue(line[0]); line[0] = 0; PngFilterType previousFilterType = PngFilterType.forValue(previousLine[0]); previousLine[0] = 0; switch (filterType) { case SUB: { int previous = -(Math.max(1, sampleBitCount / 8) - 1); for (int x = 1, a = previous; x < line.length; x++, a++) { line[x] = (byte) (line[x] + ((a < 0) ? 0 : line[a])); } break; } case UP: { for (int x = 1; x < line.length; x++) { line[x] = (byte) (line[x] + previousLine[x]); } break; } case AVERAGE: { int previous = -(Math.max(1, sampleBitCount / 8) - 1); for (int x = 1, a = previous; x < line.length; x++, a++) { line[x] = (byte) (line[x] + ((0xFF & ((a < 0) ? 0 : line[a])) + (0xFF & previousLine[x])) / 2); } break; } case PAETH: { int previous = -(Math.max(1, sampleBitCount / 8) - 1); for (int x = 1, xp = previous; x < line.length; x++, xp++) { int result = this.paethPredictor(line, previousLine, x, xp); line[x] = (byte) (line[x] + result); } break; } } line[0] = filterType.getValue(); previousLine[0] = previousFilterType.getValue(); } /* */ private int paethPredictor(byte[] line, byte[] previousLine, int x, int xp) { int a = 0xFF & ((xp < 0) ? 0 : line[xp]); int b = 0xFF & previousLine[x]; int c = 0xFF & ((xp < 0) ? 0 : previousLine[xp]); int p = a + b - c; int pa = (p >= a) ? (p - a) : -(p - a); int pb = (p >= b) ? (p - b) : -(p - b); int pc = (p >= c) ? (p - c) : -(p - c); if (pa <= pb && pa <= pc) { return a; } return (pb <= pc) ? b : c; } }
Java
package com.googlecode.pngtastic.core; /** * Represents the available PNG filter types. * @see <a href="http://www.w3.org/TR/PNG/#9Filters">Filtering</a> * * @author rayvanderborght */ public enum PngFilterType { ADAPTIVE(-1), // NOTE: not a real filter type NONE(0), SUB(1), UP(2), AVERAGE(3), PAETH(4); /** */ private byte value; public byte getValue() { return this.value; } /* */ private PngFilterType() { } /* */ private PngFilterType(int i) { this.value = (byte) i; } /** */ public static PngFilterType forValue(byte value) { for (PngFilterType type : PngFilterType.values()) { if (type.getValue() == value) return type; } return NONE; } /** */ public static PngFilterType[] standardValues() { return new PngFilterType[] { NONE, SUB, UP, AVERAGE, PAETH }; } }
Java
package com.googlecode.pngtastic.core; /** * Represents the image types available in PNG images * <pre> * Table 11.1 - Allowed combinations of colour type and bit depth * PNG image type Colour type Allowed bit depths Interpretation * Greyscale 0 1, 2, 4, 8, 16 Each pixel is a greyscale sample * Truecolour 2 8, 16 Each pixel is an R,G,B triple * Indexed-colour 3 1, 2, 4, 8 Each pixel is a palette index; a PLTE chunk shall appear. * Greyscale with alpha 4 8, 16 Each pixel is a greyscale sample followed by an alpha sample. * Truecolour with alpha 6 8, 16 Each pixel is an R,G,B triple followed by an alpha sample. * </pre> * * @author rayvanderborght */ public enum PngImageType { GREYSCALE(0), TRUECOLOR(2), INDEXED_COLOR(3), GREYSCALE_ALPHA(4), TRUECOLOR_ALPHA(6); private int colorType; /** */ private PngImageType(int colorType) { this.colorType = colorType; } /** */ public static PngImageType forColorType(int colorType) { switch (colorType) { case 0: return PngImageType.GREYSCALE; case 2: return PngImageType.TRUECOLOR; case 3: return PngImageType.INDEXED_COLOR; case 4: return PngImageType.GREYSCALE_ALPHA; case 6: return PngImageType.TRUECOLOR_ALPHA; default: throw new IllegalArgumentException(); } } /** * The number of channels for this color type. * For example truecolor is RGB and therefore has 3 channels. * * @return The number of channels for this image color type */ public int channelCount() { switch (this.colorType) { case 0: case 3: return 1; case 4: return 2; case 2: return 3; case 6: return 4; default: throw new IllegalArgumentException(); } } }
Java
package com.googlecode.pngtastic.core; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.googlecode.pngtastic.core.processing.Base64; import com.googlecode.pngtastic.core.processing.PngCompressionHandler; import com.googlecode.pngtastic.core.processing.PngFilterHandler; import com.googlecode.pngtastic.core.processing.PngInterlaceHandler; import com.googlecode.pngtastic.core.processing.PngtasticCompressionHandler; import com.googlecode.pngtastic.core.processing.PngtasticFilterHandler; import com.googlecode.pngtastic.core.processing.PngtasticInterlaceHandler; import com.googlecode.pngtastic.core.processing.ZopfliCompressionHandler; /** * Optimizes PNG images for smallest possible filesize. * * @author rayvanderborght */ public class PngOptimizer { private final Logger log; private PngFilterHandler pngFilterHandler; private PngInterlaceHandler pngInterlaceHander; private PngCompressionHandler pngCompressionHandler; private boolean generateDataUriCss = false; public void setGenerateDataUriCss(boolean generateDataUriCss) { this.generateDataUriCss = generateDataUriCss; } private final List<Stats> stats = new ArrayList<Stats>(); public List<Stats> getStats() { return stats; } public PngOptimizer() { this(Logger.NONE); } public PngOptimizer(String logLevel) { this.log = new Logger(logLevel); this.pngFilterHandler = new PngtasticFilterHandler(log); this.pngInterlaceHander = new PngtasticInterlaceHandler(log, pngFilterHandler); this.pngCompressionHandler = new PngtasticCompressionHandler(log); } /** */ public void optimize(PngImage image, String outputFileName, boolean removeGamma, Integer compressionLevel) throws FileNotFoundException, IOException { log.debug("=== OPTIMIZING ==="); long start = System.currentTimeMillis(); PngImage optimized = optimize(image, removeGamma, compressionLevel); ByteArrayOutputStream optimizedBytes = new ByteArrayOutputStream(); long optimizedSize = optimized.writeDataOutputStream(optimizedBytes).size(); File originalFile = new File(image.getFileName()); long originalFileSize = originalFile.length(); byte[] optimalBytes = (optimizedSize < originalFileSize) ? optimizedBytes.toByteArray() : getFileBytes(originalFile, originalFileSize); File exported = optimized.export(outputFileName, optimalBytes); long optimizedFileSize = exported.length(); long time = System.currentTimeMillis() - start; log.debug("Optimized in %d milliseconds, size %d", time, optimizedSize); log.debug("Original length in bytes: %d (%s)", originalFileSize, image.getFileName()); log.debug("Final length in bytes: %d (%s)", optimizedFileSize, outputFileName); long fileSizeDifference = (optimizedFileSize <= originalFileSize) ? (originalFileSize - optimizedFileSize) : -(optimizedFileSize - originalFileSize); log.info("%5.2f%% :%6dB ->%6dB (%5dB saved) - %s", fileSizeDifference / Float.valueOf(originalFileSize) * 100, originalFileSize, optimizedFileSize, fileSizeDifference, outputFileName); String dataUri = (generateDataUriCss) ? Base64.encodeBytes(optimalBytes) : null; stats.add(new Stats(image.getFileName(), originalFileSize, optimizedFileSize, image.getWidth(), image.getHeight(), dataUri)); } /** */ public PngImage optimize(PngImage image) throws IOException { return this.optimize(image, false, null); } /** */ public PngImage optimize(PngImage image, boolean removeGamma, Integer compressionLevel) throws IOException { // FIXME: support low bit depth interlaced images if (image.getInterlace() == 1 && image.getSampleBitCount() < 8) { return image; } PngImage result = new PngImage(log); result.setInterlace((short) 0); Iterator<PngChunk> itChunks = image.getChunks().iterator(); PngChunk chunk = processHeadChunks(result, removeGamma, itChunks); // collect image data chunks byte[] inflatedImageData = getInflatedImageData(chunk, itChunks); int scanlineLength = (int)(Math.ceil(image.getWidth() * image.getSampleBitCount() / 8F)) + 1; List<byte[]> originalScanlines = (image.getInterlace() == 1) ? pngInterlaceHander.deInterlace((int) image.getWidth(), (int) image.getHeight(), image.getSampleBitCount(), inflatedImageData) : getScanlines(inflatedImageData, image.getSampleBitCount(), scanlineLength, image.getHeight()); // TODO: use this for bit depth reduction // this.getColors(image, originalScanlines); // apply each type of filtering Map<PngFilterType, List<byte[]>> filteredScanlines = new HashMap<PngFilterType, List<byte[]>>(); for (PngFilterType filterType : PngFilterType.standardValues()) { log.debug("Applying filter: %s", filterType); List<byte[]> scanlines = copyScanlines(originalScanlines); pngFilterHandler.applyFiltering(filterType, scanlines, image.getSampleBitCount()); filteredScanlines.put(filterType, scanlines); } // pick the filter that compresses best PngFilterType bestFilterType = null; byte[] deflatedImageData = null; for (Entry<PngFilterType, List<byte[]>> entry : filteredScanlines.entrySet()) { byte[] imageResult = pngCompressionHandler.deflate(serialize(entry.getValue()), compressionLevel, true); if (deflatedImageData == null || imageResult.length < deflatedImageData.length) { deflatedImageData = imageResult; bestFilterType = entry.getKey(); } } // see if adaptive filtering results in even better compression List<byte[]> scanlines = copyScanlines(originalScanlines); pngFilterHandler.applyAdaptiveFiltering(inflatedImageData, scanlines, filteredScanlines, image.getSampleBitCount()); byte[] adaptiveImageData = pngCompressionHandler.deflate(inflatedImageData, compressionLevel, true); log.debug("Original=%d, Adaptive=%d, %s=%d", image.getImageData().length, adaptiveImageData.length, bestFilterType, (deflatedImageData == null) ? 0 : deflatedImageData.length); if (deflatedImageData == null || adaptiveImageData.length < deflatedImageData.length) { deflatedImageData = adaptiveImageData; bestFilterType = PngFilterType.ADAPTIVE; } PngChunk imageChunk = new PngChunk(PngChunk.IMAGE_DATA.getBytes(), deflatedImageData); result.addChunk(imageChunk); // finish it while (chunk != null) { if (chunk.isCritical() && !PngChunk.IMAGE_DATA.equals(chunk.getTypeString())) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(chunk.getLength()); DataOutputStream data = new DataOutputStream(bytes); data.write(chunk.getData()); data.close(); PngChunk newChunk = new PngChunk(chunk.getType(), bytes.toByteArray()); result.addChunk(newChunk); } chunk = itChunks.hasNext() ? itChunks.next() : null; } // make sure we have the IEND chunk List<PngChunk> chunks = result.getChunks(); if (chunks != null && !PngChunk.IMAGE_TRAILER.equals(chunks.get(chunks.size() - 1).getTypeString())) { result.addChunk(new PngChunk(PngChunk.IMAGE_TRAILER.getBytes(), new byte[] { })); } return result; } /* */ private List<byte[]> getScanlines(byte[] inflatedImageData, int sampleBitCount, int rowLength, long height) { log.debug("Getting scanlines"); List<byte[]> rows = new ArrayList<byte[]>(Math.max((int) height, 0)); byte[] previousRow = new byte[rowLength]; for (int i = 0; i < height; i++) { int offset = i * rowLength; byte[] row = new byte[rowLength]; System.arraycopy(inflatedImageData, offset, row, 0, rowLength); try { pngFilterHandler.deFilter(row, previousRow, sampleBitCount); rows.add(row); previousRow = row.clone(); } catch (PngException e) { log.error("Error: %s", e.getMessage()); } } return rows; } /* */ private List<byte[]> copyScanlines(List<byte[]> original) { List<byte[]> copy = new ArrayList<byte[]>(original.size()); for (byte[] scanline : original) { copy.add(scanline.clone()); } return copy; } /* */ private byte[] serialize(List<byte[]> scanlines) { int scanlineLength = scanlines.get(0).length; byte[] imageData = new byte[scanlineLength * scanlines.size()]; for (int i = 0; i < scanlines.size(); i++) { int offset = i * scanlineLength; byte[] scanline = scanlines.get(i); System.arraycopy(scanline, 0, imageData, offset, scanlineLength); } return imageData; } /* */ private PngChunk processHeadChunks(PngImage result, boolean removeGamma, Iterator<PngChunk> itChunks) throws IOException { PngChunk chunk = null; while (itChunks.hasNext()) { chunk = itChunks.next(); if (PngChunk.IMAGE_DATA.equals(chunk.getTypeString())) { break; } if (chunk.isRequired()) { if (removeGamma && PngChunk.IMAGE_GAMA.equalsIgnoreCase(chunk.getTypeString())) { continue; } ByteArrayOutputStream bytes = new ByteArrayOutputStream(chunk.getLength()); DataOutputStream data = new DataOutputStream(bytes); data.write(chunk.getData()); data.close(); PngChunk newChunk = new PngChunk(chunk.getType(), bytes.toByteArray()); if (PngChunk.IMAGE_HEADER.equals(chunk.getTypeString())) { newChunk.setInterlace((byte) 0); } result.addChunk(newChunk); } } return chunk; } /* */ private byte[] getInflatedImageData(PngChunk chunk, Iterator<PngChunk> itChunks) throws IOException { ByteArrayOutputStream imageBytes = new ByteArrayOutputStream(chunk == null ? 0 : chunk.getLength()); DataOutputStream imageData = new DataOutputStream(imageBytes); while (chunk != null) { if (PngChunk.IMAGE_DATA.equals(chunk.getTypeString())) { imageData.write(chunk.getData()); } else { break; } chunk = itChunks.hasNext() ? itChunks.next() : null; } imageData.close(); return pngCompressionHandler.inflate(imageBytes); } /* */ @SuppressWarnings("unused") private Set<PngPixel> getColors(PngImage original, List<byte[]> rows) throws IOException { Set<PngPixel> colors = new HashSet<PngPixel>(); PngImageType imageType = PngImageType.forColorType(original.getColorType()); int sampleSize = original.getSampleBitCount(); for (byte[] row : rows) { int sampleCount = ((row.length - 1) * 8) / sampleSize; ByteArrayInputStream ins = new ByteArrayInputStream(row); DataInputStream dis = new DataInputStream(ins); dis.readUnsignedByte(); // the filter byte for (int i = 0; i < sampleCount; i++) { switch (imageType) { case INDEXED_COLOR: // TODO: read pixels from palette break; case GREYSCALE: case GREYSCALE_ALPHA: // TODO: who knows break; case TRUECOLOR: if (original.getBitDepth() == 8) { int red = dis.readUnsignedByte(); int green = dis.readUnsignedByte(); int blue = dis.readUnsignedByte(); colors.add(new PngPixel(red, green, blue)); } else { int red = dis.readUnsignedShort(); int green = dis.readUnsignedShort(); int blue = dis.readUnsignedShort(); colors.add(new PngPixel(red, green, blue)); } break; case TRUECOLOR_ALPHA: if (original.getBitDepth() == 8) { int red = dis.readUnsignedByte(); int green = dis.readUnsignedByte(); int blue = dis.readUnsignedByte(); int alpha = dis.readUnsignedByte(); colors.add(new PngPixel(red, green, blue, alpha)); } else { int red = dis.readUnsignedShort(); int green = dis.readUnsignedShort(); int blue = dis.readUnsignedShort(); int alpha = dis.readUnsignedShort(); colors.add(new PngPixel(red, green, blue, alpha)); } break; default: throw new IllegalArgumentException(); } } } // for (PngPixel c : colors) // this.log.debug("r=%d g=%d b=%d a=%d", red, green, blue, alpha); this.log.debug("color count=%d", colors.size()); return colors; } /** */ private static class PngPixel { private final int red; private final int green; private final int blue; private final int alpha; /** */ public PngPixel(int red, int green, int blue) { this(red, green, blue, -1); } /** */ public PngPixel(int red, int green, int blue, int alpha) { this.red = red; this.green = green; this.blue = blue; this.alpha = alpha; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.alpha; result = prime * result + this.blue; result = prime * result + this.green; result = prime * result + this.red; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } PngPixel other = (PngPixel) obj; if (this.alpha != other.alpha || this.blue != other.blue || this.green != other.green || this.red != other.red) { return false; } return true; } } /** * Holds info about an image file optimization */ public static class Stats { private long originalFileSize; public long getOriginalFileSize() { return originalFileSize; } private long optimizedFileSize; public long getOptimizedFileSize() { return optimizedFileSize; } private String fileName; private long width; private long height; private String dataUri; public Stats(String fileName, long originalFileSize, long optimizedFileSize, long width, long height, String dataUri) { this.originalFileSize = originalFileSize; this.optimizedFileSize = optimizedFileSize; this.fileName = fileName; this.width = width; this.height = height; this.dataUri = dataUri; } } /** * Get the number of bytes saved in all images processed so far * * @return The number of bytes saved */ public long getTotalSavings() { long totalSavings = 0; for (PngOptimizer.Stats stat : stats) { totalSavings += (stat.getOriginalFileSize() - stat.getOptimizedFileSize()); } return totalSavings; } /** * Get the css containing data uris of the images processed by the optimizer */ public void generateDataUriCss(String dir) throws IOException { String path = (dir == null) ? "" : dir + "/"; PrintWriter out = new PrintWriter(path + "DataUriCss.html"); try { out.append("<html>\n<head>\n\t<style>"); for (PngOptimizer.Stats stat : stats) { String name = stat.fileName.replaceAll("[^A-Za-z0-9]", "_"); out.append('#').append(name).append(" {\n") .append("\tbackground: url(\"data:image/png;base64,") .append(stat.dataUri).append("\") no-repeat left top;\n") .append("\twidth: ").append(String.valueOf(stat.width)).append("px;\n") .append("\theight: ").append(String.valueOf(stat.height)).append("px;\n") .append("}\n"); } out.append("\t</style>\n</head>\n<body>\n"); for (PngOptimizer.Stats stat : stats) { String name = stat.fileName.replaceAll("[^A-Za-z0-9]", "_"); out.append("\t<div id=\"").append(name).append("\"></div>\n"); } out.append("</body>\n</html>"); } finally { if (out != null) { out.close(); } } } private byte[] getFileBytes(File originalFile, long originalFileSize) throws IOException { ByteBuffer buffer = ByteBuffer.allocate((int) originalFileSize); FileInputStream ins = null; try { ins = new FileInputStream(originalFile); ins.getChannel().read(buffer); } finally { if (ins != null) { ins.close(); } } return buffer.array(); } /* */ @SuppressWarnings("unused") private void printData(byte[] inflatedImageData) { StringBuilder result = new StringBuilder(); for (byte b : inflatedImageData) { result.append(String.format("%2x|", b)); } log.debug(result.toString()); } public void setCompressor(String compressor) { if (compressor != null && compressor.contains("zopfli")) { this.pngCompressionHandler = new ZopfliCompressionHandler(log, compressor); } } }
Java
package com.annasanches.orkut.client; import com.annasanches.orkut.shared.FieldVerifier; import com.google.gwt.core.client.GWT; import com.google.gwt.junit.client.GWTTestCase; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.rpc.ServiceDefTarget; /** * GWT JUnit <b>integration</b> tests must extend GWTTestCase. * Using <code>"GwtTest*"</code> naming pattern exclude them from running with * surefire during the test phase. * * If you run the tests using the Maven command line, you will have to * navigate with your browser to a specific url given by Maven. * See http://mojo.codehaus.org/gwt-maven-plugin/user-guide/testing.html * for details. */ public class GwtTestOrkut extends GWTTestCase { /** * Must refer to a valid module that sources this class. */ public String getModuleName() { return "com.annasanches.orkut.OrkutJUnit"; } /** * Tests the FieldVerifier. */ public void testFieldVerifier() { assertFalse(FieldVerifier.isValidName(null)); assertFalse(FieldVerifier.isValidName("")); assertFalse(FieldVerifier.isValidName("a")); assertFalse(FieldVerifier.isValidName("ab")); assertFalse(FieldVerifier.isValidName("abc")); assertTrue(FieldVerifier.isValidName("abcd")); } /** * This test will send a request to the server using the greetServer method in * GreetingService and verify the response. */ public void testGreetingService() { // Create the service that we will test. GreetingServiceAsync greetingService = GWT.create(GreetingService.class); ServiceDefTarget target = (ServiceDefTarget) greetingService; target.setServiceEntryPoint(GWT.getModuleBaseURL() + "Orkut/greet"); // Since RPC calls are asynchronous, we will need to wait for a response // after this test method returns. This line tells the test runner to wait // up to 10 seconds before timing out. delayTestFinish(10000); // Send a request to the server. greetingService.greetServer("GWT User", new AsyncCallback<String>() { public void onFailure(Throwable caught) { // The request resulted in an unexpected error. fail("Request failure: " + caught.getMessage()); } public void onSuccess(String result) { // Verify that the response is correct. assertTrue(result.startsWith("Hello, GWT User!")); // Now that we have received a response, we need to tell the test runner // that the test is complete. You must call finishTest() after an // asynchronous test finishes successfully, or the test will time out. finishTest(); } }); } }
Java
package com.annasanches.orkut.client.servicos; import com.annasanches.orkut.shared.beans.Agencia; import com.google.gwt.user.client.rpc.AsyncCallback; public interface ServicoAgenciaAsync { void cadastrarAgencia(Agencia agencia, AsyncCallback<Void> callback); void consultarAgencia(int codigo, AsyncCallback<Agencia> callback); void desativarAgencia(int codigo, AsyncCallback<Boolean> callback); void ativarAgencia(int codigo, AsyncCallback<Boolean> callback); }
Java
package com.annasanches.orkut.client.servicos; import com.annasanches.orkut.shared.beans.Agencia; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; @RemoteServiceRelativePath("agencia.rpc") public interface ServicoAgencia extends RemoteService{ void cadastrarAgencia(Agencia agencia); Agencia consultarAgencia(int codigo); Boolean desativarAgencia(int codigo); Boolean ativarAgencia(int codigo); }
Java
package com.annasanches.orkut.client.editoragencia; import com.annasanches.orkut.client.servicos.ServicoAgencia; import com.annasanches.orkut.client.servicos.ServicoAgenciaAsync; import com.annasanches.orkut.shared.beans.Agencia; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; public class EditorAgencia extends Composite { private static EditorAgenciaUiBinder uiBinder = GWT .create(EditorAgenciaUiBinder.class); interface EditorAgenciaUiBinder extends UiBinder<Widget, EditorAgencia> { } @UiField TextBox txtNome,txtAgencia,txtCNPJ,txtEndereco; @UiField CheckBox chkAgencia; /*@UiField Button btnConsulta,btnSalvar,btnDesativar,btnReativar;*/ public EditorAgencia() { initWidget(uiBinder.createAndBindUi(this)); } Agencia agencia=new Agencia(); private ServicoAgenciaAsync servico = GWT.create(ServicoAgencia.class); @UiHandler("btnSalvar") void quandoSalvar(ClickEvent event){ preencherBeanAgencia(agencia); //Window.alert("Salvando"+agencia.getCodigo()); servico.cadastrarAgencia(agencia, new AsyncCallback<Void>(){ public void onSuccess(Void result){ Window.alert("Agencia salva com sucesso!"); } public void onFailure(Throwable caught){ Window.alert(caught.getMessage()); } }); limparTela(); } @UiHandler("btnConsulta") void quandoConsulta(ClickEvent event){ int codigo = Integer.parseInt(txtAgencia.getValue()); servico.consultarAgencia(codigo, new AsyncCallback<Agencia>(){ public void onFailure(Throwable caught) { Window.alert(caught.getMessage()); } public void onSuccess(Agencia result) { mostrarBeanAgencia(result); } }); } @UiHandler("btnDesativar") void Desativar(ClickEvent event){ int codigo = Integer.parseInt(txtAgencia.getValue()); servico.desativarAgencia(codigo,new AsyncCallback<Boolean>(){ public void onFailure(Throwable caught) { Window.alert(caught.getMessage()); } public void onSuccess(Boolean result) { if(result==Boolean.TRUE){ Window.alert("Agencia Desativada"); } else{ Window.alert("Agencia já está desativada"); } } }); limparTela(); } @UiHandler("btnReativar") void Ativar(ClickEvent event){ int codigo = Integer.parseInt(txtAgencia.getValue()); servico.ativarAgencia(codigo, new AsyncCallback<Boolean>(){ public void onFailure(Throwable caught) { Window.alert(caught.getMessage()); } public void onSuccess(Boolean result) { if(result==Boolean.FALSE){ Window.alert("Agencia ativada"); } else{ Window.alert("Agencia já está ativada"); } } }); limparTela(); } private void limparTela(){ txtNome.setValue(""); txtAgencia.setValue(""); txtEndereco.setValue(""); txtCNPJ.setValue(""); chkAgencia.setValue(false); } private void preencherBeanAgencia(Agencia agencia){ agencia.setNome(txtNome.getValue()); agencia.setCodigo(Integer.parseInt(txtAgencia.getValue())); agencia.setEndereco(txtEndereco.getValue()); agencia.setCnpj(txtCNPJ.getValue()); agencia.setAtiva(chkAgencia.getValue()); } private void mostrarBeanAgencia(Agencia agencia){ txtNome.setValue(agencia.getNome()); txtCNPJ.setValue(agencia.getCnpj()); txtAgencia.setValue(String.valueOf(agencia.getCodigo())); txtEndereco.setValue(agencia.getEndereco()); chkAgencia.setValue(agencia.isAtiva()); } }
Java
package com.annasanches.orkut.client; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; /** * The client side stub for the RPC service. */ @RemoteServiceRelativePath("greet") public interface GreetingService extends RemoteService { String greetServer(String name) throws IllegalArgumentException; }
Java
package com.annasanches.orkut.client; import com.annasanches.orkut.client.editoragencia.EditorAgencia; import com.google.gwt.core.client.EntryPoint; /*import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.HTML;*/ import com.google.gwt.user.client.ui.RootPanel; public class Orkut implements EntryPoint { public void onModuleLoad() { /*final HTML html =new HTML("<center>Hello World</center>"); html.setStyleName("meustitulosvermelho"); Button botaoAmarelo=new Button("Amarelo"); Button botaoVerde=new Button("Verde"); botaoAmarelo.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { //Window.alert("Botao Clicado"); html.setStyleName("meustitulosamarelos"); // RootPanel.get().add(html); } }); botaoVerde.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { html.setStyleName("meustitulosverde"); // RootPanel.get().add(html); } }); RootPanel.get().add(html); RootPanel.get().add(botaoAmarelo); RootPanel.get().add(botaoVerde);*/ RootPanel.get().add(new EditorAgencia()); } }
Java
package com.annasanches.orkut.shared.beans; import com.google.gwt.user.client.rpc.IsSerializable; public class Agencia implements IsSerializable{ private int codigo; private String nome; private String endereco; private String cnpj; private boolean ativa; public int getCodigo() { return codigo; } public void setCodigo(int codigo) { this.codigo = codigo; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getEndereco() { return endereco; } public void setEndereco(String endereco) { this.endereco = endereco; } public String getCnpj() { return cnpj; } public void setCnpj(String cnpj) { this.cnpj = cnpj; } public boolean isAtiva() { return ativa; } public void setAtiva(boolean ativa) { this.ativa = ativa; } }
Java
package com.annasanches.orkut.shared; /** * <p> * FieldVerifier validates that the name the user enters is valid. * </p> * <p> * This class is in the <code>shared</code> packing because we use it in both * the client code and on the server. On the client, we verify that the name is * valid before sending an RPC request so the user doesn't have to wait for a * network round trip to get feedback. On the server, we verify that the name is * correct to ensure that the input is correct regardless of where the RPC * originates. * </p> * <p> * When creating a class that is used on both the client and the server, be sure * that all code is translatable and does not use native JavaScript. Code that * is note translatable (such as code that interacts with a database or the file * system) cannot be compiled into client side JavaScript. Code that uses native * JavaScript (such as Widgets) cannot be run on the server. * </p> */ public class FieldVerifier { /** * Verifies that the specified name is valid for our service. * * In this example, we only require that the name is at least four * characters. In your application, you can use more complex checks to ensure * that usernames, passwords, email addresses, URLs, and other fields have the * proper syntax. * * @param name the name to validate * @return true if valid, false if invalid */ public static boolean isValidName(String name) { if (name == null) { return false; } return name.length() > 3; } }
Java
package com.annasanches.orkut.server; import com.annasanches.orkut.client.GreetingService; import com.annasanches.orkut.shared.FieldVerifier; import com.google.gwt.user.server.rpc.RemoteServiceServlet; /** * The server side implementation of the RPC service. */ @SuppressWarnings("serial") public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService { public String greetServer(String input) throws IllegalArgumentException { // Verify that the input is valid. if (!FieldVerifier.isValidName(input)) { // If the input is not valid, throw an IllegalArgumentException back to // the client. throw new IllegalArgumentException( "Name must be at least 4 characters long"); } String serverInfo = getServletContext().getServerInfo(); String userAgent = getThreadLocalRequest().getHeader("User-Agent"); // Escape data from the client to avoid cross-site script vulnerabilities. input = escapeHtml(input); userAgent = escapeHtml(userAgent); return "Hello, " + input + "!<br><br>I am running " + serverInfo + ".<br><br>It looks like you are using:<br>" + userAgent; } /** * Escape an html string. Escaping data received from the client helps to * prevent cross-site script vulnerabilities. * * @param html the html string to escape * @return the escaped string */ private String escapeHtml(String html) { if (html == null) { return null; } return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll( ">", "&gt;"); } }
Java
package com.annasanches.orkut.server.servicos; import java.util.LinkedList; import java.util.List; import com.annasanches.orkut.client.servicos.ServicoAgencia; import com.annasanches.orkut.shared.beans.Agencia; import com.google.gwt.user.server.rpc.RemoteServiceServlet; public class ServicoAgenciaImpl extends RemoteServiceServlet implements ServicoAgencia{ // private Agencia[] agencias=new Agencia[100]; private List agencias = new LinkedList(); // private int i=0; //agencia[indice]=objetos; public ServicoAgenciaImpl(){ for(int i=1;i<5;i++){ Agencia a=new Agencia(); a.setAtiva(true); a.setCnpj("32165498725"); a.setCodigo(i); a.setEndereco("Sorocaba"+i); a.setNome("BancoDoBrasil"); agencias.add(a); } } public void cadastrarAgencia(Agencia agencia){ agencias.add(agencia); /* if((i+1)<100){ agencias[i] =agencia; i++; System.out.println("a agencia chegou ao servidor"); }*/ } public Agencia consultarAgencia(int codigo){ for(int i = 0; i < agencias.size(); i++){ Agencia a=(Agencia) agencias.get(i); if(a.getCodigo()==codigo){ return a; } } /* int j; for(j=0;j<100;j++){ if(agencias[j]!=null && agencias[j].getCodigo()==codigo){ return agencias[j]; }*/ return null; } public Boolean desativarAgencia(int codigo){ for(int i = 0; i < agencias.size(); i++){//Agencia a:agencias){ Agencia a=(Agencia) agencias.get(i); if(/*a!=null && */a.getCodigo()==codigo){ a.setAtiva((false)); return true; } } return false; } public Boolean ativarAgencia(int codigo){ for(int i = 0; i < agencias.size(); i++){//Agencia a:agencias){ Agencia a=(Agencia) agencias.get(i); if(/*a!=null &&*/ a.getCodigo()==codigo){ a.setAtiva((true)); return false; } } return true; } }
Java
package runTimeCompile; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.Writer; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * This class takes care of run time compilation and execution of formula entered by user. * Methods of this class create two temp files namely TempCompileStringClass.java and TempCompileStringClass.class * @author praveen_kulkarni */ public class RuntimeCompileString { private static File file; private static Object currentObject; private static Method computeMethod; /** * This method compiles the entered formula and returns true if success. * If compilation is not successful it throws error message box and returns false * @param formula Takes formula entered by user as String * @return Returns true if success and false if failure */ public static boolean compile(String formula) { try { if (formula == null || formula.trim().equals("")) { JOptionPane.showMessageDialog(new JFrame(), "Please enter/select the formula", "NO FORMULA PROVIDED", JOptionPane.ERROR_MESSAGE); return false; } if (formula.split("=").length != 2 || !formula.split("=")[0].trim().equals("y")) { JOptionPane.showMessageDialog(new JFrame(), "Formula entered is: " + formula + "\nPlease use proper formula of form y = f(x,y)", "IMPROPER FORMULA PROVIDED", JOptionPane.ERROR_MESSAGE); return false; } formula = formula.split("=")[1]; Writer output = null; String code = "" + " public class TempCompileStringClass{ \n" + " public float y = 0.0f; \n" + " public void compute(Float x){ \n" + " y=(float)" + formula + "; \n" + " } \n" + " public String toString(){ \n" + " return \"\"+y; \n" + " } \n" + "} "; try { file = new File(System.getProperty("user.dir") + File.separatorChar + "TempCompileStringClass.java"); } catch (Exception ex) { JOptionPane.showMessageDialog(new JFrame(), "Error occured while creating temporary java file in directory " + System.getProperty("user.dir") + ". \nCheck for permissions. \nError details:\n" + ex.getMessage(), "ERROR OCCURED WHILE COMPILING COMMAND", JOptionPane.ERROR_MESSAGE); return false; } try { output = new BufferedWriter(new FileWriter(file)); output.write(code); output.close(); } catch (Exception ex) { JOptionPane.showMessageDialog(new JFrame(), "Error occured while writing to temporary java file in directory " + System.getProperty("user.dir") + ". \nError details:\n" + ex.getMessage(), "ERROR OCCURED WHILE COMPILING COMMAND", JOptionPane.ERROR_MESSAGE); return false; } com.sun.tools.javac.Main javacMain = null; try { javacMain = new com.sun.tools.javac.Main(); javacMain.compile(new String[]{file.getPath()}); URL url = file.getParentFile().toURL(); URL[] urls = new URL[]{url}; ClassLoader loader = new URLClassLoader(urls); Class currentClass = loader.loadClass("TempCompileStringClass"); currentObject = currentClass.newInstance(); Class[] paramsClassType = {Float.class}; computeMethod = currentClass.getDeclaredMethod("compute", paramsClassType); } catch (Exception ex) { JOptionPane.showMessageDialog(new JFrame(), "Error occured while compiling temporary java file in directory " + System.getProperty("user.dir") + ". \nPlease check you have entered a proper formula " + "that java compiler can compile.\n\nHint: Formula entered can use only two variables " + "'x' and 'y' \nwith 'y' on LHS and function of 'x' and 'y' on RHS.\nYou can see more " + "examples in dropdown provided to select precompiled formulas.\n\n \nError details:\n" + ex.getMessage(), "ERROR OCCURED WHILE COMPILING COMMAND", JOptionPane.ERROR_MESSAGE); return false; }catch (Error ex) { JOptionPane.showMessageDialog(new JFrame(), "Error occured while compiling temporary java file in directory " + System.getProperty("user.dir") + ". \nPlease check you have entered a proper formula " + "that java compiler can compile.\n\nHint: Formula entered can use only two variables " + "'x' and 'y' \nwith 'y' on LHS and function of 'x' and 'y' on RHS.\nYou can see more " + "examples in dropdown provided to select precompiled formulas.\n\n \nError details:\n" + ex.getMessage(), "ERROR OCCURED WHILE COMPILING COMMAND", JOptionPane.ERROR_MESSAGE); return false; } } catch (Exception ex) { JOptionPane.showMessageDialog(new JFrame(), "Error details:\n" + ex.getMessage(), "ERROR OCCURED WHILE COMPILING COMMAND", JOptionPane.ERROR_MESSAGE); return false; } catch (Error err) { JOptionPane.showMessageDialog(new JFrame(), "Error details:\n" + err.getMessage(), "ERROR OCCURED WHILE COMPILING COMMAND", JOptionPane.ERROR_MESSAGE); return false; } return true; } /** * The compiled formula can be used by using this methods. You have to pass value of x for which y is to be computed * @param x Holds the value of x for which y is to be calculated * @return Returns the value of y for given x */ public static float compute(Float x) { Float y = 0.0f; try { computeMethod.invoke(currentObject, x); y = Float.parseFloat(currentObject.toString()); } catch (IllegalAccessException ex) { Logger.getLogger(RuntimeCompileString.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalArgumentException ex) { Logger.getLogger(RuntimeCompileString.class.getName()).log(Level.SEVERE, null, ex); } catch (InvocationTargetException ex) { Logger.getLogger(RuntimeCompileString.class.getName()).log(Level.SEVERE, null, ex); } return (Float) y; } /** * After compilation of files two temporary files are created. Call this method to delete those files. */ public static void deleteTempFilesCreated() { file.delete(); new File(System.getProperty("user.dir") + File.separatorChar + "TempCompileStringClass.class").delete(); } }
Java
/* * Copyright (c) 2009, Oracle * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * * Neither the name of Oracle nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.netbeans.javafx.design; /** * Represents a type of behaviour for timelines of previous and new state when an actual state is changed in state a DesignState. */ public enum DesignStateChangeType { /** * Use this constant for setting <code>DesignState.stateChangeType</code> field. * This type stops previous timeline and plays the new timeline from its start. */ PAUSE_AND_PLAY_FROM_START, /** * Use this constant for setting <code>DesignState.stateChangeType</code> field. * This type finishes previous timeline by setting the time to the totalDuration and plays the new timeline from its start. */ FINISH_AND_PLAY_FROM_START, /** * Use this constant for setting <code>DesignState.stateChangeType</code> field. * This type leaves the previous timeline running and starts playing the new one. * This behaviour may lead to some unconsistent state e.g. when a new timeline finishes before the old one. */ CONTINUE_AND_PLAY, /** * Use this constant for setting <code>DesignState.stateChangeType</code> field. * This type does not do anything with the timelines. */ DO_NOTHING }
Java
package threadHandlers; import com.sun.javafx.runtime.Entry; import annCode.TrainANNCpuMode; import annCode.TrainANNGpuMode; import annCode.TrainANN; import javafx.async.RunnableFuture; /** * This class helps in launching of thread which will take care of training ANN. * Throughout the life of application this thread will run in parallel * @author praveen_kulkarni */ public class JavaTrainingThreadTask implements RunnableFuture { public Float currentError = 0.0f; public Float learningConstant = 0.0f; public Integer iterationsCompleted = 0; public Boolean isTrainingActive = false; public Boolean isTrainingPaused = true; private Integer selectedModeIndex = 0; public Long durationOfTraining = (long) 0; private TrainingThreadListener listener; public float[] teacherInputArray; public float[] teacherOutputArray; public float[] trainingOutcomeArray; public TrainANN trainANN; public boolean updateGraph = true; public JavaTrainingThreadTask(TrainingThreadListener listener) { this.listener = listener; } public void setSelectedModeIndex(int temp) { synchronized (this) { this.selectedModeIndex = temp; } } /** * This method launches the java thread in parallel which takes care of training ANN * @throws Exception */ @Override public void run() throws Exception { TrainANN trainANN = null; // = new TrainANNCpuGeneralMode(); // loop infininetly while (true) { try { // Once compute button is clicked this loop will start and will end only when reset button is clicked. while (isTrainingActive) { if (trainANN == null) { // depending on mode selected create object of respective class if (selectedModeIndex == 0) { trainANN = new TrainANNCpuMode(); trainANN.loadData(teacherInputArray, teacherOutputArray); } else if (selectedModeIndex == 1) { trainANN = new TrainANNGpuMode(); trainANN.loadData(teacherInputArray, teacherOutputArray); // GPU mode requires compilation and allocation of memory ((TrainANNGpuMode) trainANN).compileKernels(); ((TrainANNGpuMode) trainANN).allocateMemoryAndCopyDataToGpgpu(); } } // Don't execute this code if stop button is clicked i.e. training is paused if (!isTrainingPaused) { long startTime = System.currentTimeMillis(); trainANN.trainANN(learningConstant, this); long stopTime = System.currentTimeMillis(); // calculate time for one iteration and add to total time taken durationOfTraining = durationOfTraining + (stopTime - startTime); // get the output estimated by ANN for this iteration trainingOutcomeArray = trainANN.getTrainingOutcome(); // get the error by which the ANN outcome is away from teacher output for this iteration currentError = trainANN.getCurrentError(); // increment number of iterations finished iterationsCompleted = iterationsCompleted + 1; // execute postMessage() only when previous update of JavaFX UI is completed. // This helps in avoiding muntiple execution of postMessage() while UI is still updating if (updateGraph == true) { postMessage(); // set to false telling other communicating programs that a call to postMessage() is done to update UI updateGraph = false; } // if (iterationsCompleted == 1) { // System.out.println("...." + durationOfTraining); // isTrainingPaused = true; // isTrainingActive = false; // break; // } } } // execute only when trainANN != null if (trainANN != null) { // If Gpu mode free memory on GPU if (trainANN instanceof TrainANNGpuMode) { ((TrainANNGpuMode) trainANN).freeGpgpuAfterTraining(); } // reset the remaining values durationOfTraining = 0l; currentError = 0.0f; iterationsCompleted = 0; // reset the UI postMessage(); // make trainANN null trainANN = null; } } catch (Exception e) { e.printStackTrace(); } } } /** * This method helps in updating UI * It creates a temporary thread that calls the methods which update UI and the thread dies. * This avoids the unnecessary waiting of thread that calls this method and thus helps the * above run method focus on training ANN rather than caring about UI update. */ public void postMessage() { Entry.deferAction( new Runnable() { @Override public void run() { listener.communicateCurrentError(currentError); listener.communicateIterationsCompleted(iterationsCompleted); listener.communicateDurationOfTraining(durationOfTraining); listener.communicateTrainingOutcomeArray(trainingOutcomeArray); } }); } }
Java
package threadHandlers; /** * This interface contains four methods whose implementation will be executed when * postMessage() method of JavaTrainingThreadTask is executed. * These methods are responsible for update of UI * @author praveen_kulkarni */ public interface TrainingThreadListener { public void communicateIterationsCompleted(Integer iterationsCompleted); public void communicateCurrentError(Float currentError); public void communicateTrainingOutcomeArray(float[] trainingOutcomeArray); public void communicateDurationOfTraining(Long durationOfTraining); }
Java
package annCode; import javax.swing.JFrame; import javax.swing.JOptionPane; import threadHandlers.JavaTrainingThreadTask; /** * This abstract class is parent class for the two classes TrainANNCpuMode and TrainANNGpuMode. * It holds some common abstract methods which are to be implemented by child classes. * * @author praveen_kulkarni */ public abstract class TrainANN { /** * These are general variables used by both child classes. * For proper training the optimal number of neurons required in layer2 is (2*number of patterns) * i.e. 2 neurons per pattern * We assume here that numberOfInputPatterns is always multiple of 512 */ public static int layer2Neurons; public static int numberOfInputPatterns; /** * These are CUDA architecture related variables and are used in TrainANNGpuMode class. * threadsPerBlock must be a multiple of 32 and less than thread limit per block. */ public static int numberOfBlocks; public static int threadsPerBlock; /** * This method is executed for getting numberOfInputPatterns and accordingly set the remaining * variables of this class. This is the first method to get executed. * @param numberOfInputPatterns Make sure that twice of this value is multiple of threads per block * limit for GPU mode to work properly */ public static void setConfigurationVariables(int numberOfInputPatterns){ // threadsPerBlock must be a multiple of 32 and less than thread limit per block TrainANN.threadsPerBlock = 512; // For proper training the optimal number of neurons required in layer2 is (2*number of patterns) TrainANN.layer2Neurons = numberOfInputPatterns*2; // display warning to user that layer2Neurons must be multiple of // threadsPerBlock limit and program may not work in case of GPU. if(TrainANN.layer2Neurons%TrainANN.threadsPerBlock!=0){ JOptionPane.showMessageDialog(new JFrame(), "Layer 2 neurons required is not the multiple of threads per block limit." + "\nThis will work for CPU mode but not for GPU", "WARNING", JOptionPane.ERROR_MESSAGE); } TrainANN.numberOfInputPatterns = numberOfInputPatterns; // calculate the number of blocks required TrainANN.numberOfBlocks = numberOfInputPatterns*2/TrainANN.threadsPerBlock; } /** * Implementation of this method by child classes is supposed to get teacher input and teacher * output for which ANN is to be trained. Accordingly it will load its instance members. * @param teacherInputArray * @param teacherOutputArray */ public abstract void loadData(float[] teacherInputArray, float[] teacherOutputArray); /** * Child classes must implement this method to implement training algorithm which will work on * data loaded by loadData() method * @param learningConstantArg learning constant at which ANN must be trained * @param javaTrainingThreadTask Helps to communicate data computed to UI (JavaFx program) and display it */ public abstract void trainANN(float learningConstantArg,JavaTrainingThreadTask javaTrainingThreadTask); /** * You can call this method to get the outcome of ANN which is undergoing training. * Each training iteration will store the estimated output for current iteration in * trainingOutcome array. This helps us to view the small progress done by trainANN() method * @return Float array is returned which can be plotted on graph to see how close * we are to the required function */ public abstract float[] getTrainingOutcome(); /** * As the training proceeds the error will reduce. This method can be used to get the error that * is occurred due to current training iteration. * @return returns the current error */ public abstract float getCurrentError(); }
Java
package annCode; import java.util.Random; import javax.swing.JFrame; import javax.swing.JOptionPane; import jcuda.Pointer; import jcuda.Sizeof; import jcuda.driver.CUdeviceptr; import jcuda.driver.JCudaDriver; import jcuda.utils.KernelLauncher; import threadHandlers.JavaTrainingThreadTask; /** * This class involves code that will execute code on GPU. * It extends TrainANN abstract classes and implements its abstract method. * @author praveen_kulkarni */ public class TrainANNGpuMode extends TrainANN { /** * Stores teacher input and output for which ANN is to be trained */ private float[] teacherInputArray = new float[numberOfInputPatterns]; private float[] teacherOutputArray = new float[numberOfInputPatterns]; /** * Each training iteration will store the estimated output for current iteration in * trainingOutcomeArray. This helps us to view the small progress done by trainANN() method */ private float[] trainingOutcomeArray = new float[numberOfInputPatterns]; /** * Weights involved between input layer and hidden layer. * Instance member layer1Weight2Vector represents weights between augmented * input of input layer and hidden layer. */ private float[] layer1Weight1Vector = new float[layer2Neurons]; private float[] layer1Weight2Vector = new float[layer2Neurons]; /** * Weights involved between hidden layer and output layer. * Instance member layer2Weight2 represents weight between augmented input * of hidden layer and output layer. Only one such weight exists as * we have only one output neuron in output layer. */ private float[] layer2Weight1Vector = new float[layer2Neurons]; private float layer2Weight2; /** * Used in modifying layer 2 weights. * It depends on error calculated for current iteration, */ private float deltaLayer2; /** * Holds error for current iteration. */ private float currentError = 0.0f; /** * This member groups different host variables to be communicated to GPU. * This helps us avoid multiple copies to GPU * Size for communicationDataArray is 4 as * communicationDataArray[0] will contain teacherInput * communicationDataArray[1] will contain teacherOutput * communicationDataArray[2] will contain learningConstant * communicationDataArray[3] will contain deltaLayer2 */ private float[] communicationDataArray = new float[4]; /** * Below members points to GPU global memory. */ private CUdeviceptr communicationDataArrayDevicePointer = new CUdeviceptr(); private CUdeviceptr layer1Weight1VectorDevicePointer = new CUdeviceptr(); private CUdeviceptr layer1Weight2VectorDevicePointer = new CUdeviceptr(); private CUdeviceptr layer2Weight1VectorDevicePointer = new CUdeviceptr(); private CUdeviceptr layer2OutputVectorDevicePointer = new CUdeviceptr(); private CUdeviceptr deltaLayer1VectorDevicePointer = new CUdeviceptr(); private CUdeviceptr tempArrayToStorePartialSumsDevicePointer = new CUdeviceptr(); /** * Below variables holds references to KernelLauncher that will help * launch kernels on GPU. */ private KernelLauncher computeLayer2OutputAndPartialSumsForTrainingOutcomeKernelLauncher; private KernelLauncher computeDeltaLayer1VectorKernelLauncher; private KernelLauncher modifyWeightsKernelLauncher; /** * See TrainANN class for more explanation. * @param teacherInput * @param teacherOutput */ @Override public void loadData(float[] teacherInput, float[] teacherOutput) { try { int count = 0; for (float x : teacherInput) { this.teacherInputArray[count] = x; count++; } count = 0; for (float x : teacherOutput) { this.teacherOutputArray[count] = x; count++; } Random randomGenerator = new Random(System.currentTimeMillis()); for (int x = 0; x < layer1Weight1Vector.length; x++) { layer1Weight1Vector[x] = 2.0f * randomGenerator.nextFloat() - 1.0f; } for (int x = 0; x < layer1Weight2Vector.length; x++) { layer1Weight2Vector[x] = 2.0f * randomGenerator.nextFloat() - 1.0f; } for (int x = 0; x < layer2Weight1Vector.length; x++) { layer2Weight1Vector[x] = 2.0f * randomGenerator.nextFloat() - 1.0f; } layer2Weight2 = 2.0f * randomGenerator.nextFloat() - 1.0f; } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(new JFrame(), "Error details: /n" + e.getMessage(), "ERROR DURING LOADING DATA [GPU MODE]", JOptionPane.ERROR_MESSAGE); } } /** * In this methods the kernel code is represented as String and compiled * using KernelLauncher class in jcudaUtils zip file. */ public void compileKernels() { try { // Explanation of partial sums calculation. // To get the outputLayer output we have to add hidden layers output multiplied by layer2 weights. // We know that for every block we have 512 such values that must be aggregated. // Thus partial sum is a sum of 512 such values in a block. // So suppose we have 30 blocks launched then we have 30 partial sums. // In this kernel we calculate partial sums using striding technique and store them on global // memory. Host code will add this partial sums and then the product of augmented input with // its corresponding weight. So finally we get our outputLayer output which will then undergo // exp operation (see host code in trainANN() method of this class). String computeLayer2OutputAndPartialSumsForTrainingOutcome = "" + " extern \"C\" " + "\n" + " __global__ void computeLayer2OutputAndPartialSumsForTrainingOutcome( " + "\n" + " float* communicationDataArrayArg, " + "\n" + " float* layer1Weight1VectorArg, " + "\n" + " float* layer1Weight2VectorArg, " + "\n" + " float* layer2Weight1VectorArg, " + "\n" + " float* layer2OutputVectorArg, " + "\n" + " float* tempArrayToStorePartialSumsArg) " + "\n" + " { " + "\n" + " __shared__ float partialSums[" + threadsPerBlock + "]; " + "\n" + " unsigned int tid = threadIdx.x; " + "\n" + " unsigned int bid = blockIdx.x; " + "\n" + " unsigned int index = bid*blockDim.x+tid; " + "\n" + " float layer2Output; " + "\n" + " layer2Output=communicationDataArrayArg[0]* " + "\n" + " layer1Weight1VectorArg[index]-layer1Weight2VectorArg[index]; " + "\n" + " layer2Output=2.0f/(1.0f+expf(-layer2Output))-1.0f; " + "\n" + " partialSums[tid]=layer2Output*layer2Weight1VectorArg[index]; " + "\n" + " layer2OutputVectorArg[index]=layer2Output; " + "\n" + " for(index = " + (threadsPerBlock / 2) + "; index>=1 ; index=index/2){ " + "\n" + " __syncthreads(); " + "\n" + " if(tid<index)partialSums[tid]+=partialSums[tid+index]; " + "\n" + " } " + "\n" + " tempArrayToStorePartialSumsArg[bid]=partialSums[0]; " + "\n" + " }; "; computeLayer2OutputAndPartialSumsForTrainingOutcomeKernelLauncher = KernelLauncher.compile(computeLayer2OutputAndPartialSumsForTrainingOutcome, "computeLayer2OutputAndPartialSumsForTrainingOutcome"); computeLayer2OutputAndPartialSumsForTrainingOutcomeKernelLauncher.setGridSize(numberOfBlocks, 1); computeLayer2OutputAndPartialSumsForTrainingOutcomeKernelLauncher.setBlockSize(threadsPerBlock, 1, 1); String computeDeltaLayer1Vector = "" + " extern \"C\" " + "\n" + " __global__ void computeDeltaLayer1Vector( " + "\n" + " float* deltaLayer1VectorArg, " + "\n" + " float* communicationDataArrayArg, " + "\n" + " float* layer2Weight1VectorArg, " + "\n" + " float* layer2OutputVectorArg) " + "\n" + " { " + "\n" + " unsigned int index = blockIdx.x*blockDim.x+threadIdx.x; " + "\n" + " float temp0=communicationDataArrayArg[3]*layer2Weight1VectorArg[index]; " + "\n" + " float temp1=layer2OutputVectorArg[index]; " + "\n" + " deltaLayer1VectorArg[index]=0.5f * (1.0f - temp1 * temp1) * temp0; " + "\n" + " }; "; computeDeltaLayer1VectorKernelLauncher = KernelLauncher.compile(computeDeltaLayer1Vector, "computeDeltaLayer1Vector"); computeDeltaLayer1VectorKernelLauncher.setGridSize(numberOfBlocks, 1); computeDeltaLayer1VectorKernelLauncher.setBlockSize(threadsPerBlock, 1, 1); String modifyWeights = "" + " extern \"C\" " + "\n" + " __global__ void modifyWeights( " + "\n" + " float* communicationDataArrayArg, " + "\n" + " float* deltaLayer1VectorArg, " + "\n" + " float* layer1Weight1VectorArg, " + "\n" + " float* layer1Weight2VectorArg, " + "\n" + " float* layer2Weight1VectorArg, " + "\n" + " float* layer2OutputVectorArg) " + "\n" + " { " + "\n" + " unsigned int index = blockIdx.x*blockDim.x+threadIdx.x; " + "\n" + " float learningConstant = communicationDataArrayArg[2]; " + "\n" + " float temp0 = learningConstant* " + "\n" + " deltaLayer1VectorArg[index]*communicationDataArrayArg[0]; " + "\n" + " layer2Weight1VectorArg[index]+=learningConstant " + "\n" + " *communicationDataArrayArg[3] " + "\n" + " *layer2OutputVectorArg[index]; " + "\n" + " layer1Weight1VectorArg[index]+=temp0; " + "\n" + " layer1Weight2VectorArg[index]+=temp0; " + "\n" + " }; "; modifyWeightsKernelLauncher = KernelLauncher.compile(modifyWeights, "modifyWeights"); modifyWeightsKernelLauncher.setGridSize(numberOfBlocks, 1); modifyWeightsKernelLauncher.setBlockSize(threadsPerBlock, 1, 1); } catch (Error e) { e.printStackTrace(); JOptionPane.showMessageDialog(new JFrame(), "Please make sure that required JCuda drivers(JCuda 3.1 drivers for windows) are accessible.\n" + "You can place them in bin folder inside Java installation directory.\n" + "Try any sample JCuda program to check your configuration.\n\n\n" + e.getMessage(), "CAN'T COMPILE THE KERNELS", JOptionPane.ERROR_MESSAGE); } } /** * This methods allocate memory and copies data to GPU which will be used by Kernel. */ public void allocateMemoryAndCopyDataToGpgpu() { try { JCudaDriver.cuMemAlloc(communicationDataArrayDevicePointer, 5 * Sizeof.FLOAT); JCudaDriver.cuMemAlloc(layer1Weight1VectorDevicePointer, layer2Neurons * Sizeof.FLOAT); JCudaDriver.cuMemAlloc(layer1Weight2VectorDevicePointer, layer2Neurons * Sizeof.FLOAT); JCudaDriver.cuMemAlloc(layer2Weight1VectorDevicePointer, layer2Neurons * Sizeof.FLOAT); JCudaDriver.cuMemAlloc(layer2OutputVectorDevicePointer, layer2Neurons * Sizeof.FLOAT); JCudaDriver.cuMemAlloc(deltaLayer1VectorDevicePointer, layer2Neurons * Sizeof.FLOAT); JCudaDriver.cuMemAlloc(tempArrayToStorePartialSumsDevicePointer, numberOfBlocks * Sizeof.FLOAT); JCudaDriver.cuMemcpyHtoD(layer1Weight1VectorDevicePointer, Pointer.to(layer1Weight1Vector), layer2Neurons * Sizeof.FLOAT); JCudaDriver.cuMemcpyHtoD(layer1Weight2VectorDevicePointer, Pointer.to(layer1Weight2Vector), layer2Neurons * Sizeof.FLOAT); JCudaDriver.cuMemcpyHtoD(layer2Weight1VectorDevicePointer, Pointer.to(layer2Weight1Vector), layer2Neurons * Sizeof.FLOAT); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(new JFrame(), "Error details:\n" + e.getMessage(), "ERROR DURING COPYING DATA TO GPGPU", JOptionPane.ERROR_MESSAGE); } } /** * This method has a mixture of CPU code and GPU code call. * Sequential code is executed on host whereas parallel code execution is * done with help of kernel calls on GPU. * Such combination helps increase performance. * See TrainANN class for more explanation. * @param learningConstantArg * @param javaTrainingThreadTask */ @Override public void trainANN(float learningConstantArg, JavaTrainingThreadTask javaTrainingThreadTask) { try { this.currentError = 0.0f; int patternCount = -1; // iterations for all patterns while (++patternCount < numberOfInputPatterns) { // break training if user clicks stop button if (javaTrainingThreadTask.isTrainingPaused == true) { break; } // communicating details to GPU communicationDataArray[0] = teacherInputArray[patternCount]; communicationDataArray[1] = teacherOutputArray[patternCount]; communicationDataArray[2] = learningConstantArg; JCudaDriver.cuMemcpyHtoD(communicationDataArrayDevicePointer, Pointer.to(communicationDataArray), Sizeof.FLOAT * communicationDataArray.length); // computing hidden layer output done by kernel call. // computing partial sums (for more info see the kernel in compileKernels() method) computeLayer2OutputAndPartialSumsForTrainingOutcomeKernelLauncher.call( communicationDataArrayDevicePointer, layer1Weight1VectorDevicePointer, layer1Weight2VectorDevicePointer, layer2Weight1VectorDevicePointer, layer2OutputVectorDevicePointer, tempArrayToStorePartialSumsDevicePointer); // getting the partial sums for hidden layer float[] partialSumsFromBlock = new float[numberOfBlocks]; JCudaDriver.cuMemcpyDtoH(Pointer.to(partialSumsFromBlock), tempArrayToStorePartialSumsDevicePointer, Sizeof.FLOAT * numberOfBlocks); // calculating output layer output // This is done on host as most part is sequential. // If done on GPU the execution is slow. float currentOutput = 0.0f; for (float temp : partialSumsFromBlock) { currentOutput += temp; } currentOutput -= layer2Weight2; currentOutput = (float) (2.0f / (1.0f + Math.exp(-currentOutput)) - 1.0f); trainingOutcomeArray[patternCount] = currentOutput; // calculating deltaLayer2 which will be used to modify weights deltaLayer2 = (float) (0.5f * (teacherOutputArray[patternCount] - currentOutput) * (1.0f - Math.pow(currentOutput, 2))); // communicating deltaLayer2 value to GPU so that kernel to modify weights can use it. communicationDataArray[3] = deltaLayer2; JCudaDriver.cuMemcpyHtoD(communicationDataArrayDevicePointer, Pointer.to(communicationDataArray), Sizeof.FLOAT * communicationDataArray.length); // calculating deltaLayer1Vector on GPU computeDeltaLayer1VectorKernelLauncher.call( deltaLayer1VectorDevicePointer, communicationDataArrayDevicePointer, layer2Weight1VectorDevicePointer, layer2OutputVectorDevicePointer); // modify weights with help of kernel code modifyWeightsKernelLauncher.call( communicationDataArrayDevicePointer, deltaLayer1VectorDevicePointer, layer1Weight1VectorDevicePointer, layer1Weight2VectorDevicePointer, layer2Weight1VectorDevicePointer, layer2OutputVectorDevicePointer); // modify layer2Weight2 on host i.e. CPU layer2Weight2 -= learningConstantArg * deltaLayer2; } // calculating error for this iteration which is sum of errors that occurred for each pattern. for (int count = 0; count < numberOfInputPatterns; count++) { this.currentError = (float) (this.currentError + 0.5f * Math.pow(teacherOutputArray[count] - trainingOutcomeArray[count], 2)); } } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(new JFrame(), "Error details:/n" + e.getMessage(), "ERROR DURING TRAINING ANN [GPU MODE]", JOptionPane.ERROR_MESSAGE); } } /** * See TrainANN class for more explanation. * @return */ @Override public float[] getTrainingOutcome() { return this.trainingOutcomeArray; } /** * See TrainANN class for more explanation. * @return */ @Override public float getCurrentError() { return this.currentError; } /** * After training is entirely stopped call to this method will ensure that * allocated memory will be freed. */ public void freeGpgpuAfterTraining() { try { JCudaDriver.cuMemFree(communicationDataArrayDevicePointer); JCudaDriver.cuMemFree(layer1Weight1VectorDevicePointer); JCudaDriver.cuMemFree(layer1Weight2VectorDevicePointer); JCudaDriver.cuMemFree(layer2Weight1VectorDevicePointer); JCudaDriver.cuMemFree(layer2OutputVectorDevicePointer); JCudaDriver.cuMemFree(deltaLayer1VectorDevicePointer); JCudaDriver.cuMemFree(tempArrayToStorePartialSumsDevicePointer); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(new JFrame(), "Error details:/n" + e.getMessage(), "ERROR DURING FREEING GPGPU AFTER TRAINING", JOptionPane.ERROR_MESSAGE); } } }
Java
package annCode; import threadHandlers.JavaTrainingThreadTask; import java.util.Random; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * This class involves code that will execute code on CPU in sequential way. * It extends TrainANN abstract classes and implements its abstract method. * @author praveen_kulkarni */ public class TrainANNCpuMode extends TrainANN { /** * Stores teacher input and output for which ANN is to be trained */ private float[] teacherInputArray = new float[numberOfInputPatterns]; private float[] teacherOutputArray = new float[numberOfInputPatterns]; /** * Each training iteration will store the estimated output for current iteration in * trainingOutcomeArray. This helps us to view the small progress done by trainANN() method */ private float[] trainingOutcomeArray = new float[numberOfInputPatterns]; /** * Weights involved between input layer and hidden layer. * Instance member layer1Weight2Vector represents weights between augmented * input of input layer and hidden layer. */ private float[] layer1Weight1Vector = new float[layer2Neurons]; private float[] layer1Weight2Vector = new float[layer2Neurons]; /** * Weights involved between hidden layer and output layer. * Instance member layer2Weight2 represents weight between augmented input * of hidden layer and output layer. Only one such weight exists as * we have only one output neuron in output layer. */ private float[] layer2Weight1Vector = new float[layer2Neurons]; private float layer2Weight2; /** * Represents output of hidden layer. Changer for every iteration. */ private float[] layer2OutputVector = new float[layer2Neurons]; /** * Used in modifying layer 1 and layer 2 weights. * They depend on error calculated for current iteration, */ private float[] deltaLayer1Vector = new float[layer2Neurons]; private float deltaLayer2; /** * Holds error for current iteration. */ private float currentError = 0.0f; /** * See TrainANN class for more explanation. * @param teacherInputArray * @param teacherOutputArray */ @Override public void loadData(float[] teacherInput, float[] teacherOutput) { try { if(teacherInput!=null){ int count=0; for(float x : teacherInput){ this.teacherInputArray[count]=x; count++; } count=0; for(float x : teacherOutput){ this.teacherOutputArray[count]=x; count++; } } Random randomGenerator = new Random(System.currentTimeMillis()); for (int x = 0; x < layer1Weight1Vector.length; x++) { layer1Weight1Vector[x] = 2.0f * randomGenerator.nextFloat() - 1.0f; } for (int x = 0; x < layer1Weight2Vector.length; x++) { layer1Weight2Vector[x] = 2.0f * randomGenerator.nextFloat() - 1.0f; } for (int x = 0; x < layer2Weight1Vector.length; x++) { layer2Weight1Vector[x] = 2.0f * randomGenerator.nextFloat() - 1.0f; } layer2Weight2 = 2.0f * randomGenerator.nextFloat() - 1.0f; } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "ERROR DURING LOADING DATA [CPU MODE]", JOptionPane.ERROR_MESSAGE); } } /** * See TrainANN class for more explanation. * @param learningConstantArg * @param javaTrainingThreadTask */ @Override public void trainANN(float learningConstantArg, JavaTrainingThreadTask javaTrainingThreadTask) { try { this.currentError = 0.0f; int patternCount = -1; // iterations for all patterns while (++patternCount < numberOfInputPatterns) { // break training if user clicks stop button if(javaTrainingThreadTask.isTrainingPaused==true){ break; } // compte hidden layer output for (int count = 0; count < layer2Neurons; count++) { layer2OutputVector[count] = teacherInputArray[patternCount] * layer1Weight1Vector[count] - layer1Weight2Vector[count]; layer2OutputVector[count] = (float) (2.0f / (1.0f + Math.exp(-layer2OutputVector[count])) - 1.0f); } // computing the output layer output for current pattern trainingOutcomeArray[patternCount]=0.0f; for (int count = 0; count < layer2Neurons; count++) { trainingOutcomeArray[patternCount] += layer2OutputVector[count] * layer2Weight1Vector[count]; } trainingOutcomeArray[patternCount] -= layer2Weight2; trainingOutcomeArray[patternCount] = (float) (2.0f / (1.0f + Math.exp(-trainingOutcomeArray[patternCount])) - 1.0f); // calculating deltaLayer2 which will be used to modify weights deltaLayer2 = (float) (0.5f * (teacherOutputArray[patternCount] - trainingOutcomeArray[patternCount]) * (1.0f - Math.pow(trainingOutcomeArray[patternCount], 2))); // calculating deltaLayer1Vector for (int count = 0; count < layer2Neurons; count++) { float temp0 = deltaLayer2 * layer2Weight1Vector[count]; float temp1 = layer2OutputVector[count]; deltaLayer1Vector[count] = 0.5f * (1.0f - temp1 * temp1) * temp0; } // modyfying weights for (int count = 0; count < layer2Neurons; count++) { layer2Weight1Vector[count] += learningConstantArg * deltaLayer2 * layer2OutputVector[count]; float temp2 = learningConstantArg * deltaLayer1Vector[count] * teacherInputArray[patternCount]; layer1Weight1Vector[count] += temp2; layer1Weight2Vector[count] += temp2; } layer2Weight2 -= learningConstantArg * deltaLayer2; } // calculating error for this iteration which is sum of errors that occurred for each pattern. for (int count = 0; count < numberOfInputPatterns; count++) { this.currentError = (float) (this.currentError + 0.5f * Math.pow(teacherOutputArray[count] - trainingOutcomeArray[count], 2)); } } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "ERROR DURING TRAINING ANN [CPU MODE]", JOptionPane.ERROR_MESSAGE); } } /** * See TrainANN class for more explanation. * @return */ @Override public float[] getTrainingOutcome() { return this.trainingOutcomeArray; } /** * See TrainANN class for more explanation. * @return */ @Override public float getCurrentError() { return this.currentError; } }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.tesseract.android; import android.graphics.Bitmap; import android.graphics.Rect; import com.googlecode.leptonica.android.Pix; import com.googlecode.leptonica.android.Pixa; import com.googlecode.leptonica.android.ReadFile; import java.io.File; /** * Java interface for the Tesseract OCR engine. Does not implement all available * JNI methods, but does implement enough to be useful. Comments are adapted * from original Tesseract source. * * @author alanv@google.com (Alan Viverette) */ public class TessBaseAPI { /** * Used by the native implementation of the class. */ private int mNativeData; static { System.loadLibrary("lept"); System.loadLibrary("tess"); nativeClassInit(); } public static final class PageSegMode { /** Orientation and script detection only. */ public static final int PSM_OSD_ONLY = 0; /** * Automatic page segmentation with orientation and script detection. * (OSD) */ public static final int PSM_AUTO_OSD = 1; /** Automatic page segmentation, but no OSD, or OCR. */ public static final int PSM_AUTO_ONLY = 2; /** Fully automatic page segmentation, but no OSD. */ public static final int PSM_AUTO = 3; /** Assume a single column of text of variable sizes. */ public static final int PSM_SINGLE_COLUMN = 4; /** Assume a single uniform block of vertically aligned text. */ public static final int PSM_SINGLE_BLOCK_VERT_TEXT = 5; /** Assume a single uniform block of text. (Default.) */ public static final int PSM_SINGLE_BLOCK = 6; /** Treat the image as a single text line. */ public static final int PSM_SINGLE_LINE = 7; /** Treat the image as a single word. */ public static final int PSM_SINGLE_WORD = 8; /** Treat the image as a single word in a circle. */ public static final int PSM_CIRCLE_WORD = 9; /** Treat the image as a single character. */ public static final int PSM_SINGLE_CHAR = 10; /** Number of enum entries. */ public static final int PSM_COUNT = 11; } /** * Elements of the page hierarchy, used in {@link ResultIterator} to provide * functions that operate on each level without having to have 5x as many * functions. * <p> * NOTE: At present {@link #RIL_PARA} and {@link #RIL_BLOCK} are equivalent * as there is no paragraph internally yet. */ public static final class PageIteratorLevel { /** Block of text/image/separator line. */ public static final int RIL_BLOCK = 0; /** Paragraph within a block. */ public static final int RIL_PARA = 1; /** Line within a paragraph. */ public static final int RIL_TEXTLINE = 2; /** Word within a text line. */ public static final int RIL_WORD = 3; /** Symbol/character within a word. */ public static final int RIL_SYMBOL = 4; } /** Default accuracy versus speed mode. */ public static final int AVS_FASTEST = 0; /** Slowest and most accurate mode. */ public static final int AVS_MOST_ACCURATE = 100; /** Whitelist of characters to recognize. */ public static final String VAR_CHAR_WHITELIST = "tessedit_char_whitelist"; /** Blacklist of characters to not recognize. */ public static final String VAR_CHAR_BLACKLIST = "tessedit_char_blacklist"; /** Accuracy versus speed setting. */ public static final String VAR_ACCURACYVSPEED = "tessedit_accuracyvspeed"; /** * Constructs an instance of TessBaseAPI. */ public TessBaseAPI() { nativeConstruct(); } /** * Called by the GC to clean up the native data that we set up when we * construct the object. */ @Override protected void finalize() throws Throwable { try { nativeFinalize(); } finally { super.finalize(); } } /** * Initializes the Tesseract engine with a specified language model. Returns * <code>true</code> on success. * <p> * Instances are now mostly thread-safe and totally independent, but some * global parameters remain. Basically it is safe to use multiple * TessBaseAPIs in different threads in parallel, UNLESS you use SetVariable * on some of the Params in classify and textord. If you do, then the effect * will be to change it for all your instances. * <p> * The datapath must be the name of the parent directory of tessdata and * must end in / . Any name after the last / will be stripped. The language * is (usually) an ISO 639-3 string or <code>null</code> will default to * eng. It is entirely safe (and eventually will be efficient too) to call * Init multiple times on the same instance to change language, or just to * reset the classifier. * <p> * <b>WARNING:</b> On changing languages, all Tesseract parameters are reset * back to their default values. (Which may vary between languages.) * <p> * If you have a rare need to set a Variable that controls initialization * for a second call to Init you should explicitly call End() and then use * SetVariable before Init. This is only a very rare use case, since there * are very few uses that require any parameters to be set before Init. * * @param datapath the parent directory of tessdata ending in a forward * slash * @param language (optional) an ISO 639-3 string representing the language * @return <code>true</code> on success */ public boolean init(String datapath, String language) { if (datapath == null) { throw new IllegalArgumentException("Data path must not be null!"); } if (!datapath.endsWith(File.separator)) { datapath += File.separator; } File tessdata = new File(datapath + "tessdata"); if (!tessdata.exists() || !tessdata.isDirectory()) { throw new IllegalArgumentException("Data path must contain subfolder tessdata!"); } return nativeInit(datapath, language); } /** * Frees up recognition results and any stored image data, without actually * freeing any recognition data that would be time-consuming to reload. * Afterwards, you must call SetImage or SetRectangle before doing any * Recognize or Get* operation. */ public void clear() { nativeClear(); } /** * Closes down tesseract and free up all memory. End() is equivalent to * destructing and reconstructing your TessBaseAPI. * <p> * Once End() has been used, none of the other API functions may be used * other than Init and anything declared above it in the class definition. */ public void end() { nativeEnd(); } /** * Set the value of an internal "variable" (of either old or new types). * Supply the name of the variable and the value as a string, just as you * would in a config file. * <p> * Example: * <code>setVariable(VAR_TESSEDIT_CHAR_BLACKLIST, "xyz"); to ignore x, y and z. * setVariable(VAR_BLN_NUMERICMODE, "1"); to set numeric-only mode. * </code> * <p> * setVariable() may be used before open(), but settings will revert to * defaults on close(). * * @param var name of the variable * @param value value to set * @return false if the name lookup failed */ public boolean setVariable(String var, String value) { return nativeSetVariable(var, value); } /** * Sets the page segmentation mode. This controls how much processing the * OCR engine will perform before recognizing text. * * @param mode the page segmentation mode to set */ public void setPageSegMode(int mode) { nativeSetPageSegMode(mode); } /** * Sets debug mode. This controls how much information is displayed in the * log during recognition. * * @param enabled <code>true</code> to enable debugging mode */ public void setDebug(boolean enabled) { nativeSetDebug(enabled); } /** * Restricts recognition to a sub-rectangle of the image. Call after * SetImage. Each SetRectangle clears the recogntion results so multiple * rectangles can be recognized with the same image. * * @param rect the bounding rectangle */ public void setRectangle(Rect rect) { setRectangle(rect.left, rect.top, rect.width(), rect.height()); } /** * Restricts recognition to a sub-rectangle of the image. Call after * SetImage. Each SetRectangle clears the recogntion results so multiple * rectangles can be recognized with the same image. * * @param left the left bound * @param top the right bound * @param width the width of the bounding box * @param height the height of the bounding box */ public void setRectangle(int left, int top, int width, int height) { nativeSetRectangle(left, top, width, height); } /** * Provides an image for Tesseract to recognize. * * @param file absolute path to the image file */ public void setImage(File file) { Pix image = ReadFile.readFile(file); if (image == null) { throw new RuntimeException("Failed to read image file"); } nativeSetImagePix(image.getNativePix()); } /** * Provides an image for Tesseract to recognize. Does not copy the image * buffer. The source image must persist until after Recognize or * GetUTF8Chars is called. * * @param bmp bitmap representation of the image */ public void setImage(Bitmap bmp) { Pix image = ReadFile.readBitmap(bmp); if (image == null) { throw new RuntimeException("Failed to read bitmap"); } nativeSetImagePix(image.getNativePix()); } /** * Provides a Leptonica pix format image for Tesseract to recognize. Clones * the pix object. The source image may be destroyed immediately after * SetImage is called, but its contents may not be modified. * * @param image Leptonica pix representation of the image */ public void setImage(Pix image) { nativeSetImagePix(image.getNativePix()); } /** * Provides an image for Tesseract to recognize. Copies the image buffer. * The source image may be destroyed immediately after SetImage is called. * SetImage clears all recognition results, and sets the rectangle to the * full image, so it may be followed immediately by a GetUTF8Text, and it * will automatically perform recognition. * * @param imagedata byte representation of the image * @param width image width * @param height image height * @param bpp bytes per pixel * @param bpl bytes per line */ public void setImage(byte[] imagedata, int width, int height, int bpp, int bpl) { nativeSetImageBytes(imagedata, width, height, bpp, bpl); } /** * The recognized text is returned as a String which is coded as UTF8. * * @return the recognized text */ public String getUTF8Text() { // Trim because the text will have extra line breaks at the end String text = nativeGetUTF8Text(); return text.trim(); } public Pixa getRegions() { int pixa = nativeGetRegions(); if (pixa == 0) { return null; } return new Pixa(pixa, 0, 0); } public Pixa getWords() { int pixa = nativeGetWords(); if (pixa == 0) { return null; } return new Pixa(pixa, 0, 0); } /** * Returns the mean confidence of text recognition. * * @return the mean confidence */ public int meanConfidence() { return nativeMeanConfidence(); } /** * Returns all word confidences (between 0 and 100) in an array. The number * of confidences should correspond to the number of space-delimited words * in GetUTF8Text(). * * @return an array of word confidences (between 0 and 100) for each * space-delimited word returned by GetUTF8Text() */ public int[] wordConfidences() { int[] conf = nativeWordConfidences(); // We shouldn't return null confidences if (conf == null) { conf = new int[0]; } return conf; } public ResultIterator getResultIterator() { int nativeResultIterator = nativeGetResultIterator(); if (nativeResultIterator == 0) { return null; } return new ResultIterator(nativeResultIterator); } // ****************** // * Native methods * // ****************** /** * Initializes static native data. Must be called on object load. */ private static native void nativeClassInit(); /** * Initializes native data. Must be called on object construction. */ private native void nativeConstruct(); /** * Finalizes native data. Must be called on object destruction. */ private native void nativeFinalize(); private native boolean nativeInit(String datapath, String language); private native void nativeClear(); private native void nativeEnd(); private native void nativeSetImageBytes( byte[] imagedata, int width, int height, int bpp, int bpl); private native void nativeSetImagePix(int nativePix); private native void nativeSetRectangle(int left, int top, int width, int height); private native String nativeGetUTF8Text(); private native int nativeGetRegions(); private native int nativeGetWords(); private native int nativeMeanConfidence(); private native int[] nativeWordConfidences(); private native boolean nativeSetVariable(String var, String value); private native void nativeSetDebug(boolean debug); private native void nativeSetPageSegMode(int mode); private native int nativeGetResultIterator(); }
Java
/* * Copyright (C) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.tesseract.android; import com.googlecode.tesseract.android.TessBaseAPI.PageIteratorLevel; public class PageIterator { static { System.loadLibrary("lept"); System.loadLibrary("tess"); } /** Pointer to native page iterator. */ private final int mNativePageIterator; /* package */PageIterator(int nativePageIterator) { mNativePageIterator = nativePageIterator; } /** * Resets the iterator to point to the start of the page. */ public void begin() { nativeBegin(mNativePageIterator); } /** * Moves to the start of the next object at the given level in the page * hierarchy, and returns false if the end of the page was reached. * <p> * NOTE that {@link PageIteratorLevel#RIL_SYMBOL} will skip non-text blocks, * but all other {@link PageIteratorLevel} level values will visit each * non-text block once. Think of non text blocks as containing a single * para, with a single line, with a single imaginary word. * <p> * Calls to {@link #next} with different levels may be freely intermixed. * <p> * This function iterates words in right-to-left scripts correctly, if the * appropriate language has been loaded into Tesseract. * * @param level the page iterator level. See {@link PageIteratorLevel}. * @return {@code false} if the end of the page was reached, {@code true} * otherwise. */ public boolean next(int level) { return nativeNext(mNativePageIterator, level); } private static native void nativeBegin(int nativeIterator); private static native boolean nativeNext(int nativeIterator, int level); }
Java
/* * Copyright (C) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.tesseract.android; import com.googlecode.tesseract.android.TessBaseAPI.PageIteratorLevel; /** * Java interface for the ResultIterator. Does not implement all available JNI * methods, but does implement enough to be useful. Comments are adapted from * original Tesseract source. * * @author alanv@google.com (Alan Viverette) */ public class ResultIterator extends PageIterator { static { System.loadLibrary("lept"); System.loadLibrary("tess"); } /** Pointer to native result iterator. */ private final int mNativeResultIterator; /* package */ResultIterator(int nativeResultIterator) { super(nativeResultIterator); mNativeResultIterator = nativeResultIterator; } /** * Returns the text string for the current object at the given level. * * @param level the page iterator level. See {@link PageIteratorLevel}. * @return the text string for the current object at the given level. */ public String getUTF8Text(int level) { return nativeGetUTF8Text(mNativeResultIterator, level); } /** * Returns the mean confidence of the current object at the given level. The * number should be interpreted as a percent probability (0-100). * * @param level the page iterator level. See {@link PageIteratorLevel}. * @return the mean confidence of the current object at the given level. */ public float confidence(int level) { return nativeConfidence(mNativeResultIterator, level); } private static native String nativeGetUTF8Text(int nativeResultIterator, int level); private static native float nativeConfidence(int nativeResultIterator, int level); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; import android.graphics.Rect; /** * Java representation of a native Leptonica PIX object. * * @author alanv@google.com (Alan Viverette) */ public class Pix { static { System.loadLibrary("lept"); } /** Index of the image width within the dimensions array. */ public static final int INDEX_W = 0; /** Index of the image height within the dimensions array. */ public static final int INDEX_H = 1; /** Index of the image bit-depth within the dimensions array. */ public static final int INDEX_D = 2; /** Package-accessible pointer to native pix. */ final int mNativePix; private boolean mRecycled; /** * Creates a new Pix wrapper for the specified native PIX object. Never call * this twice on the same native pointer, because finalize() will attempt to * free native memory twice. * * @param nativePix A pointer to the native PIX object. */ public Pix(int nativePix) { mNativePix = nativePix; mRecycled = false; } public Pix(int width, int height, int depth) { if (width <= 0 || height <= 0) { throw new IllegalArgumentException("Pix width and height must be > 0"); } else if (depth != 1 && depth != 2 && depth != 4 && depth != 8 && depth != 16 && depth != 24 && depth != 32) { throw new IllegalArgumentException("Depth must be one of 1, 2, 4, 8, 16, or 32"); } mNativePix = nativeCreatePix(width, height, depth); mRecycled = false; } /** * Returns a pointer to the native Pix object. This is used by native code * and is only valid within the same process in which the Pix was created. * * @return a native pointer to the Pix object */ public int getNativePix() { return mNativePix; } /** * Return the raw bytes of the native PIX object. You can reconstruct the * Pix from this data using createFromPix(). * * @return a copy of this PIX object's raw data */ public byte[] getData() { int size = nativeGetDataSize(mNativePix); byte[] buffer = new byte[size]; if (!nativeGetData(mNativePix, buffer)) { throw new RuntimeException("native getData failed"); } return buffer; } /** * Returns an array of this image's dimensions. See Pix.INDEX_* for indices. * * @return an array of this image's dimensions or <code>null</code> on * failure */ public int[] getDimensions() { int[] dimensions = new int[4]; if (getDimensions(dimensions)) { return dimensions; } return null; } /** * Fills an array with this image's dimensions. The array must be at least 3 * elements long. * * @param dimensions An integer array with at least three elements. * @return <code>true</code> on success */ public boolean getDimensions(int[] dimensions) { return nativeGetDimensions(mNativePix, dimensions); } /** * Returns a clone of this Pix. This does NOT create a separate copy, just a * new pointer that can be recycled without affecting other clones. * * @return a clone (shallow copy) of the Pix */ @Override public Pix clone() { int nativePix = nativeClone(mNativePix); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } /** * Returns a deep copy of this Pix that can be modified without affecting * the original Pix. * * @return a copy of the Pix */ public Pix copy() { int nativePix = nativeCopy(mNativePix); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } /** * Inverts this Pix in-place. * * @return <code>true</code> on success */ public boolean invert() { return nativeInvert(mNativePix); } /** * Releases resources and frees any memory associated with this Pix. You may * not modify or access the pix after calling this method. */ public void recycle() { if (!mRecycled) { nativeDestroy(mNativePix); mRecycled = true; } } @Override protected void finalize() throws Throwable { recycle(); super.finalize(); } /** * Creates a new Pix from raw Pix data obtained from getData(). * * @param pixData Raw pix data obtained from getData(). * @param width The width of the original Pix. * @param height The height of the original Pix. * @param depth The bit-depth of the original Pix. * @return a new Pix or <code>null</code> on error */ public static Pix createFromPix(byte[] pixData, int width, int height, int depth) { int nativePix = nativeCreateFromData(pixData, width, height, depth); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } /** * Returns a Rect with the width and height of this Pix. * * @return a Rect with the width and height of this Pix */ public Rect getRect() { int w = getWidth(); int h = getHeight(); return new Rect(0, 0, w, h); } /** * Returns the width of this Pix. * * @return the width of this Pix */ public int getWidth() { return nativeGetWidth(mNativePix); } /** * Returns the height of this Pix. * * @return the height of this Pix */ public int getHeight() { return nativeGetHeight(mNativePix); } /** * Returns the depth of this Pix. * * @return the depth of this Pix */ public int getDepth() { return nativeGetDepth(mNativePix); } /** * Returns the {@link android.graphics.Color} at the specified location. * * @param x The x coordinate (0...width-1) of the pixel to return. * @param y The y coordinate (0...height-1) of the pixel to return. * @return The argb {@link android.graphics.Color} at the specified * coordinate. * @throws IllegalArgumentException If x, y exceeds the image bounds. */ public int getPixel(int x, int y) { if (x < 0 || x >= getWidth()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } else if (y < 0 || y >= getHeight()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } return nativeGetPixel(mNativePix, x, y); } /** * Sets the {@link android.graphics.Color} at the specified location. * * @param x The x coordinate (0...width-1) of the pixel to set. * @param y The y coordinate (0...height-1) of the pixel to set. * @param color The argb {@link android.graphics.Color} to set at the * specified coordinate. * @throws IllegalArgumentException If x, y exceeds the image bounds. */ public void setPixel(int x, int y, int color) { if (x < 0 || x >= getWidth()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } else if (y < 0 || y >= getHeight()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } nativeSetPixel(mNativePix, x, y, color); } // *************** // * NATIVE CODE * // *************** private static native int nativeCreatePix(int w, int h, int d); private static native int nativeCreateFromData(byte[] data, int w, int h, int d); private static native boolean nativeGetData(int nativePix, byte[] data); private static native int nativeGetDataSize(int nativePix); private static native int nativeClone(int nativePix); private static native int nativeCopy(int nativePix); private static native boolean nativeInvert(int nativePix); private static native void nativeDestroy(int nativePix); private static native boolean nativeGetDimensions(int nativePix, int[] dimensions); private static native int nativeGetWidth(int nativePix); private static native int nativeGetHeight(int nativePix); private static native int nativeGetDepth(int nativePix); private static native int nativeGetPixel(int nativePix, int x, int y); private static native void nativeSetPixel(int nativePix, int x, int y, int color); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.File; /** * Image input and output methods. * * @author alanv@google.com (Alan Viverette) */ public class ReadFile { static { System.loadLibrary("lept"); } /** * Creates a 32bpp Pix object from encoded data. Supported formats are BMP * and JPEG. * * @param encodedData JPEG or BMP encoded byte data. * @return a 32bpp Pix object */ public static Pix readMem(byte[] encodedData) { if (encodedData == null) throw new IllegalArgumentException("Image data byte array must be non-null"); final BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inPreferredConfig = Bitmap.Config.ARGB_8888; final Bitmap bmp = BitmapFactory.decodeByteArray(encodedData, 0, encodedData.length, opts); final Pix pix = readBitmap(bmp); bmp.recycle(); return pix; } /** * Creates an 8bpp Pix object from raw 8bpp grayscale pixels. * * @param pixelData 8bpp grayscale pixel data. * @param width The width of the input image. * @param height The height of the input image. * @return an 8bpp Pix object */ public static Pix readBytes8(byte[] pixelData, int width, int height) { if (pixelData == null) throw new IllegalArgumentException("Byte array must be non-null"); if (width <= 0) throw new IllegalArgumentException("Image width must be greater than 0"); if (height <= 0) throw new IllegalArgumentException("Image height must be greater than 0"); if (pixelData.length < width * height) throw new IllegalArgumentException("Array length does not match dimensions"); int nativePix = nativeReadBytes8(pixelData, width, height); if (nativePix == 0) throw new RuntimeException("Failed to read pix from memory"); return new Pix(nativePix); } /** * Replaces the bytes in an 8bpp Pix object with raw grayscale 8bpp pixels. * Width and height be identical to the input Pix. * * @param pixs The Pix whose bytes will be replaced. * @param pixelData 8bpp grayscale pixel data. * @param width The width of the input image. * @param height The height of the input image. * @return an 8bpp Pix object */ public static boolean replaceBytes8(Pix pixs, byte[] pixelData, int width, int height) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (pixelData == null) throw new IllegalArgumentException("Byte array must be non-null"); if (width <= 0) throw new IllegalArgumentException("Image width must be greater than 0"); if (height <= 0) throw new IllegalArgumentException("Image height must be greater than 0"); if (pixelData.length < width * height) throw new IllegalArgumentException("Array length does not match dimensions"); if (pixs.getWidth() != width) throw new IllegalArgumentException("Source pix width does not match image width"); if (pixs.getHeight() != height) throw new IllegalArgumentException("Source pix width does not match image width"); return nativeReplaceBytes8(pixs.mNativePix, pixelData, width, height); } /** * Creates a Pixa object from encoded files in a directory. Supported * formats are BMP and JPEG. * * @param dir The directory containing the files. * @param prefix The prefix of the files to load into a Pixa. * @return a Pixa object containing one Pix for each file */ public static Pixa readFiles(File dir, String prefix) { if (dir == null) throw new IllegalArgumentException("Directory must be non-null"); if (!dir.exists()) throw new IllegalArgumentException("Directory does not exist"); if (!dir.canRead()) throw new IllegalArgumentException("Cannot read directory"); // TODO: Remove or fix this. throw new RuntimeException("readFiles() is not current supported"); } /** * Creates a Pix object from encoded file data. Supported formats are BMP * and JPEG. * * @param file The JPEG or BMP-encoded file to read in as a Pix. * @return a Pix object */ public static Pix readFile(File file) { if (file == null) throw new IllegalArgumentException("File must be non-null"); if (!file.exists()) throw new IllegalArgumentException("File does not exist"); if (!file.canRead()) throw new IllegalArgumentException("Cannot read file"); final BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inPreferredConfig = Bitmap.Config.ARGB_8888; final Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath(), opts); final Pix pix = readBitmap(bmp); bmp.recycle(); return pix; } /** * Creates a Pix object from Bitmap data. Currently supports only * ARGB_8888-formatted bitmaps. * * @param bmp The Bitmap object to convert to a Pix. * @return a Pix object */ public static Pix readBitmap(Bitmap bmp) { if (bmp == null) throw new IllegalArgumentException("Bitmap must be non-null"); if (bmp.getConfig() != Bitmap.Config.ARGB_8888) throw new IllegalArgumentException("Bitmap config must be ARGB_8888"); int nativePix = nativeReadBitmap(bmp); if (nativePix == 0) throw new RuntimeException("Failed to read pix from bitmap"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeReadMem(byte[] data, int size); private static native int nativeReadBytes8(byte[] data, int w, int h); private static native boolean nativeReplaceBytes8(int nativePix, byte[] data, int w, int h); private static native int nativeReadFiles(String dirname, String prefix); private static native int nativeReadFile(String filename); private static native int nativeReadBitmap(Bitmap bitmap); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Wrapper for Leptonica's native BOX. * * @author alanv@google.com (Alan Viverette) */ public class Box { static { System.loadLibrary("lept"); } /** The index of the X coordinate within the geometry array. */ public static final int INDEX_X = 0; /** The index of the Y coordinate within the geometry array. */ public static final int INDEX_Y = 1; /** The index of the width within the geometry array. */ public static final int INDEX_W = 2; /** The index of the height within the geometry array. */ public static final int INDEX_H = 3; /** * A pointer to the native Box object. This is used internally by native * code. */ final int mNativeBox; private boolean mRecycled = false; /** * Creates a new Box wrapper for the specified native BOX. * * @param nativeBox A pointer to the native BOX. */ Box(int nativeBox) { mNativeBox = nativeBox; mRecycled = false; } /** * Creates a box with the specified geometry. All dimensions should be * non-negative and specified in pixels. * * @param x X-coordinate of the top-left corner of the box. * @param y Y-coordinate of the top-left corner of the box. * @param w Width of the box. * @param h Height of the box. */ public Box(int x, int y, int w, int h) { if (x < 0 || y < 0 || w < 0 || h < 0) { throw new IllegalArgumentException("All box dimensions must be non-negative"); } int nativeBox = nativeCreate(x, y, w, h); if (nativeBox == 0) { throw new OutOfMemoryError(); } mNativeBox = nativeBox; mRecycled = false; } /** * Returns the box's x-coordinate in pixels. * * @return The box's x-coordinate in pixels. */ public int getX() { return nativeGetX(mNativeBox); } /** * Returns the box's y-coordinate in pixels. * * @return The box's y-coordinate in pixels. */ public int getY() { return nativeGetY(mNativeBox); } /** * Returns the box's width in pixels. * * @return The box's width in pixels. */ public int getWidth() { return nativeGetWidth(mNativeBox); } /** * Returns the box's height in pixels. * * @return The box's height in pixels. */ public int getHeight() { return nativeGetHeight(mNativeBox); } /** * Returns an array containing the coordinates of this box. See INDEX_* * constants for indices. * * @return an array of box oordinates */ public int[] getGeometry() { int[] geometry = new int[4]; if (getGeometry(geometry)) { return geometry; } return null; } /** * Fills an array containing the coordinates of this box. See INDEX_* * constants for indices. * * @param geometry A 4+ element integer array to fill with coordinates. * @return <code>true</code> on success */ public boolean getGeometry(int[] geometry) { if (geometry.length < 4) { throw new IllegalArgumentException("Geometry array must be at least 4 elements long"); } return nativeGetGeometry(mNativeBox, geometry); } /** * Releases resources and frees any memory associated with this Box. */ public void recycle() { if (!mRecycled) { nativeDestroy(mNativeBox); mRecycled = true; } } @Override protected void finalize() throws Throwable { recycle(); super.finalize(); } // *************** // * NATIVE CODE * // *************** private static native int nativeCreate(int x, int y, int w, int h); private static native int nativeGetX(int nativeBox); private static native int nativeGetY(int nativeBox); private static native int nativeGetWidth(int nativeBox); private static native int nativeGetHeight(int nativeBox); private static native void nativeDestroy(int nativeBox); private static native boolean nativeGetGeometry(int nativeBox, int[] geometry); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Image bit-depth conversion methods. * * @author alanv@google.com (Alan Viverette) */ public class Convert { static { System.loadLibrary("lept"); } /** * Converts an image of any bit depth to 8-bit grayscale. * * @param pixs Source pix of any bit-depth. * @return a new Pix image or <code>null</code> on error */ public static Pix convertTo8(Pix pixs) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeConvertTo8(pixs.mNativePix); if (nativePix == 0) throw new RuntimeException("Failed to natively convert pix"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeConvertTo8(int nativePix); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; import android.graphics.Rect; import java.io.File; import java.util.ArrayList; import java.util.Iterator; /** * Java representation of a native PIXA object. This object contains multiple * PIX objects and their associated bounding BOX objects. * * @author alanv@google.com (Alan Viverette) */ public class Pixa implements Iterable<Pix> { static { System.loadLibrary("lept"); } /** A pointer to the native PIXA object. This is used internally by native code. */ final int mNativePixa; /** The specified width of this Pixa. */ final int mWidth; /** The specified height of this Pixa. */ final int mHeight; private boolean mRecycled; /** * Creates a new Pixa with the specified minimum capacity. The Pixa will * expand automatically as new Pix are added. * * @param size The minimum capacity of this Pixa. * @return a new Pixa or <code>null</code> on error */ public static Pixa createPixa(int size) { return createPixa(size, 0, 0); } /** * Creates a new Pixa with the specified minimum capacity. The Pixa will * expand automatically as new Pix are added. * <p> * If non-zero, the specified width and height will be used to specify the * bounds of output images. * * * @param size The minimum capacity of this Pixa. * @param width (Optional) The width of this Pixa, use 0 for default. * @param height (Optional) The height of this Pixa, use 0 for default. * @return a new Pixa or <code>null</code> on error */ public static Pixa createPixa(int size, int width, int height) { int nativePixa = nativeCreate(size); if (nativePixa == 0) { throw new OutOfMemoryError(); } return new Pixa(nativePixa, width, height); } /** * Creates a wrapper for the specified native Pixa pointer. * * @param nativePixa Native pointer to a PIXA object. * @param width The width of the PIXA. * @param height The height of the PIXA. */ public Pixa(int nativePixa, int width, int height) { mNativePixa = nativePixa; mWidth = width; mHeight = height; mRecycled = false; } /** * Returns a pointer to the native PIXA object. This is used by native code. * * @return a pointer to the native PIXA object */ public int getNativePixa() { return mNativePixa; } /** * Creates a shallow copy of this Pixa. Contained Pix are cloned, and the * resulting Pixa may be recycled separately from the original. * * @return a shallow copy of this Pixa */ public Pixa copy() { int nativePixa = nativeCopy(mNativePixa); if (nativePixa == 0) { throw new OutOfMemoryError(); } return new Pixa(nativePixa, mWidth, mHeight); } /** * Sorts this Pixa using the specified field and order. See * Constants.L_SORT_BY_* and Constants.L_SORT_INCREASING or * Constants.L_SORT_DECREASING. * * @param field The field to sort by. See Constants.L_SORT_BY_*. * @param order The order in which to sort. Must be either * Constants.L_SORT_INCREASING or Constants.L_SORT_DECREASING. * @return a sorted copy of this Pixa */ public Pixa sort(int field, int order) { int nativePixa = nativeSort(mNativePixa, field, order); if (nativePixa == 0) { throw new OutOfMemoryError(); } return new Pixa(nativePixa, mWidth, mHeight); } /** * Returns the number of elements in this Pixa. * * @return the number of elements in this Pixa */ public int size() { return nativeGetCount(mNativePixa); } /** * Recycles this Pixa and frees natively allocated memory. You may not * access or modify the Pixa after calling this method. * <p> * Any Pix obtained from this Pixa or copies of this Pixa will still be * accessible until they are explicitly recycled or finalized by the garbage * collector. */ public synchronized void recycle() { if (!mRecycled) { nativeDestroy(mNativePixa); mRecycled = true; } } @Override protected void finalize() throws Throwable { recycle(); super.finalize(); } /** * Merges the contents of another Pixa into this one. * * @param otherPixa * @return <code>true</code> on success */ public boolean join(Pixa otherPixa) { return nativeJoin(mNativePixa, otherPixa.mNativePixa); } /** * Adds a Pix to this Pixa. * * @param pix The Pix to add. * @param mode The mode in which to add this Pix, typically * Constants.L_CLONE. */ public void addPix(Pix pix, int mode) { nativeAddPix(mNativePixa, pix.mNativePix, mode); } /** * Adds a Box to this Pixa. * * @param box The Box to add. * @param mode The mode in which to add this Box, typically * Constants.L_CLONE. */ public void addBox(Box box, int mode) { nativeAddBox(mNativePixa, box.mNativeBox, mode); } /** * Adds a Pix and associated Box to this Pixa. * * @param pix The Pix to add. * @param box The Box to add. * @param mode The mode in which to add this Pix and Box, typically * Constants.L_CLONE. */ public void add(Pix pix, Box box, int mode) { nativeAdd(mNativePixa, pix.mNativePix, box.mNativeBox, mode); } /** * Returns the Box at the specified index, or <code>null</code> on error. * * @param index The index of the Box to return. * @return the Box at the specified index, or <code>null</code> on error */ public Box getBox(int index) { int nativeBox = nativeGetBox(mNativePixa, index); if (nativeBox == 0) { return null; } return new Box(nativeBox); } /** * Returns the Pix at the specified index, or <code>null</code> on error. * * @param index The index of the Pix to return. * @return the Pix at the specified index, or <code>null</code> on error */ public Pix getPix(int index) { int nativePix = nativeGetPix(mNativePixa, index); if (nativePix == 0) { return null; } return new Pix(nativePix); } /** * Returns the width of this Pixa, or 0 if one was not set when it was * created. * * @return the width of this Pixa, or 0 if one was not set when it was * created */ public int getWidth() { return mWidth; } /** * Returns the height of this Pixa, or 0 if one was not set when it was * created. * * @return the height of this Pixa, or 0 if one was not set when it was * created */ public int getHeight() { return mHeight; } /** * Returns a bounding Rect for this Pixa, which may be (0,0,0,0) if width * and height were not specified on creation. * * @return a bounding Rect for this Pixa */ public Rect getRect() { return new Rect(0, 0, mWidth, mHeight); } /** * Returns a bounding Rect for the Box at the specified index. * * @param index The index of the Box to get the bounding Rect of. * @return a bounding Rect for the Box at the specified index */ public Rect getBoxRect(int index) { int[] dimensions = getBoxGeometry(index); if (dimensions == null) { return null; } int x = dimensions[Box.INDEX_X]; int y = dimensions[Box.INDEX_Y]; int w = dimensions[Box.INDEX_W]; int h = dimensions[Box.INDEX_H]; Rect bound = new Rect(x, y, x + w, y + h); return bound; } /** * Returns a geometry array for the Box at the specified index. See * Box.INDEX_* for indices. * * @param index The index of the Box to get the geometry of. * @return a bounding Rect for the Box at the specified index */ public int[] getBoxGeometry(int index) { int[] dimensions = new int[4]; if (getBoxGeometry(index, dimensions)) { return dimensions; } return null; } /** * Fills an array with the geometry of the Box at the specified index. See * Box.INDEX_* for indices. * * @param index The index of the Box to get the geometry of. * @param dimensions The array to fill with Box geometry. Must be at least 4 * elements. * @return <code>true</code> on success */ public boolean getBoxGeometry(int index, int[] dimensions) { return nativeGetBoxGeometry(mNativePixa, index, dimensions); } /** * Returns an ArrayList of Box bounding Rects. * * @return an ArrayList of Box bounding Rects */ public ArrayList<Rect> getBoxRects() { final int pixaCount = nativeGetCount(mNativePixa); final int[] buffer = new int[4]; final ArrayList<Rect> rects = new ArrayList<Rect>(pixaCount); for (int i = 0; i < pixaCount; i++) { getBoxGeometry(i, buffer); final int x = buffer[Box.INDEX_X]; final int y = buffer[Box.INDEX_Y]; final Rect bound = new Rect(x, y, x + buffer[Box.INDEX_W], y + buffer[Box.INDEX_H]); rects.add(bound); } return rects; } /** * Replaces the Pix and Box at the specified index with the specified Pix * and Box, both of which may be recycled after calling this method. * * @param index The index of the Pix to replace. * @param pix The Pix to replace the existing Pix. * @param box The Box to replace the existing Box. */ public void replacePix(int index, Pix pix, Box box) { nativeReplacePix(mNativePixa, index, pix.mNativePix, box.mNativeBox); } /** * Merges the Pix at the specified indices and removes the Pix at the second * index. * * @param indexA The index of the first Pix. * @param indexB The index of the second Pix, which will be removed after * merging. */ public void mergeAndReplacePix(int indexA, int indexB) { nativeMergeAndReplacePix(mNativePixa, indexA, indexB); } /** * Writes the components of this Pix to a bitmap-formatted file using a * random color map. * * @param file The file to write to. * @return <code>true</code> on success */ public boolean writeToFileRandomCmap(File file) { return nativeWriteToFileRandomCmap(mNativePixa, file.getAbsolutePath(), mWidth, mHeight); } @Override public Iterator<Pix> iterator() { return new PixIterator(); } private class PixIterator implements Iterator<Pix> { private int mIndex; private PixIterator() { mIndex = 0; } @Override public boolean hasNext() { final int size = size(); return (size > 0 && mIndex < size); } @Override public Pix next() { return getPix(mIndex++); } @Override public void remove() { throw new UnsupportedOperationException(); } } // *************** // * NATIVE CODE * // *************** private static native int nativeCreate(int size); private static native int nativeCopy(int nativePixa); private static native int nativeSort(int nativePixa, int field, int order); private static native boolean nativeJoin(int nativePixa, int otherPixa); private static native int nativeGetCount(int nativePixa); private static native void nativeDestroy(int nativePixa); private static native void nativeAddPix(int nativePixa, int nativePix, int mode); private static native void nativeAddBox(int nativePixa, int nativeBox, int mode); private static native void nativeAdd(int nativePixa, int nativePix, int nativeBox, int mode); private static native boolean nativeWriteToFileRandomCmap( int nativePixa, String fileName, int width, int height); private static native void nativeReplacePix( int nativePixa, int index, int nativePix, int nativeBox); private static native void nativeMergeAndReplacePix(int nativePixa, int indexA, int indexB); private static native int nativeGetBox(int nativePix, int index); private static native int nativeGetPix(int nativePix, int index); private static native boolean nativeGetBoxGeometry(int nativePixa, int index, int[] dimensions); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; import android.graphics.Bitmap; import java.io.File; /** * @author alanv@google.com (Alan Viverette) */ public class WriteFile { static { System.loadLibrary("lept"); } /* Default JPEG quality */ public static final int DEFAULT_QUALITY = 85; /* Default JPEG progressive encoding */ public static final boolean DEFAULT_PROGRESSIVE = true; /** * Write an 8bpp Pix to a flat byte array. * * @param pixs The 8bpp source image. * @return a byte array where each byte represents a single 8-bit pixel */ public static byte[] writeBytes8(Pix pixs) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int size = pixs.getWidth() * pixs.getHeight(); if (pixs.getDepth() != 8) { Pix pix8 = Convert.convertTo8(pixs); pixs.recycle(); pixs = pix8; } byte[] data = new byte[size]; writeBytes8(pixs, data); return data; } /** * Write an 8bpp Pix to a flat byte array. * * @param pixs The 8bpp source image. * @param data A byte array large enough to hold the pixels of pixs. * @return the number of bytes written to data */ public static int writeBytes8(Pix pixs, byte[] data) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int size = pixs.getWidth() * pixs.getHeight(); if (data.length < size) throw new IllegalArgumentException("Data array must be large enough to hold image bytes"); int bytesWritten = nativeWriteBytes8(pixs.mNativePix, data); return bytesWritten; } /** * Writes all the images in a Pixa array to individual files using the * specified format. The output file extension will be determined by the * format. * <p> * Output file names will take the format <path>/<prefix><index>.<extension> * * @param pixas The source Pixa image array. * @param path The output directory. * @param prefix The prefix to give output files. * @param format The format to use for output files. * @return <code>true</code> on success */ public static boolean writeFiles(Pixa pixas, File path, String prefix, int format) { if (pixas == null) throw new IllegalArgumentException("Source pixa must be non-null"); if (path == null) throw new IllegalArgumentException("Destination path non-null"); if (prefix == null) throw new IllegalArgumentException("Filename prefix must be non-null"); throw new RuntimeException("writeFiles() is not currently supported"); } /** * Write a Pix to a byte array using the specified encoding from * Constants.IFF_*. * * @param pixs The source image. * @param format A format from Constants.IFF_*. * @return a byte array containing encoded bytes */ public static byte[] writeMem(Pix pixs, int format) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); return nativeWriteMem(pixs.mNativePix, format); } /** * Writes a Pix to file using the file extension as the output format; * supported formats are .jpg or .jpeg for JPEG and .bmp for bitmap. * <p> * Uses default quality and progressive encoding settings. * * @param pixs Source image. * @param file The file to write. * @return <code>true</code> on success */ public static boolean writeImpliedFormat(Pix pixs, File file) { return writeImpliedFormat(pixs, file, DEFAULT_QUALITY, DEFAULT_PROGRESSIVE); } /** * Writes a Pix to file using the file extension as the output format; * supported formats are .jpg or .jpeg for JPEG and .bmp for bitmap. * <p> * Notes: * <ol> * <li>This determines the output format from the filename extension. * <li>The last two args are ignored except for requests for jpeg files. * <li>The jpeg default quality is 75. * </ol> * * @param pixs Source image. * @param file The file to write. * @param quality (Only for lossy formats) Quality between 1 - 100, 0 for * default. * @param progressive (Only for JPEG) Whether to encode as progressive. * @return <code>true</code> on success */ public static boolean writeImpliedFormat( Pix pixs, File file, int quality, boolean progressive) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (file == null) throw new IllegalArgumentException("File must be non-null"); return nativeWriteImpliedFormat( pixs.mNativePix, file.getAbsolutePath(), quality, progressive); } /** * Writes a Pix to an Android Bitmap object. The output Bitmap will always * be in ARGB_8888 format, but the input Pixs may be any bit-depth. * * @param pixs The source image. * @return a Bitmap containing a copy of the source image, or <code>null * </code> on failure */ public static Bitmap writeBitmap(Pix pixs) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); final int[] dimensions = pixs.getDimensions(); final int width = dimensions[Pix.INDEX_W]; final int height = dimensions[Pix.INDEX_H]; //final int depth = dimensions[Pix.INDEX_D]; final Bitmap.Config config = Bitmap.Config.ARGB_8888; final Bitmap bitmap = Bitmap.createBitmap(width, height, config); if (nativeWriteBitmap(pixs.mNativePix, bitmap)) { return bitmap; } bitmap.recycle(); return null; } // *************** // * NATIVE CODE * // *************** private static native int nativeWriteBytes8(int nativePix, byte[] data); private static native boolean nativeWriteFiles(int nativePix, String rootname, int format); private static native byte[] nativeWriteMem(int nativePix, int format); private static native boolean nativeWriteImpliedFormat( int nativePix, String fileName, int quality, boolean progressive); private static native boolean nativeWriteBitmap(int nativePix, Bitmap bitmap); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Image binarization methods. * * @author alanv@google.com (Alan Viverette) */ public class Binarize { static { System.loadLibrary("lept"); } // Otsu thresholding constants /** Desired tile X dimension; actual size may vary */ public final static int OTSU_SIZE_X = 32; /** Desired tile Y dimension; actual size may vary */ public final static int OTSU_SIZE_Y = 32; /** Desired X smoothing value */ public final static int OTSU_SMOOTH_X = 2; /** Desired Y smoothing value */ public final static int OTSU_SMOOTH_Y = 2; /** Fraction of the max Otsu score, typically 0.1 */ public final static float OTSU_SCORE_FRACTION = 0.1f; /** * Performs locally-adaptive Otsu threshold binarization with default * parameters. * * @param pixs An 8 bpp PIX source image. * @return A 1 bpp thresholded PIX image. */ public static Pix otsuAdaptiveThreshold(Pix pixs) { return otsuAdaptiveThreshold( pixs, OTSU_SIZE_X, OTSU_SIZE_Y, OTSU_SMOOTH_X, OTSU_SMOOTH_Y, OTSU_SCORE_FRACTION); } /** * Performs locally-adaptive Otsu threshold binarization. * <p> * Notes: * <ol> * <li>The Otsu method finds a single global threshold for an image. This * function allows a locally adapted threshold to be found for each tile * into which the image is broken up. * <li>The array of threshold values, one for each tile, constitutes a * highly downscaled image. This array is optionally smoothed using a * convolution. The full width and height of the convolution kernel are (2 * * smoothX + 1) and (2 * smoothY + 1). * <li>The minimum tile dimension allowed is 16. If such small tiles are * used, it is recommended to use smoothing, because without smoothing, each * small tile determines the splitting threshold independently. A tile that * is entirely in the image bg will then hallucinate fg, resulting in a very * noisy binarization. The smoothing should be large enough that no tile is * only influenced by one type (fg or bg) of pixels, because it will force a * split of its pixels. * <li>To get a single global threshold for the entire image, use input * values of sizeX and sizeY that are larger than the image. For this * situation, the smoothing parameters are ignored. * <li>The threshold values partition the image pixels into two classes: one * whose values are less than the threshold and another whose values are * greater than or equal to the threshold. This is the same use of * 'threshold' as in pixThresholdToBinary(). * <li>The scorefract is the fraction of the maximum Otsu score, which is * used to determine the range over which the histogram minimum is searched. * See numaSplitDistribution() for details on the underlying method of * choosing a threshold. * <li>This uses enables a modified version of the Otsu criterion for * splitting the distribution of pixels in each tile into a fg and bg part. * The modification consists of searching for a minimum in the histogram * over a range of pixel values where the Otsu score is within a defined * fraction, scoreFraction, of the max score. To get the original Otsu * algorithm, set scoreFraction == 0. * </ol> * * @param pixs An 8 bpp PIX source image. * @param sizeX Desired tile X dimension; actual size may vary. * @param sizeY Desired tile Y dimension; actual size may vary. * @param smoothX Half-width of convolution kernel applied to threshold * array: use 0 for no smoothing. * @param smoothY Half-height of convolution kernel applied to threshold * array: use 0 for no smoothing. * @param scoreFraction Fraction of the max Otsu score; typ. 0.1 (use 0.0 * for standard Otsu). * @return A 1 bpp thresholded PIX image. */ public static Pix otsuAdaptiveThreshold( Pix pixs, int sizeX, int sizeY, int smoothX, int smoothY, float scoreFraction) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (pixs.getDepth() != 8) throw new IllegalArgumentException("Source pix depth must be 8bpp"); int nativePix = nativeOtsuAdaptiveThreshold( pixs.mNativePix, sizeX, sizeY, smoothX, smoothY, scoreFraction); if (nativePix == 0) throw new RuntimeException("Failed to perform Otsu adaptive threshold on image"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeOtsuAdaptiveThreshold( int nativePix, int sizeX, int sizeY, int smoothX, int smoothY, float scoreFract); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * @author alanv@google.com (Alan Viverette) */ public class Rotate { static { System.loadLibrary("lept"); } // Rotation default /** Default rotation quality is high. */ public static final boolean ROTATE_QUALITY = true; /** * Performs rotation using the default parameters. * * @param pixs The source pix. * @param degrees The number of degrees to rotate; clockwise is positive. * @return the rotated source image */ public static Pix rotate(Pix pixs, float degrees) { return rotate(pixs, degrees, false); } /** * Performs rotation with resizing using the default parameters. * * @param pixs The source pix. * @param degrees The number of degrees to rotate; clockwise is positive. * @param quality Whether to use high-quality rotation. * @return the rotated source image */ public static Pix rotate(Pix pixs, float degrees, boolean quality) { return rotate(pixs, degrees, quality, true); } /** * Performs basic image rotation about the center. * <p> * Notes: * <ol> * <li>Rotation is about the center of the image. * <li>For very small rotations, just return a clone. * <li>Rotation brings either white or black pixels in from outside the * image. * <li>Above 20 degrees, if rotation by shear is requested, we rotate by * sampling. * <li>Colormaps are removed for rotation by area map and shear. * <li>The dest can be expanded so that no image pixels are lost. To invoke * expansion, input the original width and height. For repeated rotation, * use of the original width and height allows the expansion to stop at the * maximum required size, which is a square with side = sqrt(w*w + h*h). * </ol> * * @param pixs The source pix. * @param degrees The number of degrees to rotate; clockwise is positive. * @param quality Whether to use high-quality rotation. * @param resize Whether to expand the output so that no pixels are lost. * <strong>Note:</strong> 1bpp images are always resized when * quality is {@code true}. * @return the rotated source image */ public static Pix rotate(Pix pixs, float degrees, boolean quality, boolean resize) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeRotate(pixs.mNativePix, degrees, quality, resize); if (nativePix == 0) return null; return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeRotate(int nativePix, float degrees, boolean quality, boolean resize); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Image rotation and skew detection methods. * * @author alanv@google.com (Alan Viverette) */ public class Skew { static { System.loadLibrary("lept"); } // Text alignment defaults /** Default range for sweep, will detect rotation of + or - 30 degrees. */ public final static float SWEEP_RANGE = 30.0f; /** Default sweep delta, reasonably accurate within 0.05 degrees. */ public final static float SWEEP_DELTA = 5.0f; /** Default sweep reduction, one-eighth the size of the original image. */ public final static int SWEEP_REDUCTION = 8; /** Default sweep reduction, one-fourth the size of the original image. */ public final static int SEARCH_REDUCTION = 4; /** Default search minimum delta, reasonably accurate within 0.05 degrees. */ public final static float SEARCH_MIN_DELTA = 0.01f; /** * Finds and returns the skew angle using default parameters. * * @param pixs Input pix (1 bpp). * @return the detected skew angle, or 0.0 on failure */ public static float findSkew(Pix pixs) { return findSkew(pixs, SWEEP_RANGE, SWEEP_DELTA, SWEEP_REDUCTION, SEARCH_REDUCTION, SEARCH_MIN_DELTA); } /** * Finds and returns the skew angle, doing first a sweep through a set of * equal angles, and then doing a binary search until convergence. * <p> * Notes: * <ol> * <li>In computing the differential line sum variance score, we sum the * result over scanlines, but we always skip: * <ul> * <li>at least one scanline * <li>not more than 10% of the image height * <li>not more than 5% of the image width * </ul> * </ol> * * @param pixs Input pix (1 bpp). * @param sweepRange Half the full search range, assumed about 0; in * degrees. * @param sweepDelta Angle increment of sweep; in degrees. * @param sweepReduction Sweep reduction factor = 1, 2, 4 or 8. * @param searchReduction Binary search reduction factor = 1, 2, 4 or 8; and * must not exceed redsweep. * @param searchMinDelta Minimum binary search increment angle; in degrees. * @return the detected skew angle, or 0.0 on failure */ public static float findSkew(Pix pixs, float sweepRange, float sweepDelta, int sweepReduction, int searchReduction, float searchMinDelta) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); return nativeFindSkew(pixs.mNativePix, sweepRange, sweepDelta, sweepReduction, searchReduction, searchMinDelta); } // *************** // * NATIVE CODE * // *************** private static native float nativeFindSkew(int nativePix, float sweepRange, float sweepDelta, int sweepReduction, int searchReduction, float searchMinDelta); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Image adaptive mapping methods. * * @author alanv@google.com (Alan Viverette) */ public class AdaptiveMap { static { System.loadLibrary("lept"); } // Background normalization constants /** Image reduction value; possible values are 1, 2, 4, 8 */ private final static int NORM_REDUCTION = 16; /** Desired tile size; actual size may vary */ private final static int NORM_SIZE = 3; /** Background brightness value; values over 200 may result in clipping */ private final static int NORM_BG_VALUE = 200; /** * Normalizes an image's background using default parameters. * * @param pixs A source pix image. * @return the source pix image with a normalized background */ public static Pix backgroundNormMorph(Pix pixs) { return backgroundNormMorph(pixs, NORM_REDUCTION, NORM_SIZE, NORM_BG_VALUE); } /** * Normalizes an image's background to a specified value. * <p> * Notes: * <ol> * <li>This is a top-level interface for normalizing the image intensity by * mapping the image so that the background is near the input value 'bgval'. * <li>The input image is either grayscale or rgb. * <li>For each component in the input image, the background value is * estimated using a grayscale closing; hence the 'Morph' in the function * name. * <li>An optional binary mask can be specified, with the foreground pixels * typically over image regions. The resulting background map values will be * determined by surrounding pixels that are not under the mask foreground. * The origin (0,0) of this mask is assumed to be aligned with the origin of * the input image. This binary mask must not fully cover pixs, because then * there will be no pixels in the input image available to compute the * background. * <li>The map is computed at reduced size (given by 'reduction') from the * input pixs and optional pixim. At this scale, pixs is closed to remove * the background, using a square Sel of odd dimension. The product of * reduction * size should be large enough to remove most of the text * foreground. * <li>No convolutional smoothing needs to be done on the map before * inverting it. * <li>A 'bgval' target background value for the normalized image. This * should be at least 128. If set too close to 255, some clipping will occur * in the result. * </ol> * * @param pixs A source pix image. * @param normReduction Reduction at which morphological closings are done. * @param normSize Size of square Sel for the closing. * @param normBgValue Target background value. * @return the source pix image with a normalized background */ public static Pix backgroundNormMorph( Pix pixs, int normReduction, int normSize, int normBgValue) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeBackgroundNormMorph( pixs.mNativePix, normReduction, normSize, normBgValue); if (nativePix == 0) throw new RuntimeException("Failed to normalize image background"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeBackgroundNormMorph( int nativePix, int reduction, int size, int bgval); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Image sharpening methods. * * @author alanv@google.com (Alan Viverette) */ public class Enhance { static { System.loadLibrary("lept"); } /** * Performs unsharp masking (edge enhancement). * <p> * Notes: * <ul> * <li>We use symmetric smoothing filters of odd dimension, typically use * sizes of 3, 5, 7, etc. The <code>halfwidth</code> parameter for these is * (size - 1)/2; i.e., 1, 2, 3, etc.</li> * <li>The <code>fract</code> parameter is typically taken in the range: 0.2 * &lt; <code>fract</code> &lt; 0.7</li> * </ul> * * @param halfwidth The half-width of the smoothing filter. * @param fraction The fraction of edge to be added back into the source * image. * @return an edge-enhanced Pix image or copy if no enhancement requested */ public static Pix unsharpMasking(Pix pixs, int halfwidth, float fraction) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeUnsharpMasking(pixs.mNativePix, halfwidth, fraction); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeUnsharpMasking(int nativePix, int halfwidth, float fract); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * JPEG input and output methods. * * @author alanv@google.com (Alan Viverette) */ public class JpegIO { static { System.loadLibrary("lept"); } /** Default quality is 85%, which is reasonably good. */ public static final int DEFAULT_QUALITY = 85; /** Progressive encoding is disabled by default to increase compatibility. */ public static final boolean DEFAULT_PROGRESSIVE = false; /** * Returns a compressed JPEG byte representation of this Pix using default * parameters. * * @param pixs * @return a compressed JPEG byte array representation of the Pix */ public static byte[] compressToJpeg(Pix pixs) { return compressToJpeg(pixs, DEFAULT_QUALITY, DEFAULT_PROGRESSIVE); } /** * Returns a compressed JPEG byte representation of this Pix. * * @param pixs A source pix image. * @param quality The quality of the compressed image. Valid range is 0-100. * @param progressive Whether to use progressive compression. * @return a compressed JPEG byte array representation of the Pix */ public static byte[] compressToJpeg(Pix pixs, int quality, boolean progressive) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (quality < 0 || quality > 100) throw new IllegalArgumentException("Quality must be between 0 and 100 (inclusive)"); final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); final Bitmap bmp = WriteFile.writeBitmap(pixs); bmp.compress(CompressFormat.JPEG, quality, byteStream); bmp.recycle(); final byte[] encodedData = byteStream.toByteArray(); try { byteStream.close(); } catch (IOException e) { e.printStackTrace(); } return encodedData; } // *************** // * NATIVE CODE * // *************** private static native byte[] nativeCompressToJpeg( int nativePix, int quality, boolean progressive); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Leptonica constants. * * @author alanv@google.com (Alan Viverette) */ public class Constants { /*-------------------------------------------------------------------------* * Access and storage flags * *-------------------------------------------------------------------------*/ /* * For Pix, Box, Pta and Numa, there are 3 standard methods for handling the * retrieval or insertion of a struct: (1) direct insertion (Don't do this * if there is another handle somewhere to this same struct!) (2) copy * (Always safe, sets up a refcount of 1 on the new object. Can be * undesirable if very large, such as an image or an array of images.) (3) * clone (Makes another handle to the same struct, and bumps the refcount up * by 1. Safe to do unless you're changing data through one of the handles * but don't want those changes to be seen by the other handle.) For Pixa * and Boxa, which are structs that hold an array of clonable structs, there * is an additional method: (4) copy-clone (Makes a new higher-level struct * with a refcount of 1, but clones all the structs in the array.) Unlike * the other structs, when retrieving a string from an Sarray, you are * allowed to get a handle without a copy or clone (i.e., that you don't * own!). You must not free or insert such a string! Specifically, for an * Sarray, the copyflag for retrieval is either: TRUE (or 1 or L_COPY) or * FALSE (or 0 or L_NOCOPY) For insertion, the copyflag is either: TRUE (or * 1 or L_COPY) or FALSE (or 0 or L_INSERT) Note that L_COPY is always 1, * and L_INSERT and L_NOCOPY are always 0. */ /* Stuff it in; no copy, clone or copy-clone */ public static final int L_INSERT = 0; /* Make/use a copy of the object */ public static final int L_COPY = 1; /* Make/use clone (ref count) of the object */ public static final int L_CLONE = 2; /* * Make a new object and fill with with clones of each object in the * array(s) */ public static final int L_COPY_CLONE = 3; /*--------------------------------------------------------------------------* * Sort flags * *--------------------------------------------------------------------------*/ /* Sort in increasing order */ public static final int L_SORT_INCREASING = 1; /* Sort in decreasing order */ public static final int L_SORT_DECREASING = 2; /* Sort box or c.c. by horiz location */ public static final int L_SORT_BY_X = 3; /* Sort box or c.c. by vert location */ public static final int L_SORT_BY_Y = 4; /* Sort box or c.c. by width */ public static final int L_SORT_BY_WIDTH = 5; /* Sort box or c.c. by height */ public static final int L_SORT_BY_HEIGHT = 6; /* Sort box or c.c. by min dimension */ public static final int L_SORT_BY_MIN_DIMENSION = 7; /* Sort box or c.c. by max dimension */ public static final int L_SORT_BY_MAX_DIMENSION = 8; /* Sort box or c.c. by perimeter */ public static final int L_SORT_BY_PERIMETER = 9; /* Sort box or c.c. by area */ public static final int L_SORT_BY_AREA = 10; /* Sort box or c.c. by width/height ratio */ public static final int L_SORT_BY_ASPECT_RATIO = 11; /* ------------------ Image file format types -------------- */ /* * The IFF_DEFAULT flag is used to write the file out in the same (input) * file format that the pix was read from. If the pix was not read from * file, the input format field will be IFF_UNKNOWN and the output file * format will be chosen to be compressed and lossless; namely, IFF_TIFF_G4 * for d = 1 and IFF_PNG for everything else. IFF_JP2 is for jpeg2000, which * is not supported in leptonica. */ public static final int IFF_UNKNOWN = 0; public static final int IFF_BMP = 1; public static final int IFF_JFIF_JPEG = 2; public static final int IFF_PNG = 3; public static final int IFF_TIFF = 4; public static final int IFF_TIFF_PACKBITS = 5; public static final int IFF_TIFF_RLE = 6; public static final int IFF_TIFF_G3 = 7; public static final int IFF_TIFF_G4 = 8; public static final int IFF_TIFF_LZW = 9; public static final int IFF_TIFF_ZIP = 10; public static final int IFF_PNM = 11; public static final int IFF_PS = 12; public static final int IFF_GIF = 13; public static final int IFF_JP2 = 14; public static final int IFF_DEFAULT = 15; public static final int IFF_SPIX = 16; }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.leptonica.android; /** * Image scaling methods. * * @author alanv@google.com (Alan Viverette) */ public class Scale { static { System.loadLibrary("lept"); } public enum ScaleType { /* Scale in X and Y independently, so that src matches dst exactly. */ FILL, /* * Compute a scale that will maintain the original src aspect ratio, but * will also ensure that src fits entirely inside dst. May shrink or * expand src to fit dst. */ FIT, /* * Compute a scale that will maintain the original src aspect ratio, but * will also ensure that src fits entirely inside dst. May shrink src to * fit dst, but will not expand it. */ FIT_SHRINK, } /** * Scales the Pix to a specified width and height using a specified scaling * type (fill, stretch, etc.). Returns a scaled image or a clone of the Pix * if no scaling is required. * * @param pixs * @param width * @param height * @param type * @return a scaled image or a clone of the Pix if no scaling is required */ public static Pix scaleToSize(Pix pixs, int width, int height, ScaleType type) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int pixWidth = pixs.getWidth(); int pixHeight = pixs.getHeight(); float scaleX = width / (float) pixWidth; float scaleY = height / (float) pixHeight; switch (type) { case FILL: // Retains default scaleX and scaleY values break; case FIT: scaleX = Math.min(scaleX, scaleY); scaleY = scaleX; break; case FIT_SHRINK: scaleX = Math.min(1.0f, Math.min(scaleX, scaleY)); scaleY = scaleX; break; } return scale(pixs, scaleX, scaleY); } /** * Scales the Pix to specified scale. If no scaling is required, returns a * clone of the source Pix. * * @param pixs the source Pix * @param scale dimension scaling factor * @return a Pix scaled according to the supplied factors */ public static Pix scale(Pix pixs, float scale) { return scale(pixs, scale, scale); } /** * Scales the Pix to specified x and y scale. If no scaling is required, * returns a clone of the source Pix. * * @param pixs the source Pix * @param scaleX x-dimension (width) scaling factor * @param scaleY y-dimension (height) scaling factor * @return a Pix scaled according to the supplied factors */ public static Pix scale(Pix pixs, float scaleX, float scaleY) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (scaleX <= 0.0f) throw new IllegalArgumentException("X scaling factor must be positive"); if (scaleY <= 0.0f) throw new IllegalArgumentException("Y scaling factor must be positive"); int nativePix = nativeScale(pixs.mNativePix, scaleX, scaleY); if (nativePix == 0) throw new RuntimeException("Failed to natively scale pix"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeScale(int nativePix, float scaleX, float scaleY); }
Java
package vcard.io; import java.io.IOException; /** * A Base64 Encoder/Decoder. * * <p> * This class is used to encode and decode data in Base64 format as described in RFC 1521. * * <p> * This is "Open Source" software and released under the <a href="http://www.gnu.org/licenses/lgpl.html">GNU/LGPL</a> license.<br> * It is provided "as is" without warranty of any kind.<br> * Copyright 2003: Christian d'Heureuse, Inventec Informatik AG, Switzerland.<br> * Home page: <a href="http://www.source-code.biz">www.source-code.biz</a><br> * * <p> * Version history:<br> * 2003-07-22 Christian d'Heureuse (chdh): Module created.<br> * 2005-08-11 chdh: Lincense changed from GPL to LGPL.<br> * 2006-11-21 chdh:<br> * &nbsp; Method encode(String) renamed to encodeString(String).<br> * &nbsp; Method decode(String) renamed to decodeString(String).<br> * &nbsp; New method encode(byte[],int) added.<br> * &nbsp; New method decode(String) added.<br> * 2009-02-25 ducktayp:<br> * &nbsp; New method mimeEncode(Appendable, byte[], int, String) for creating mime-compatible output.<br> * &nbsp; New method decodeInPlace(StringBuffer) for whitespace-tolerant decoding without allocating memory.<br> */ public class Base64Coder { // Mapping table from 6-bit nibbles to Base64 characters. private static char[] map1 = new char[64]; static { int i=0; for (char c='A'; c<='Z'; c++) map1[i++] = c; for (char c='a'; c<='z'; c++) map1[i++] = c; for (char c='0'; c<='9'; c++) map1[i++] = c; map1[i++] = '+'; map1[i++] = '/'; } // Mapping table from Base64 characters to 6-bit nibbles. private static byte[] map2 = new byte[128]; static { for (int i=0; i<map2.length; i++) map2[i] = -1; for (int i=0; i<64; i++) map2[map1[i]] = (byte)i; } /** * Encodes a byte array into Base64 format. * A separator is inserted after every linelength chars * @param out an StringBuffer into which output is appended. * @param in an array containing the data bytes to be encoded. * @param linelength number of characters per line * @param sep Separator placed every linelength characters. * */ public static void mimeEncode(Appendable out, byte[] in, int linelength, String sep) throws IOException { int pos = 0; int bits = 0; int val = 0; for (byte b : in) { val <<= 8; val |= ((int) b) & 0xff; bits += 8; if (bits == 24) { for (int i = 0; i < 4; ++i) { out.append((char) map1[(val >>> 18) & 0x3f]); val <<= 6; pos++; if (pos % linelength == 0) { out.append(sep); } } bits = 0; val = 0; } } int pad = (3 - (bits / 8)) % 3; while (bits > 0) { out.append((char) map1[(val >>> 18) & 0x3f]); val <<= 6; bits -= 6; pos++; if (pos % linelength == 0) { out.append(sep); } } while (pad-- > 0) out.append('='); } /** * Decodes data in Base64 format in a StringBuffer. * Whitespace and invalid characters are ignored in the Base64 encoded data; * @param inout a StringBuffer containing the Base64 encoded data; Buffer is modified to contain decoded data (one byte per char) * @return new length of the StringBuffer */ public static int decodeInPlace (StringBuffer inout) { final int n = inout.length(); int pos = 0; // Writer position int val = 0; // Current byte contents int pad = 0; // Number of padding chars int bits = 0; // Number of bits decoded in val for (int i = 0; i < n; ++i) { char ch = inout.charAt(i); switch (ch) { case ' ': case '\t': case '\n': case '\r': continue; // whitespace case '=': // Padding ++pad; ch = 'A'; default: if (ch > 127) continue; // invalid char int ch2 = map2[ch]; if (ch2 < 0) continue; // invalid char // Shift val and put decoded bits into val's MSB val <<= 6; val |= ch2; bits += 6; // If we have 24 bits write them out. if (bits == 24) { bits -= 8 * pad; pad = 0; while (bits > 0) { inout.setCharAt(pos++, (char) ((val >>> 16) & 0xff)); val <<= 8; bits -= 8; } val = 0; } } } inout.setLength(pos); return pos; } // Dummy constructor. private Base64Coder() {} } // end class Base64Coder
Java
package vcard.io; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; import android.os.Binder; import android.os.IBinder; import android.provider.Contacts; import android.widget.Toast; public class VCardIO extends Service { static final String DATABASE_NAME = "syncdata.db"; static final String SYNCDATA_TABLE_NAME = "sync"; static final String PERSONID = "person"; static final String SYNCID = "syncid"; private static final int DATABASE_VERSION = 1; private NotificationManager mNM; final Object syncMonitor = "SyncMonitor"; String syncFileName; enum Action { IDLE, IMPORT, EXPORT }; /** * This class helps open, create, and upgrade the database file. */ private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + SYNCDATA_TABLE_NAME + " (" + PERSONID + " INTEGER PRIMARY KEY," + SYNCID + " TEXT UNIQUE" +");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // No need to do anything --- this is version 1 } } private DatabaseHelper mOpenHelper; Action mAction; public class LocalBinder extends Binder { VCardIO getService() { return VCardIO.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } // This is the object that receives interactions from clients. See // RemoteService for a more complete example. private final IBinder mBinder = new LocalBinder(); @Override public void onCreate() { mOpenHelper = new DatabaseHelper(getApplicationContext()); mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); mAction = Action.IDLE; // Display a notification about us starting. We put an icon in the status bar. showNotification(); } @Override public void onDestroy() { // Cancel the persistent notification. mNM.cancelAll(); synchronized (syncMonitor) { switch (mAction) { case IMPORT: // Tell the user we stopped. Toast.makeText(this, "VCard import aborted ("+syncFileName +")", Toast.LENGTH_SHORT).show(); break; case EXPORT: // Tell the user we stopped. Toast.makeText(this, "VCard export aborted ("+syncFileName +")", Toast.LENGTH_SHORT).show(); break; default: break; } mAction = Action.IDLE; } } /** * Show a notification while this service is running. */ private void showNotification() { // In this sample, we'll use the same text for the ticker and the expanded notification String text = null; String detailedText = ""; synchronized (syncMonitor) { switch (mAction) { case IMPORT: text = (String) getText(R.string.importServiceMsg); detailedText = "Importing VCards from " + syncFileName; break; case EXPORT: text = (String) getText(R.string.exportServiceMsg); detailedText = "Exporting VCards from " + syncFileName; break; default: break; } } if (text == null) { mNM.cancelAll(); } else { // Set the icon, scrolling text and timestamp Notification notification = new Notification(R.drawable.status_icon, text, System.currentTimeMillis()); // The PendingIntent to launch our activity if the user selects this notification PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, App.class), 0); // Set the info for the views that show in the notification panel. notification.setLatestEventInfo(this, "VCard IO", detailedText, contentIntent); // Send the notification. // We use a layout id because it is a unique number. We use it later to cancel. mNM.notify(R.string.app_name, notification); } } public void doImport(final String fileName, final boolean replace, final App app) { try { File vcfFile = new File(fileName); final BufferedReader vcfBuffer = new BufferedReader(new FileReader(fileName)); final long maxlen = vcfFile.length(); // Start lengthy operation in a background thread new Thread(new Runnable() { public void run() { long importStatus = 0; synchronized (syncMonitor) { mAction = Action.IMPORT; syncFileName = fileName; } showNotification(); SQLiteDatabase db = mOpenHelper.getWritableDatabase(); SQLiteStatement querySyncId = db.compileStatement("SELECT " + SYNCID + " FROM " + SYNCDATA_TABLE_NAME + " WHERE " + PERSONID + "=?"); SQLiteStatement queryPersonId = db.compileStatement("SELECT " + PERSONID + " FROM " + SYNCDATA_TABLE_NAME + " WHERE " + SYNCID + "=?"); SQLiteStatement insertSyncId = db.compileStatement("INSERT INTO " + SYNCDATA_TABLE_NAME + " (" + PERSONID + "," + SYNCID + ") VALUES (?,?)"); Contact parseContact = new Contact(querySyncId, queryPersonId, insertSyncId); try { long ret = 0; do { ret = parseContact.parseVCard(vcfBuffer); if (ret >= 0) { parseContact.addContact(getApplicationContext(), 0, replace); importStatus += parseContact.getParseLen(); // Update the progress bar app.updateProgress((int) (100 * importStatus / maxlen)); } } while (ret > 0); db.close(); app.updateProgress(100); synchronized (syncMonitor) { mAction = Action.IDLE; showNotification(); } stopSelf(); } catch (IOException e) { } } }).start(); } catch (FileNotFoundException e) { app.updateStatus("File not found: " + e.getMessage()); } } public void doExport(final String fileName, final App app) { try { final BufferedWriter vcfBuffer = new BufferedWriter(new FileWriter(fileName)); final ContentResolver cResolver = getContentResolver(); final Cursor allContacts = cResolver.query(Contacts.People.CONTENT_URI, null, null, null, null); if (allContacts == null || !allContacts.moveToFirst()) { app.updateStatus("No contacts found"); allContacts.close(); return; } final long maxlen = allContacts.getCount(); // Start lengthy operation in a background thread new Thread(new Runnable() { public void run() { long exportStatus = 0; synchronized (syncMonitor) { mAction = Action.EXPORT; syncFileName = fileName; } showNotification(); SQLiteDatabase db = mOpenHelper.getWritableDatabase(); SQLiteStatement querySyncId = db.compileStatement("SELECT " + SYNCID + " FROM " + SYNCDATA_TABLE_NAME + " WHERE " + PERSONID + "=?"); SQLiteStatement queryPersonId = db.compileStatement("SELECT " + PERSONID + " FROM " + SYNCDATA_TABLE_NAME + " WHERE " + SYNCID + "=?"); SQLiteStatement insertSyncId = db.compileStatement("INSERT INTO " + SYNCDATA_TABLE_NAME + " (" + PERSONID + "," + SYNCID + ") VALUES (?,?)"); Contact parseContact = new Contact(querySyncId, queryPersonId, insertSyncId); try { boolean hasNext = true; do { parseContact.populate(allContacts, cResolver); parseContact.writeVCard(vcfBuffer); ++exportStatus; // Update the progress bar app.updateProgress((int) (100 * exportStatus / maxlen)); hasNext = allContacts.moveToNext(); } while (hasNext); vcfBuffer.close(); db.close(); app.updateProgress(100); synchronized (syncMonitor) { mAction = Action.IDLE; showNotification(); } stopSelf(); } catch (IOException e) { app.updateStatus("Write error: " + e.getMessage()); } } }).start(); } catch (IOException e) { app.updateStatus("Error opening file: " + e.getMessage()); } } }
Java
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". * * 2009-02-25 ducktayp: Modified to parse and format more Vcard fields, including PHOTO. * No attempt was made to preserve compatibility with previous code. * */ package vcard.io; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.UUID; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDoneException; import android.database.sqlite.SQLiteStatement; import android.net.Uri; import android.net.Uri.Builder; import android.provider.Contacts; import android.provider.Contacts.ContactMethodsColumns; import com.funambol.util.Log; import com.funambol.util.QuotedPrintable; import com.funambol.util.StringUtil; /** * A Contact item */ public class Contact { static final String NL = "\r\n"; // Property name for Instant-message addresses static final String IMPROP = "X-IM-NICK"; // Property parameter name for custom labels static final String LABEL_PARAM = "LABEL"; // Property parameter for IM protocol static final String PROTO_PARAM = "PROTO"; // Protocol labels static final String[] PROTO = { "AIM", // ContactMethods.PROTOCOL_AIM = 0 "MSN", // ContactMethods.PROTOCOL_MSN = 1 "YAHOO", // ContactMethods.PROTOCOL_YAHOO = 2 "SKYPE", // ContactMethods.PROTOCOL_SKYPE = 3 "QQ", // ContactMethods.PROTOCOL_QQ = 4 "GTALK", // ContactMethods.PROTOCOL_GOOGLE_TALK = 5 "ICQ", // ContactMethods.PROTOCOL_ICQ = 6 "JABBER" // ContactMethods.PROTOCOL_JABBER = 7 }; long parseLen; static final String BIRTHDAY_FIELD = "Birthday:"; /** * Contact fields declaration */ // Contact identifier String _id; String syncid; // Contact displayed name String displayName; // Contact first name String firstName; // Contact last name String lastName; static class RowData { RowData(int type, String data, boolean preferred, String customLabel) { this.type = type; this.data = data; this.preferred = preferred; this.customLabel = customLabel; auxData = null; } RowData(int type, String data, boolean preferred) { this(type, data, preferred, null); } int type; String data; boolean preferred; String customLabel; String auxData; } static class OrgData { OrgData(int type, String title, String company, String customLabel) { this.type = type; this.title = title; this.company = company; this.customLabel = customLabel; } int type; // Contact title String title; // Contact company name String company; String customLabel; } // Phones dictionary; keys are android Contact Column ids List<RowData> phones; // Emails dictionary; keys are android Contact Column ids List<RowData> emails; // Address dictionary; keys are android Contact Column ids List<RowData> addrs; // Instant message addr dictionary; keys are android Contact Column ids List<RowData> ims; // Organizations list List<OrgData> orgs; // Compressed photo byte[] photo; // Contact note String notes; // Contact's birthday String birthday; Hashtable<String, handleProp> propHandlers; interface handleProp { void parseProp(final String propName, final Vector<String> propVec, final String val); } // Initializer block { reset(); propHandlers = new Hashtable<String, handleProp>(); handleProp simpleValue = new handleProp() { public void parseProp(final String propName, final Vector<String> propVec, final String val) { if (propName.equals("FN")) { displayName = val; } else if (propName.equals("NOTE")) { notes = val; } else if (propName.equals("BDAY")) { birthday = val; } else if (propName.equals("X-IRMC-LUID") || propName.equals("UID")) { syncid = val; } else if (propName.equals("N")) { String[] names = StringUtil.split(val, ";"); // We set only the first given name. // The others are ignored in input and will not be // overridden on the server in output. if (names.length >= 2) { firstName = names[1]; lastName = names[0]; } else { String[] names2 = StringUtil.split(names[0], " "); firstName = names2[0]; if (names2.length > 1) lastName = names2[1]; } } } }; propHandlers.put("FN", simpleValue); propHandlers.put("NOTE", simpleValue); propHandlers.put("BDAY", simpleValue); propHandlers.put("X-IRMC-LUID", simpleValue); propHandlers.put("UID", simpleValue); propHandlers.put("N", simpleValue); handleProp orgHandler = new handleProp() { @Override public void parseProp(String propName, Vector<String> propVec, String val) { String label = null; for (String prop : propVec) { String[] propFields = StringUtil.split(prop, "="); if (propFields[0].equalsIgnoreCase(LABEL_PARAM) && propFields.length > 1) { label = propFields[1]; } } if (propName.equals("TITLE")) { boolean setTitle = false; for (OrgData org : orgs) { if (label == null && org.customLabel != null) continue; if (label != null && !label.equals(org.customLabel)) continue; if (org.title == null) { org.title = val; setTitle = true; break; } } if (!setTitle) { orgs.add(new OrgData(label == null ? ContactMethodsColumns.TYPE_WORK : ContactMethodsColumns.TYPE_CUSTOM, val, null, label)); } } else if (propName.equals("ORG")) { String[] orgFields = StringUtil.split(val, ";"); boolean setCompany = false; for (OrgData org : orgs) { if (label == null && org.customLabel != null) continue; if (label != null && !label.equals(org.customLabel)) continue; if (org.company == null) { org.company = val; setCompany = true; break; } } if (!setCompany) { orgs.add(new OrgData(label == null ? ContactMethodsColumns.TYPE_WORK : ContactMethodsColumns.TYPE_CUSTOM, null, orgFields[0], label)); } } } }; propHandlers.put("ORG", orgHandler); propHandlers.put("TITLE", orgHandler); propHandlers.put("TEL", new handleProp() { public void parseProp(final String propName, final Vector<String> propVec, final String val) { String label = null; int subtype = Contacts.PhonesColumns.TYPE_OTHER; boolean preferred = false; for (String prop : propVec) { if (prop.equalsIgnoreCase("HOME") || prop.equalsIgnoreCase("VOICE")) { if (subtype != Contacts.PhonesColumns.TYPE_FAX_HOME) subtype = Contacts.PhonesColumns.TYPE_HOME; } else if (prop.equalsIgnoreCase("WORK")) { if (subtype == Contacts.PhonesColumns.TYPE_FAX_HOME) { subtype = Contacts.PhonesColumns.TYPE_FAX_WORK; } else subtype = Contacts.PhonesColumns.TYPE_WORK; } else if (prop.equalsIgnoreCase("CELL")) { subtype = Contacts.PhonesColumns.TYPE_MOBILE; } else if (prop.equalsIgnoreCase("FAX")) { if (subtype == Contacts.PhonesColumns.TYPE_WORK) { subtype = Contacts.PhonesColumns.TYPE_FAX_WORK; } else subtype = Contacts.PhonesColumns.TYPE_FAX_HOME; } else if (prop.equalsIgnoreCase("PAGER")) { subtype = Contacts.PhonesColumns.TYPE_PAGER; } else if (prop.equalsIgnoreCase("PREF")) { preferred = true; } else { String[] propFields = StringUtil.split(prop, "="); if (propFields.length > 1 && propFields[0].equalsIgnoreCase(LABEL_PARAM)) { label = propFields[1]; subtype = Contacts.ContactMethodsColumns.TYPE_CUSTOM; } } } phones.add(new RowData(subtype, toCanonicalPhone(val), preferred, label)); } }); propHandlers.put("ADR", new handleProp() { public void parseProp(final String propName, final Vector<String> propVec, final String val) { boolean preferred = false; String label = null; int subtype = Contacts.ContactMethodsColumns.TYPE_WORK; // vCard spec says default is WORK for (String prop : propVec) { if (prop.equalsIgnoreCase("WORK")) { subtype = Contacts.ContactMethodsColumns.TYPE_WORK; } else if (prop.equalsIgnoreCase("HOME")) { subtype = Contacts.ContactMethodsColumns.TYPE_HOME; } else if (prop.equalsIgnoreCase("PREF")) { preferred = true; } else { String[] propFields = StringUtil.split(prop, "="); if (propFields.length > 1 && propFields[0].equalsIgnoreCase(LABEL_PARAM)) { label = propFields[1]; subtype = Contacts.ContactMethodsColumns.TYPE_CUSTOM; } } } String[] addressFields = StringUtil.split(val, ";"); StringBuffer addressBuf = new StringBuffer(val.length()); if (addressFields.length > 2) { addressBuf.append(addressFields[2]); int maxLen = Math.min(7, addressFields.length); for (int i = 3; i < maxLen; ++i) { addressBuf.append(", ").append(addressFields[i]); } } String address = addressBuf.toString(); addrs.add(new RowData(subtype, address, preferred, label)); } }); propHandlers.put("EMAIL", new handleProp() { public void parseProp(final String propName, final Vector<String> propVec, final String val) { boolean preferred = false; String label = null; int subtype = Contacts.ContactMethodsColumns.TYPE_HOME; for (String prop : propVec) { if (prop.equalsIgnoreCase("PREF")) { preferred = true; } else if (prop.equalsIgnoreCase("WORK")) { subtype = Contacts.ContactMethodsColumns.TYPE_WORK; } else { String[] propFields = StringUtil.split(prop, "="); if (propFields.length > 1 && propFields[0].equalsIgnoreCase(LABEL_PARAM)) { label = propFields[1]; subtype = Contacts.ContactMethodsColumns.TYPE_CUSTOM; } } } emails.add(new RowData(subtype, val, preferred, label)); } }); propHandlers.put(IMPROP, new handleProp() { public void parseProp(final String propName, final Vector<String> propVec, final String val) { boolean preferred = false; String label = null; String proto = null; int subtype = Contacts.ContactMethodsColumns.TYPE_HOME; for (String prop : propVec) { if (prop.equalsIgnoreCase("PREF")) { preferred = true; } else if (prop.equalsIgnoreCase("WORK")) { subtype = Contacts.ContactMethodsColumns.TYPE_WORK; } else { String[] propFields = StringUtil.split(prop, "="); if (propFields.length > 1) { if (propFields[0].equalsIgnoreCase(PROTO_PARAM)) { proto = propFields[1]; } else if (propFields[0].equalsIgnoreCase(LABEL_PARAM)) { label = propFields[1]; } } } } RowData newRow = new RowData(subtype, val, preferred, label); newRow.auxData = proto; ims.add(newRow); } }); propHandlers.put("PHOTO", new handleProp() { public void parseProp(final String propName, final Vector<String> propVec, final String val) { boolean isUrl = false; photo = new byte[val.length()]; for (int i = 0; i < photo.length; ++i) photo[i] = (byte) val.charAt(i); for (String prop : propVec) { if (prop.equalsIgnoreCase("VALUE=URL")) { isUrl = true; } } if (isUrl) { // TODO: Deal with photo URLS } } }); } private void reset() { _id = null; syncid = null; parseLen = 0; displayName = null; notes = null; birthday = null; photo = null; firstName = null; lastName = null; if (phones == null) phones = new ArrayList<RowData>(); else phones.clear(); if (emails == null) emails = new ArrayList<RowData>(); else emails.clear(); if (addrs == null) addrs = new ArrayList<RowData>(); else addrs.clear(); if (orgs == null) orgs = new ArrayList<OrgData>(); else orgs.clear(); if (ims == null) ims = new ArrayList<RowData>(); else ims.clear(); } SQLiteStatement querySyncId; SQLiteStatement queryPersonId; SQLiteStatement insertSyncId; // Constructors------------------------------------------------ public Contact(SQLiteStatement querySyncId, SQLiteStatement queryPersionId, SQLiteStatement insertSyncId) { this.querySyncId = querySyncId; this.queryPersonId = queryPersionId; this.insertSyncId = insertSyncId; } public Contact(String vcard, SQLiteStatement querySyncId, SQLiteStatement queryPersionId, SQLiteStatement insertSyncId) { this(querySyncId, queryPersionId, insertSyncId); BufferedReader vcardReader = new BufferedReader(new StringReader(vcard)); try { parseVCard(vcardReader); } catch (IOException e) { e.printStackTrace(); } } public Contact(BufferedReader vcfReader, SQLiteStatement querySyncId, SQLiteStatement queryPersionId, SQLiteStatement insertSyncId) throws IOException { this(querySyncId, queryPersionId, insertSyncId); parseVCard(vcfReader); } public Contact(Cursor peopleCur, ContentResolver cResolver, SQLiteStatement querySyncId, SQLiteStatement queryPersionId, SQLiteStatement insertSyncId) { this(querySyncId, queryPersionId, insertSyncId); populate(peopleCur, cResolver); } final static Pattern[] phonePatterns = { Pattern.compile("[+](1)(\\d\\d\\d)(\\d\\d\\d)(\\d\\d\\d\\d.*)"), Pattern.compile("[+](972)(2|3|4|8|9|50|52|54|57|59|77)(\\d\\d\\d)(\\d\\d\\d\\d.*)"), }; /** * Change the phone to canonical format (with dashes, etc.) if it's in a supported country. * @param phone * @return */ String toCanonicalPhone(String phone) { for (final Pattern phonePattern : phonePatterns) { Matcher m = phonePattern.matcher(phone); if (m.matches()) { return "+" + m.group(1) + "-" + m.group(2) + "-" + m.group(3) + "-" + m.group(4); } } return phone; } /** * Set the person identifier */ public void setId(String id) { _id = id; } /** * Get the person identifier */ public long getId() { return Long.parseLong(_id); } final static Pattern beginPattern = Pattern.compile("BEGIN:VCARD",Pattern.CASE_INSENSITIVE); final static Pattern propPattern = Pattern.compile("([^:]+):(.*)"); final static Pattern propParamPattern = Pattern.compile("([^;=]+)(=([^;]+))?(;|$)"); final static Pattern base64Pattern = Pattern.compile("\\s*([a-zA-Z0-9+/]+={0,2})\\s*$"); final static Pattern namePattern = Pattern.compile("(([^,]+),(.*))|((.*?)\\s+(\\S+))"); // Parse birthday in notes final static Pattern birthdayPattern = Pattern.compile("^" + BIRTHDAY_FIELD + ":\\s*([^;]+)(;\\s*|\\s*$)",Pattern.CASE_INSENSITIVE); /** * Parse the vCard string into the contacts fields */ public long parseVCard(BufferedReader vCard) throws IOException { // Reset the currently read values. reset(); // Find Begin. String line = vCard.readLine(); if (line != null) parseLen += line.length(); else return -1; while (line != null && !beginPattern.matcher(line).matches()) { line = vCard.readLine(); parseLen += line.length(); } if (line == null) return -1; boolean skipRead = false; while (line != null) { if (!skipRead) line = vCard.readLine(); if (line == null) { return 0; } skipRead = false; // do multi-line unfolding (cr lf with whitespace immediately following is removed, joining the two lines). vCard.mark(1); for (int ch = vCard.read(); ch == (int) ' ' || ch == (int) '\t'; ch = vCard.read()) { vCard.reset(); String newLine = vCard.readLine(); if (newLine != null) line += newLine; vCard.mark(1); } vCard.reset(); parseLen += line.length(); // TODO: doesn't include CR LFs Matcher pm = propPattern.matcher(line); if (pm.matches()) { String prop = pm.group(1); String val = pm.group(2); if (prop.equalsIgnoreCase("END") && val.equalsIgnoreCase("VCARD")) { // End of vCard return parseLen; } Matcher ppm = propParamPattern.matcher(prop); if (!ppm.find()) // Doesn't seem to be a valid vCard property continue; String propName = ppm.group(1).toUpperCase(); Vector<String> propVec = new Vector<String>(); String charSet = "UTF-8"; String encoding = ""; while (ppm.find()) { String param = ppm.group(1); String paramVal = ppm.group(3); propVec.add(param + (paramVal != null ? "=" + paramVal : "")); if (param.equalsIgnoreCase("CHARSET")) charSet = paramVal; else if (param.equalsIgnoreCase("ENCODING")) encoding = paramVal; } if (encoding.equalsIgnoreCase("QUOTED-PRINTABLE")) { try { val = QuotedPrintable.decode(val.getBytes(charSet), "UTF-8"); } catch (UnsupportedEncodingException uee) { } } else if (encoding.equalsIgnoreCase("BASE64")) { StringBuffer tmpVal = new StringBuffer(val); do { line = vCard.readLine(); if ((line == null) || (line.length() == 0) || (!base64Pattern.matcher(line).matches())) { //skipRead = true; break; } tmpVal.append(line); } while (true); Base64Coder.decodeInPlace(tmpVal); val = tmpVal.toString(); } handleProp propHandler = propHandlers.get(propName); if (propHandler != null) propHandler.parseProp(propName, propVec, val); } } return 0; } public long getParseLen() { return parseLen; } /** * Format an email as a vCard field. * * @param cardBuff Formatted email will be appended to this buffer * @param email The rowdata containing the actual email data. */ public static void formatEmail(Appendable cardBuff, RowData email) throws IOException { cardBuff.append("EMAIL;INTERNET"); if (email.preferred) cardBuff.append(";PREF"); if (email.customLabel != null) { cardBuff.append(";" + LABEL_PARAM + "="); cardBuff.append(email.customLabel); } switch (email.type) { case Contacts.ContactMethodsColumns.TYPE_WORK: cardBuff.append(";WORK"); break; } if (!StringUtil.isASCII(email.data)) cardBuff.append(";CHARSET=UTF-8"); cardBuff.append(":").append(email.data.trim()).append(NL); } /** * Format a phone as a vCard field. * * @param formatted Formatted phone will be appended to this buffer * @param phone The rowdata containing the actual phone data. */ public static void formatPhone(Appendable formatted, RowData phone) throws IOException { formatted.append("TEL"); if (phone.preferred) formatted.append(";PREF"); if (phone.customLabel != null) { formatted.append(";" + LABEL_PARAM + "="); formatted.append(phone.customLabel); } switch (phone.type) { case Contacts.PhonesColumns.TYPE_HOME: formatted.append(";VOICE"); break; case Contacts.PhonesColumns.TYPE_WORK: formatted.append(";VOICE;WORK"); break; case Contacts.PhonesColumns.TYPE_FAX_WORK: formatted.append(";FAX;WORK"); break; case Contacts.PhonesColumns.TYPE_FAX_HOME: formatted.append(";FAX;HOME"); break; case Contacts.PhonesColumns.TYPE_MOBILE: formatted.append(";CELL"); break; case Contacts.PhonesColumns.TYPE_PAGER: formatted.append(";PAGER"); break; } if (!StringUtil.isASCII(phone.data)) formatted.append(";CHARSET=UTF-8"); formatted.append(":").append(phone.data.trim()).append(NL); } /** * Format a phone as a vCard field. * * @param formatted Formatted phone will be appended to this buffer * @param addr The rowdata containing the actual phone data. */ public static void formatAddr(Appendable formatted, RowData addr) throws IOException { formatted.append("ADR"); if (addr.preferred) formatted.append(";PREF"); if (addr.customLabel != null) { formatted.append(";" + LABEL_PARAM + "="); formatted.append(addr.customLabel); } switch (addr.type) { case Contacts.ContactMethodsColumns.TYPE_HOME: formatted.append(";HOME"); break; case Contacts.PhonesColumns.TYPE_WORK: formatted.append(";WORK"); break; } if (!StringUtil.isASCII(addr.data)) formatted.append(";CHARSET=UTF-8"); formatted.append(":;;").append(addr.data.replace(", ", ";").trim()).append(NL); } /** * Format an IM contact as a vCard field. * * @param formatted Formatted im contact will be appended to this buffer * @param addr The rowdata containing the actual phone data. */ public static void formatIM(Appendable formatted, RowData im) throws IOException { formatted.append(IMPROP); if (im.preferred) formatted.append(";PREF"); if (im.customLabel != null) { formatted.append(";" + LABEL_PARAM + "="); formatted.append(im.customLabel); } switch (im.type) { case Contacts.ContactMethodsColumns.TYPE_HOME: formatted.append(";HOME"); break; case Contacts.ContactMethodsColumns.TYPE_WORK: formatted.append(";WORK"); break; } if (im.auxData != null) { formatted.append(";").append(PROTO_PARAM).append("=").append(im.auxData); } if (!StringUtil.isASCII(im.data)) formatted.append(";CHARSET=UTF-8"); formatted.append(":").append(im.data.trim()).append(NL); } /** * Format Organization fields. * * * * @param formatted Formatted organization info will be appended to this buffer * @param addr The rowdata containing the actual organization data. */ public static void formatOrg(Appendable formatted, OrgData org) throws IOException { if (org.company != null) { formatted.append("ORG"); if (org.customLabel != null) { formatted.append(";" + LABEL_PARAM + "="); formatted.append(org.customLabel); } if (!StringUtil.isASCII(org.company)) formatted.append(";CHARSET=UTF-8"); formatted.append(":").append(org.company.trim()).append(NL); if (org.title == null) formatted.append("TITLE:").append(NL); } if (org.title != null) { if (org.company == null) formatted.append("ORG:").append(NL); formatted.append("TITLE"); if (org.customLabel != null) { formatted.append(";" + LABEL_PARAM + "="); formatted.append(org.customLabel); } if (!StringUtil.isASCII(org.title)) formatted.append(";CHARSET=UTF-8"); formatted.append(":").append(org.title.trim()).append(NL); } } public String toString() { StringWriter out = new StringWriter(); try { writeVCard(out); } catch (IOException e) { // Should never happen } return out.toString(); } /** * Write the contact vCard to an appendable stream. */ public void writeVCard(Appendable vCardBuff) throws IOException { // Start vCard vCardBuff.append("BEGIN:VCARD").append(NL); vCardBuff.append("VERSION:2.1").append(NL); appendField(vCardBuff, "X-IRMC-LUID", syncid); vCardBuff.append("N"); if (!StringUtil.isASCII(lastName) || !StringUtil.isASCII(firstName)) vCardBuff.append(";CHARSET=UTF-8"); vCardBuff.append(":").append((lastName != null) ? lastName.trim() : "") .append(";").append((firstName != null) ? firstName.trim() : "") .append(";").append(";").append(";").append(NL); for (RowData email : emails) { formatEmail(vCardBuff, email); } for (RowData phone : phones) { formatPhone(vCardBuff, phone); } for (OrgData org : orgs) { formatOrg(vCardBuff, org); } for (RowData addr : addrs) { formatAddr(vCardBuff, addr); } for (RowData im : ims) { formatIM(vCardBuff, im); } appendField(vCardBuff, "NOTE", notes); appendField(vCardBuff, "BDAY", birthday); if (photo != null) { appendField(vCardBuff, "PHOTO;TYPE=JPEG;ENCODING=BASE64", " "); Base64Coder.mimeEncode(vCardBuff, photo, 76, NL); vCardBuff.append(NL); vCardBuff.append(NL); } // End vCard vCardBuff.append("END:VCARD").append(NL); } /** * Append the field to the StringBuffer out if not null. */ private static void appendField(Appendable out, String name, String val) throws IOException { if(val != null && val.length() > 0) { out.append(name); if (!StringUtil.isASCII(val)) out.append(";CHARSET=UTF-8"); out.append(":").append(val).append(NL); } } /** * Populate the contact fields from a cursor */ public void populate(Cursor peopleCur, ContentResolver cResolver) { reset(); setPeopleFields(peopleCur); String personID = _id; if (querySyncId != null) { querySyncId.bindString(1, personID); try { syncid = querySyncId.simpleQueryForString(); } catch (SQLiteDoneException e) { if (insertSyncId != null) { // Create a new syncid syncid = UUID.randomUUID().toString(); // Write the new syncid insertSyncId.bindString(1, personID); insertSyncId.bindString(2, syncid); insertSyncId.executeInsert(); } } } Cursor organization = cResolver.query(Contacts.Organizations.CONTENT_URI, null, Contacts.OrganizationColumns.PERSON_ID + "=" + personID, null, null); // Set the organization fields if (organization.moveToFirst()) { do { setOrganizationFields(organization); } while (organization.moveToNext()); } organization.close(); Cursor phones = cResolver.query(Contacts.Phones.CONTENT_URI, null, Contacts.Phones.PERSON_ID + "=" + personID, null, null); // Set all the phone numbers if (phones.moveToFirst()) { do { setPhoneFields(phones); } while (phones.moveToNext()); } phones.close(); Cursor contactMethods = cResolver.query(Contacts.ContactMethods.CONTENT_URI, null, Contacts.ContactMethods.PERSON_ID + "=" + personID, null, null); // Set all the contact methods (emails, addresses, ims) if (contactMethods.moveToFirst()) { do { setContactMethodsFields(contactMethods); } while (contactMethods.moveToNext()); } contactMethods.close(); // Load a photo if one exists. Cursor contactPhoto = cResolver.query(Contacts.Photos.CONTENT_URI, null, Contacts.PhotosColumns.PERSON_ID + "=" + personID, null, null); if (contactPhoto.moveToFirst()) { photo = contactPhoto.getBlob(contactPhoto.getColumnIndex(Contacts.PhotosColumns.DATA)); } contactPhoto.close(); } /** * Retrieve the People fields from a Cursor */ private void setPeopleFields(Cursor cur) { int selectedColumn; // Set the contact id selectedColumn = cur.getColumnIndex(Contacts.People._ID); long nid = cur.getLong(selectedColumn); _id = String.valueOf(nid); // // Get PeopleColumns fields // selectedColumn = cur.getColumnIndex(Contacts.PeopleColumns.NAME); displayName = cur.getString(selectedColumn); if (displayName != null) { Matcher m = namePattern.matcher(displayName); if (m.matches()) { if (m.group(1) != null) { lastName = m.group(2); firstName = m.group(3); } else { firstName = m.group(5); lastName = m.group(6); } } else { firstName = displayName; lastName = ""; } } else { firstName = lastName = ""; } selectedColumn = cur.getColumnIndex(Contacts.People.NOTES); notes = cur.getString(selectedColumn); if (notes != null) { Matcher ppm = birthdayPattern.matcher(notes); if (ppm.find()) { birthday = ppm.group(1); notes = ppm.replaceFirst(""); } } } /** * Retrieve the organization fields from a Cursor */ private void setOrganizationFields(Cursor cur) { int selectedColumn; // // Get Organizations fields // selectedColumn = cur.getColumnIndex(Contacts.OrganizationColumns.COMPANY); String company = cur.getString(selectedColumn); selectedColumn = cur.getColumnIndex(Contacts.OrganizationColumns.TITLE); String title = cur.getString(selectedColumn); selectedColumn = cur.getColumnIndex(Contacts.OrganizationColumns.TYPE); int orgType = cur.getInt(selectedColumn); String customLabel = null; if (orgType == Contacts.ContactMethodsColumns.TYPE_CUSTOM) { selectedColumn = cur .getColumnIndex(Contacts.ContactMethodsColumns.LABEL); customLabel = cur.getString(selectedColumn); } orgs.add(new OrgData(orgType, title, company, customLabel)); } /** * Retrieve the Phone fields from a Cursor */ private void setPhoneFields(Cursor cur) { int selectedColumn; int selectedColumnType; int preferredColumn; int phoneType; String customLabel = null; // // Get PhonesColums fields // selectedColumn = cur.getColumnIndex(Contacts.PhonesColumns.NUMBER); selectedColumnType = cur.getColumnIndex(Contacts.PhonesColumns.TYPE); preferredColumn = cur.getColumnIndex(Contacts.PhonesColumns.ISPRIMARY); phoneType = cur.getInt(selectedColumnType); String phone = cur.getString(selectedColumn); boolean preferred = cur.getInt(preferredColumn) != 0; if (phoneType == Contacts.PhonesColumns.TYPE_CUSTOM) { customLabel = cur.getString(cur.getColumnIndex(Contacts.PhonesColumns.LABEL)); } phones.add(new RowData(phoneType, phone, preferred, customLabel)); } /** * Retrieve the email fields from a Cursor */ private void setContactMethodsFields(Cursor cur) { int selectedColumn; int selectedColumnType; int selectedColumnKind; int selectedColumnPrimary; int selectedColumnLabel; int methodType; int kind; String customLabel = null; String auxData = null; // // Get ContactsMethodsColums fields // selectedColumn = cur .getColumnIndex(Contacts.ContactMethodsColumns.DATA); selectedColumnType = cur .getColumnIndex(Contacts.ContactMethodsColumns.TYPE); selectedColumnKind = cur .getColumnIndex(Contacts.ContactMethodsColumns.KIND); selectedColumnPrimary = cur .getColumnIndex(Contacts.ContactMethodsColumns.ISPRIMARY); kind = cur.getInt(selectedColumnKind); methodType = cur.getInt(selectedColumnType); String methodData = cur.getString(selectedColumn); boolean preferred = cur.getInt(selectedColumnPrimary) != 0; if (methodType == Contacts.ContactMethodsColumns.TYPE_CUSTOM) { selectedColumnLabel = cur .getColumnIndex(Contacts.ContactMethodsColumns.LABEL); customLabel = cur.getString(selectedColumnLabel); } switch (kind) { case Contacts.KIND_EMAIL: emails.add(new RowData(methodType, methodData, preferred, customLabel)); break; case Contacts.KIND_POSTAL: addrs.add(new RowData(methodType, methodData, preferred, customLabel)); break; case Contacts.KIND_IM: RowData newRow = new RowData(methodType, methodData, preferred, customLabel); selectedColumn = cur.getColumnIndex(Contacts.ContactMethodsColumns.AUX_DATA); auxData = cur.getString(selectedColumn); if (auxData != null) { String[] auxFields = StringUtil.split(auxData, ":"); if (auxFields.length > 1) { if (auxFields[0].equalsIgnoreCase("pre")) { int protval = 0; try { protval = Integer.decode(auxFields[1]); } catch (NumberFormatException e) { // Do nothing; protval = 0 } if (protval < 0 || protval >= PROTO.length) protval = 0; newRow.auxData = PROTO[protval]; } else if (auxFields[0].equalsIgnoreCase("custom")) { newRow.auxData = auxFields[1]; } } else { newRow.auxData = auxData; } } ims.add(newRow); break; } } public ContentValues getPeopleCV() { ContentValues cv = new ContentValues(); StringBuffer fullname = new StringBuffer(); if (displayName != null) fullname.append(displayName); else { if (firstName != null) fullname.append(firstName); if (lastName != null) { if (firstName != null) fullname.append(" "); fullname.append(lastName); } } // Use company name if only the company is given. if (fullname.length() == 0 && orgs.size() > 0 && orgs.get(0).company != null) fullname.append(orgs.get(0).company); cv.put(Contacts.People.NAME, fullname.toString()); if (!StringUtil.isNullOrEmpty(_id)) { cv.put(Contacts.People._ID, _id); } StringBuffer allnotes = new StringBuffer(); if (birthday != null) { allnotes.append(BIRTHDAY_FIELD).append(" ").append(birthday); } if (notes != null) { if (birthday != null) { allnotes.append(";\n"); } allnotes.append(notes); } if (allnotes.length() > 0) cv.put(Contacts.People.NOTES, allnotes.toString()); return cv; } public ContentValues getOrganizationCV(OrgData org) { if(StringUtil.isNullOrEmpty(org.company) && StringUtil.isNullOrEmpty(org.title)) { return null; } ContentValues cv = new ContentValues(); cv.put(Contacts.Organizations.COMPANY, org.company); cv.put(Contacts.Organizations.TITLE, org.title); cv.put(Contacts.Organizations.TYPE, org.type); cv.put(Contacts.Organizations.PERSON_ID, _id); if (org.customLabel != null) { cv.put(Contacts.Organizations.LABEL, org.customLabel); } return cv; } public ContentValues getPhoneCV(RowData data) { ContentValues cv = new ContentValues(); cv.put(Contacts.Phones.NUMBER, data.data); cv.put(Contacts.Phones.TYPE, data.type); cv.put(Contacts.Phones.ISPRIMARY, data.preferred ? 1 : 0); cv.put(Contacts.Phones.PERSON_ID, _id); if (data.customLabel != null) { cv.put(Contacts.Phones.LABEL, data.customLabel); } return cv; } public ContentValues getEmailCV(RowData data) { ContentValues cv = new ContentValues(); cv.put(Contacts.ContactMethods.DATA, data.data); cv.put(Contacts.ContactMethods.TYPE, data.type); cv.put(Contacts.ContactMethods.KIND, Contacts.KIND_EMAIL); cv.put(Contacts.ContactMethods.ISPRIMARY, data.preferred ? 1 : 0); cv.put(Contacts.ContactMethods.PERSON_ID, _id); if (data.customLabel != null) { cv.put(Contacts.ContactMethods.LABEL, data.customLabel); } return cv; } public ContentValues getAddressCV(RowData data) { ContentValues cv = new ContentValues(); cv.put(Contacts.ContactMethods.DATA, data.data); cv.put(Contacts.ContactMethods.TYPE, data.type); cv.put(Contacts.ContactMethods.KIND, Contacts.KIND_POSTAL); cv.put(Contacts.ContactMethods.ISPRIMARY, data.preferred ? 1 : 0); cv.put(Contacts.ContactMethods.PERSON_ID, _id); if (data.customLabel != null) { cv.put(Contacts.ContactMethods.LABEL, data.customLabel); } return cv; } public ContentValues getImCV(RowData data) { ContentValues cv = new ContentValues(); cv.put(Contacts.ContactMethods.DATA, data.data); cv.put(Contacts.ContactMethods.TYPE, data.type); cv.put(Contacts.ContactMethods.KIND, Contacts.KIND_IM); cv.put(Contacts.ContactMethods.ISPRIMARY, data.preferred ? 1 : 0); cv.put(Contacts.ContactMethods.PERSON_ID, _id); if (data.customLabel != null) { cv.put(Contacts.ContactMethods.LABEL, data.customLabel); } if (data.auxData != null) { int protoNum = -1; for (int i = 0; i < PROTO.length; ++i) { if (data.auxData.equalsIgnoreCase(PROTO[i])) { protoNum = i; break; } } if (protoNum >= 0) { cv.put(Contacts.ContactMethods.AUX_DATA, "pre:"+protoNum); } else { cv.put(Contacts.ContactMethods.AUX_DATA, "custom:"+data.auxData); } } return cv; } /** * Add a new contact to the Content Resolver * * @param key the row number of the existing contact (if known) * @return The row number of the inserted column */ public long addContact(Context context, long key, boolean replace) { ContentResolver cResolver = context.getContentResolver(); ContentValues pCV = getPeopleCV(); boolean addSyncId = false; boolean replacing = false; if (key <= 0 && syncid != null) { if (queryPersonId != null) try { queryPersonId.bindString(1, syncid); setId(queryPersonId.simpleQueryForString()); key = getId(); } catch(SQLiteDoneException e) { // Couldn't locate syncid, we'll add it; // need to wait until we know what the key is, though. addSyncId = true; } } Uri newContactUri = null; if (key > 0) { newContactUri = ContentUris.withAppendedId(Contacts.People.CONTENT_URI, key); Cursor testit = cResolver.query(newContactUri, null, null, null, null); if (testit == null || testit.getCount() == 0) { newContactUri = null; pCV.put(Contacts.People._ID, key); } if (testit != null) testit.close(); } if (newContactUri == null) { newContactUri = insertContentValues(cResolver, Contacts.People.CONTENT_URI, pCV); if (newContactUri == null) { Log.error("Error adding contact." + " (key: " + key + ")"); return -1; } // Set the contact person id setId(newContactUri.getLastPathSegment()); key = getId(); // Add the new contact to the myContacts group Contacts.People.addToMyContactsGroup(cResolver, key); } else { // update existing Uri if (!replace) return -1; replacing = true; cResolver.update(newContactUri, pCV, null, null); } // We need to add the syncid to the database so // that we'll detect this contact if we try to import // it again. if (addSyncId && insertSyncId != null) { insertSyncId.bindLong(1, key); insertSyncId.bindString(2, syncid); insertSyncId.executeInsert(); } /* * Insert all the new ContentValues */ if (replacing) { // Remove existing phones Uri phones = Uri.withAppendedPath(ContentUris.withAppendedId(Contacts.People.CONTENT_URI, key), Contacts.People.Phones.CONTENT_DIRECTORY); String[] phoneID = {Contacts.People.Phones._ID}; Cursor existingPhones = cResolver.query(phones, phoneID, null, null, null); if (existingPhones != null && existingPhones.moveToFirst()) { int idColumn = existingPhones.getColumnIndex(Contacts.People.Phones._ID); List<Long> ids = new ArrayList<Long>(existingPhones.getCount()); do { ids.add(existingPhones.getLong(idColumn)); } while (existingPhones.moveToNext()); existingPhones.close(); for (Long id : ids) { Uri phone = ContentUris.withAppendedId(Contacts.Phones.CONTENT_URI, id); cResolver.delete(phone, null, null); } } // Remove existing contact methods (emails, addresses, etc.) Uri methods = Uri.withAppendedPath(ContentUris.withAppendedId(Contacts.People.CONTENT_URI, key), Contacts.People.ContactMethods.CONTENT_DIRECTORY); String[] methodID = {Contacts.People.ContactMethods._ID}; Cursor existingMethods = cResolver.query(methods, methodID, null, null, null); if (existingMethods != null && existingMethods.moveToFirst()) { int idColumn = existingMethods.getColumnIndex(Contacts.People.ContactMethods._ID); List<Long> ids = new ArrayList<Long>(existingMethods.getCount()); do { ids.add(existingMethods.getLong(idColumn)); } while (existingMethods.moveToNext()); existingMethods.close(); for (Long id : ids) { Uri method = ContentUris.withAppendedId(Contacts.Phones.CONTENT_URI, id); cResolver.delete(method, null, null); } } } // Phones for (RowData phone : phones) { insertContentValues(cResolver, Contacts.Phones.CONTENT_URI, getPhoneCV(phone)); } // Organizations for (OrgData org : orgs) { insertContentValues(cResolver, Contacts.Organizations.CONTENT_URI, getOrganizationCV(org)); } Builder builder = newContactUri.buildUpon(); builder.appendEncodedPath(Contacts.ContactMethods.CONTENT_URI.getPath()); // Emails for (RowData email : emails) { insertContentValues(cResolver, builder.build(), getEmailCV(email)); } // Addressess for (RowData addr : addrs) { insertContentValues(cResolver, builder.build(), getAddressCV(addr)); } // IMs for (RowData im : ims) { insertContentValues(cResolver, builder.build(), getImCV(im)); } // Photo if (photo != null) { Uri person = ContentUris.withAppendedId(Contacts.People.CONTENT_URI, key); Contacts.People.setPhotoData(cResolver, person, photo); } return key; } /** * Insert a new ContentValues raw into the Android ContentProvider */ private Uri insertContentValues(ContentResolver cResolver, Uri uri, ContentValues cv) { if (cv != null) { return cResolver.insert(uri, cv); } return null; } /** * Get the item content */ public String getContent() { return toString(); } /** * Check if the email string is well formatted */ @SuppressWarnings("unused") private boolean checkEmail(String email) { return (email != null && !"".equals(email) && email.indexOf("@") != -1); } }
Java
package vcard.io; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class App extends Activity { /** Called when the activity is first created. */ boolean isActive; Handler mHandler = new Handler(); VCardIO mBoundService = null; int mLastProgress; TextView mStatusText = null; CheckBox mReplaceOnImport = null; @Override protected void onPause() { isActive = false; super.onPause(); } @Override protected void onResume() { super.onResume(); isActive = true; updateProgress(mLastProgress); } protected void updateProgress(final int progress) { // Update the progress bar mHandler.post(new Runnable() { public void run() { if (isActive) { setProgress(progress * 100); if (progress == 100) mStatusText.setText("Done"); } else { mLastProgress = progress; } } }); } void updateStatus(final String status) { // Update the progress bar mHandler.post(new Runnable() { public void run() { if (isActive) { mStatusText.setText(status); } } }); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Request the progress bar to be shown in the title requestWindowFeature(Window.FEATURE_PROGRESS); setProgress(10000); // Turn it off for now setContentView(R.layout.main); Button importButton = (Button) findViewById(R.id.ImportButton); Button exportButton = (Button) findViewById(R.id.ExportButton); mStatusText = ((TextView) findViewById(R.id.StatusText)); mReplaceOnImport = ((CheckBox) findViewById(R.id.ReplaceOnImport)); final Intent app = new Intent(App.this, VCardIO.class); OnClickListener listenImport = new OnClickListener() { public void onClick(View v) { // Make sure the service is started. It will continue running // until someone calls stopService(). The Intent we use to find // the service explicitly specifies our service component, because // we want it running in our own process and don't want other // applications to replace it. if (mBoundService != null) { String fileName = ((EditText) findViewById(R.id.ImportFile)).getText().toString(); // Update the progress bar setProgress(0); mStatusText.setText("Importing Contacts..."); // Start the import mBoundService.doImport(fileName, mReplaceOnImport.isChecked(), App.this); } } }; OnClickListener listenExport = new OnClickListener() { public void onClick(View v) { // Make sure the service is started. It will continue running // until someone calls stopService(). The Intent we use to find // the service explicitly specifies our service component, because // we want it running in our own process and don't want other // applications to replace it. if (mBoundService != null) { String fileName = ((EditText) findViewById(R.id.ExportFile)).getText().toString(); // Update the progress bar setProgress(0); mStatusText.setText("Exporting Contacts..."); // Start the import mBoundService.doExport(fileName, App.this); } } }; // Start the service using startService so it won't be stopped when activity is in background. startService(app); bindService(app, mConnection, Context.BIND_AUTO_CREATE); importButton.setOnClickListener(listenImport); exportButton.setOnClickListener(listenExport); } private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { // This is called when the connection with the service has been // established, giving us the service object we can use to // interact with the service. Because we have bound to a explicit // service that we know is running in our own process, we can // cast its IBinder to a concrete class and directly access it. mBoundService = ((VCardIO.LocalBinder)service).getService(); // Tell the user about this for our demo. Toast.makeText(App.this, "Connected to VCard IO Service", Toast.LENGTH_SHORT).show(); } public void onServiceDisconnected(ComponentName className) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. // Because it is running in our same process, we should never // see this happen. mBoundService = null; Toast.makeText(App.this, "Disconnected from VCard IO!", Toast.LENGTH_SHORT).show(); } }; }
Java
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.storage; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; /** * A simple interface to serialize objects on j2ME platform */ public interface Serializable { /** * Write object fields to the output stream. * @param out Output stream * @throws IOException */ void serialize(DataOutputStream out) throws IOException; /** * Read object field from the input stream. * @param in Input stream * @throws IOException */ void deserialize(DataInputStream in) throws IOException; }
Java
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.storage; /** * Represents a <i>"update"</i> error on device database. */ public class DataAccessException extends Exception { /** * */ private static final long serialVersionUID = -6695128856314376170L; /** * Creates a new instance of <code>DataAccessException</code> * without detail message. */ public DataAccessException() { } /** * Constructs an instance of <p><code>DataAccessException</code></p> * with the specified detail message. * @param msg the detail message. */ public DataAccessException(String msg) { super(msg); } }
Java
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.util; import java.io.UnsupportedEncodingException; /** * A class containing static methods to perform decoding from <b>quoted * printable</b> content transfer encoding and to encode into */ public class QuotedPrintable { private static byte HT = 0x09; // \t private static byte LF = 0x0A; // \n private static byte CR = 0x0D; // \r /** * A method to decode quoted printable encoded data. * It overrides the same input byte array to save memory. Can be done * because the result is surely smaller than the input. * * @param qp * a byte array to decode. * @return the length of the decoded array. */ public static int decode(byte [] qp) { int qplen = qp.length; int retlen = 0; for (int i=0; i < qplen; i++) { // Handle encoded chars if (qp[i] == '=') { if (qplen - i > 2) { // The sequence can be complete, check it if (qp[i+1] == CR && qp[i+2] == LF) { // soft line break, ignore it i += 2; continue; } else if (isHexDigit(qp[i+1]) && isHexDigit(qp[i+2]) ) { // convert the number into an integer, taking // the ascii digits stored in the array. qp[retlen++]=(byte)(getHexValue(qp[i+1])*16 + getHexValue(qp[i+2])); i += 2; continue; } else { Log.error("decode: Invalid sequence = " + qp[i+1] + qp[i+2]); } } // In all wrong cases leave the original bytes // (see RFC 2045). They can be incomplete sequence, // or a '=' followed by non hex digit. } // RFC 2045 says to exclude control characters mistakenly // present (unencoded) in the encoded stream. // As an exception, we keep unencoded tabs (0x09) if( (qp[i] >= 0x20 && qp[i] <= 0x7f) || qp[i] == HT || qp[i] == CR || qp[i] == LF) { qp[retlen++] = qp[i]; } } return retlen; } private static boolean isHexDigit(byte b) { return ( (b>=0x30 && b<=0x39) || (b>=0x41&&b<=0x46) ); } private static byte getHexValue(byte b) { return (byte)Character.digit((char)b, 16); } /** * * @param qp Byte array to decode * @param enc The character encoding of the returned string * @return The decoded string. */ public static String decode(byte[] qp, String enc) { int len=decode(qp); try { return new String(qp, 0, len, enc); } catch (UnsupportedEncodingException e) { Log.error("qp.decode: "+ enc + " not supported. " + e.toString()); return new String(qp, 0, len); } } /** * A method to encode data in quoted printable * * @param content * The string to be encoded * @return the encoded string. * @throws Exception * public static byte[] encode(String content, String enc) throws Exception { // TODO: to be implemented (has to return a String) throw new Exception("This method is not implemented!"); } */ /** * A method to encode data in quoted printable * * @param content * The string to be encoded * @return the encoded string. * @throws Exception * public static byte[] encode(byte[] content) throws Exception { // TODO: to be implemented (has to return a String) throw new Exception("This method is not implemented!"); } */ }
Java
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.util; import java.util.Vector; /** * Utility class useful when dealing with string objects. * This class is a collection of static functions, and the usage is: * * StringUtil.method() * * it is not allowed to create instances of this class */ public class StringUtil { private static final String HT = "\t"; private static final String CRLF = "\r\n"; // This class cannot be instantiated private StringUtil() { } /** * Split the string into an array of strings using one of the separator * in 'sep'. * * @param s the string to tokenize * @param sep a list of separator to use * * @return the array of tokens (an array of size 1 with the original * string if no separator found) */ public static String[] split(String s, String sep) { // convert a String s to an Array, the elements // are delimited by sep Vector<Integer> tokenIndex = new Vector<Integer>(10); int len = s.length(); int i; // Find all characters in string matching one of the separators in 'sep' for (i = 0; i < len; i++) { if (sep.indexOf(s.charAt(i)) != -1 ){ tokenIndex.addElement(new Integer(i)); } } int size = tokenIndex.size(); String[] elements = new String[size+1]; // No separators: return the string as the first element if(size == 0) { elements[0] = s; } else { // Init indexes int start = 0; int end = (tokenIndex.elementAt(0)).intValue(); // Get the first token elements[0] = s.substring(start, end); // Get the mid tokens for (i=1; i<size; i++) { // update indexes start = (tokenIndex.elementAt(i-1)).intValue()+1; end = (tokenIndex.elementAt(i)).intValue(); elements[i] = s.substring(start, end); } // Get last token start = (tokenIndex.elementAt(i-1)).intValue()+1; elements[i] = (start < s.length()) ? s.substring(start) : ""; } return elements; } /** * Split the string into an array of strings using one of the separator * in 'sep'. * * @param list the string array to join * @param sep the separator to use * * @return the joined string */ public static String join(String[] list, String sep) { StringBuffer buffer = new StringBuffer(list[0]); int len = list.length; for (int i = 1; i < len; i++) { buffer.append(sep).append(list[i]); } return buffer.toString(); } /** * Returns the string array * @param stringVec the Vecrot of tring to convert * @return String [] */ public static String[] getStringArray(Vector<String> stringVec){ if(stringVec==null){ return null; } String[] stringArray=new String[stringVec.size()]; for(int i=0;i<stringVec.size();i++){ stringArray[i]=stringVec.elementAt(i); } return stringArray; } /** * Find two consecutive newlines in a string. * @param s - The string to search * @return int: the position of the empty line */ public static int findEmptyLine(String s){ int ret = 0; // Find a newline while( (ret = s.indexOf("\n", ret)) != -1 ){ // Skip carriage returns, if any while(s.charAt(ret) == '\r'){ ret++; } if(s.charAt(ret) == '\n'){ // Okay, it was empty ret ++; break; } } return ret; } /** * Removes unwanted blank characters * @param content * @return String */ public static String removeBlanks(String content){ if(content==null){ return null; } StringBuffer buff = new StringBuffer(); buff.append(content); for(int i = buff.length()-1; i >= 0;i--){ if(' ' == buff.charAt(i)){ buff.deleteCharAt(i); } } return buff.toString(); } /** * Removes unwanted backslashes characters * * @param content The string containing the backslashes to be removed * @return the content without backslashes */ public static String removeBackslashes(String content){ if (content == null) { return null; } StringBuffer buff = new StringBuffer(); buff.append(content); int len = buff.length(); for (int i = len - 1; i >= 0; i--) { if ('\\' == buff.charAt(i)) buff.deleteCharAt(i); } return buff.toString(); } /** * Builds a list of the recipients email addresses each on a different line, * starting just from the second line with an HT ("\t") separator at the * head of the line. This is an implementation of the 'folding' concept from * the RFC 2822 (par. 2.2.3) * * @param recipients * A string containing all recipients comma-separated * @return A string containing the email list of the recipients spread over * more lines, ended by CRLF and beginning from the second with the * WSP defined in the RFC 2822 */ public static String fold(String recipients) { String[] list = StringUtil.split(recipients, ","); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < list.length; i++) { String address = list[i] + (i != list.length - 1 ? "," : ""); buffer.append(i == 0 ? address + CRLF : HT + address + CRLF); } return buffer.toString(); } /** * This method is missing in CLDC 1.0 String implementation */ public static boolean equalsIgnoreCase(String string1, String string2) { // Strings are both null, return true if (string1 == null && string2 == null) { return true; } // One of the two is null, return false if (string1 == null || string2 == null) { return false; } // Both are not null, compare the lowercase strings if ((string1.toLowerCase()).equals(string2.toLowerCase())) { return true; } else { return false; } } /** * Util method for retrieve a boolean primitive type from a String. * Implemented because Boolean class doesn't provide * parseBoolean() method */ public static boolean getBooleanValue(String string) { if ((string == null) || string.equals("")) { return false; } else { if (StringUtil.equalsIgnoreCase(string, "true")) { return true; } else { return false; } } } /** * Removes characters 'c' from the beginning and the end of the string */ public static String trim(String s, char c) { int start = 0; int end = s.length()-1; while(s.charAt(start) == c) { if(++start >= end) { // The string is made by c only return ""; } } while(s.charAt(end) == c) { if(--end <= start) { return ""; } } return s.substring(start, end+1); } /** * Returns true if the given string is null or empty. */ public static boolean isNullOrEmpty(String str) { if (str==null) { return true; } if (str.trim().equals("")) { return true; } return false; } /** * Returns true if the string does not fit in standard ASCII */ public static boolean isASCII(String str) { if (str == null) return true; for (int i = 0; i < str.length(); ++i) { char c = str.charAt(i); if (c < 0 || c > 0x7f) return false; } return true; } }
Java
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.util; import com.funambol.storage.DataAccessException; public interface Appender { /** * Initialize Log File */ void initLogFile(); /** * Open Log file */ void openLogFile(); /** * Close Log file */ void closeLogFile(); /** * Delete Log file */ void deleteLogFile(); /** * Append a message to the Log file */ void writeLogMessage(String level, String msg) throws DataAccessException; }
Java
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.util; import java.util.Calendar; import java.util.Date; /** * A utility class providing methods to convert date information contained in * <code>Date</code> objects into RFC2822 and UTC ('Zulu') strings, and to * build <code>Date</code> objects starting from string representations of * dates in RFC2822 and UTC format */ public class MailDateFormatter { /** Format date as: MM/DD */ public static final int FORMAT_MONTH_DAY = 0; /** Format date as: MM/DD/YYYY */ public static final int FORMAT_MONTH_DAY_YEAR = 1; /** Format date as: hh:mm */ public static final int FORMAT_HOURS_MINUTES = 2; /** Format date as: hh:mm:ss */ public static final int FORMAT_HOURS_MINUTES_SECONDS = 3; /** Format date as: DD/MM */ public static final int FORMAT_DAY_MONTH = 4; /** Format date as: DD/MM/YYYY */ public static final int FORMAT_DAY_MONTH_YEAR = 5; /** Device offset, as string */ private static String deviceOffset = "+0000"; /** Device offset, in millis */ private static long millisDeviceOffset = 0; /** Names of the months */ private static String[] monthNames = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; /** * Transforms data contained in a <code>Date</code> object (expressed in * UTC) in a string formatted as per RFC2822 in local time (par. 3.3) * * @return A string representing the date contained in the passed * <code>Date</code> object formatted as per RFC 2822 and in local * time */ public static String dateToRfc2822(Date date) { Calendar deviceTime = Calendar.getInstance(); deviceTime.setTime(date); String dayweek = ""; int dayOfWeek = deviceTime.get(Calendar.DAY_OF_WEEK); switch (dayOfWeek) { case 1 : dayweek = "Sun"; break; case 2 : dayweek = "Mon"; break; case 3 : dayweek = "Tue"; break; case 4 : dayweek = "Wed"; break; case 5 : dayweek = "Thu"; break; case 6 : dayweek = "Fri"; break; case 7 : dayweek = "Sat"; break; } int dayOfMonth = deviceTime.get(Calendar.DAY_OF_MONTH); String monthInYear = getMonthName(deviceTime.get(Calendar.MONTH)); int year = deviceTime.get(Calendar.YEAR); int hourOfDay = deviceTime.get(Calendar.HOUR_OF_DAY); int minutes = deviceTime.get(Calendar.MINUTE); int seconds = deviceTime.get(Calendar.SECOND); String rfc = dayweek + ", " + // Tue dayOfMonth + " " + // 7 monthInYear + " " + // Nov year + " " + // 2006 hourOfDay + ":" + minutes + ":" + seconds + " " + // 14:13:26 deviceOffset; //+0200 return rfc; } /** * Converts a <code>Date</code> object into a string in 'Zulu' format * * @param d * A <code>Date</code> object to be converted into a string in * 'Zulu' format * @return A string representing the date contained in the passed * <code>Date</code> object in 'Zulu' format (e.g. * yyyyMMDDThhmmssZ) */ public static String dateToUTC(Date d) { StringBuffer date = new StringBuffer(); Calendar cal = Calendar.getInstance(); cal.setTime(d); date.append(cal.get(Calendar.YEAR)); date.append(printTwoDigits(cal.get(Calendar.MONTH) + 1)) .append(printTwoDigits(cal.get(Calendar.DATE))) .append("T"); date.append(printTwoDigits(cal.get(Calendar.HOUR_OF_DAY))) .append(printTwoDigits(cal.get(Calendar.MINUTE))) .append(printTwoDigits(cal.get(Calendar.SECOND))) .append("Z"); return date.toString(); } /** * A method that returns a string rapresenting a date. * * @param date the date * * @param format the format as one of * FORMAT_MONTH_DAY, * FORMAT_MONTH_DAY_YEAR, * FORMAT_HOURS_MINUTES, * FORMAT_HOURS_MINUTES_SECONDS * FORMAT_DAY_MONTH * FORMAT_DAY_MONTH_YEAR * constants * * @param separator the separator to be used */ public static String getFormattedStringFromDate( Date date, int format, String separator) { Calendar cal=Calendar.getInstance(); cal.setTime(date); StringBuffer ret = new StringBuffer(); switch (format) { case FORMAT_HOURS_MINUTES: //if pm and hour == 0 we want to write 12, not 0 if (cal.get(Calendar.AM_PM)==Calendar.PM && cal.get(Calendar.HOUR) == 0) { ret.append("12"); } else { ret.append(cal.get(Calendar.HOUR)); } ret.append(separator) .append(printTwoDigits(cal.get(Calendar.MINUTE))) .append(getAMPM(cal)); break; case FORMAT_HOURS_MINUTES_SECONDS: //if pm and hour == 0 we want to write 12, not 0 if (cal.get(Calendar.AM_PM)==Calendar.PM && cal.get(Calendar.HOUR) == 0) { ret.append("12"); } else { ret.append(cal.get(Calendar.HOUR)); } ret.append(separator) .append(printTwoDigits(cal.get(Calendar.MINUTE))) .append(separator) .append(cal.get(Calendar.SECOND)) .append(getAMPM(cal)); break; case FORMAT_MONTH_DAY: ret.append(cal.get(Calendar.MONTH)+1) .append(separator) .append(cal.get(Calendar.DAY_OF_MONTH)); break; case FORMAT_DAY_MONTH: ret.append(cal.get(Calendar.DAY_OF_MONTH)) .append(separator) .append(cal.get(Calendar.MONTH)+1); break; case FORMAT_MONTH_DAY_YEAR: ret.append(cal.get(Calendar.MONTH)+1) .append(separator) .append(cal.get(Calendar.DAY_OF_MONTH)) .append(separator) .append(cal.get(Calendar.YEAR)); break; case FORMAT_DAY_MONTH_YEAR: ret.append(cal.get(Calendar.DAY_OF_MONTH)) .append(separator) .append(cal.get(Calendar.MONTH)+1) .append(separator) .append(cal.get(Calendar.YEAR)); break; default: Log.error("getFormattedStringFromDate: invalid format ("+ format+")"); } return ret.toString(); } /** * Returns a localized string representation of Date. */ public static String formatLocalTime(Date d) { int dateFormat = FORMAT_MONTH_DAY_YEAR; int timeFormat = FORMAT_HOURS_MINUTES; if(!System.getProperty("microedition.locale").equals("en")) { dateFormat = FORMAT_DAY_MONTH_YEAR; } return getFormattedStringFromDate(d,dateFormat,"/") +" "+getFormattedStringFromDate(d,timeFormat,":"); } /** * Parses the string in RFC 2822 format and return a <code>Date</code> * object. <p> * Parse strings like: * Thu, 03 May 2007 14:45:38 GMT * Thu, 03 May 2007 14:45:38 GMT+0200 * Thu, 1 Feb 2007 03:57:01 -0800 * Fri, 04 May 2007 13:40:17 PDT * * @param d the date representation to parse * @return a date, if valid, or null on error * */ public static Date parseRfc2822Date(String stringDate) { if (stringDate == null) { return null; } long hourOffset=0; long minOffset=0; Calendar cal = Calendar.getInstance(); try { Log.info("Date original: " + stringDate); // Just skip the weekday if present int start = stringDate.indexOf(','); //put start after ", " start = (start == -1) ? 0 : start + 2; stringDate = stringDate.substring(start).trim(); start = 0; // Get day of month int end = stringDate.indexOf(' ', start); int day =1; try { day = Integer.parseInt(stringDate.substring(start, end)); } catch (NumberFormatException ex) { // some phones (Nokia 6111) have a invalid date format, // something like Tue10 Jul... instead of Tue, 10 // so we try to strip (again) the weekday day = Integer.parseInt(stringDate.substring(start+3, end)); Log.info("Nokia 6111 patch applied."); } cal.set(Calendar.DAY_OF_MONTH,day); // Get month start = end + 1; end = stringDate.indexOf(' ', start); cal.set(Calendar.MONTH, getMonthNumber(stringDate.substring(start, end))); // Get year start = end + 1; end = stringDate.indexOf(' ', start); cal.set(Calendar.YEAR, Integer.parseInt(stringDate.substring(start, end))); // Get hour start = end + 1; end = stringDate.indexOf(':', start); cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(stringDate.substring(start, end).trim())); // Get min start = end + 1; end = stringDate.indexOf(':', start); cal.set(Calendar.MINUTE, Integer.parseInt(stringDate.substring(start, end))); // Get sec start = end + 1; end = stringDate.indexOf(' ', start); cal.set(Calendar.SECOND, Integer.parseInt(stringDate.substring(start, end))); // Get OFFSET start = end +1; end = stringDate.indexOf('\r', start); // Process Timezone, checking first for the actual RFC2822 format, // and then for nthe obsolete syntax. char sign = '+'; String hourDiff = "0"; String minDiff = "0"; String offset = stringDate.substring(start).trim(); if (offset.startsWith("+") || offset.startsWith("-")) { if(offset.length() >= 5 ){ sign = offset.charAt(0); hourDiff = offset.substring(1,3); minDiff = offset.substring(3,5); } else if(offset.length() == 3){ sign = offset.charAt(0); hourDiff = offset.substring(1); minDiff = "00"; } // Convert offset to int hourOffset = Long.parseLong(hourDiff); minOffset = Long.parseLong(minDiff); if(sign == '-') { hourOffset = -hourOffset; } } else if(offset.equals("EDT")){ hourOffset = -4; } else if(offset.equals("EST") || offset.equals("CDT")){ hourOffset = -5; } else if(offset.equals("CST") || offset.equals("MDT")){ hourOffset = -6; } else if(offset.equals("PDT") || offset.equals("MST")){ hourOffset = -7; } else if(offset.equals("PST")){ hourOffset = -8; } else if(offset.equals("GMT") || offset.equals("UT")){ hourOffset = 0; } else if (offset.substring(0,3).equals("GMT") && offset.length() > 3){ sign = offset.charAt(3); hourDiff = offset.substring(4,6); minDiff = offset.substring(6,8); } long millisOffset = (hourOffset * 3600000) + (minOffset * 60000); Date gmtDate = cal.getTime(); long millisDate = gmtDate.getTime(); millisDate -= millisOffset; gmtDate.setTime(millisDate); return gmtDate; } catch (Exception e) { Log.error("Exception in parseRfc2822Date: " + e.toString() + " parsing " + stringDate); e.printStackTrace(); return null; } } /** * Convert the given date (GMT) into the local date. * NOTE: changes the original date too! * Should we change it to a void toLocalDate(Date) that changes the * input date only? */ public static Date getDeviceLocalDate (Date gmtDate){ if (null != gmtDate){ /*long dateInMillis = gmtDate.getTime(); Date deviceDate = new Date(); deviceDate.setTime(dateInMillis+millisDeviceOffset); return deviceDate; **/ gmtDate.setTime(gmtDate.getTime()+millisDeviceOffset); return gmtDate; } else { return null; } } /** * Gets a <code>Date</code> object from a string representing a date in * 'Zulu' format (yyyyMMddTHHmmssZ) * * @param utc * date in 'Zulu' format (yyyyMMddTHHmmssZ) * @return A <code>Date</code> object obtained starting from a time in * milliseconds from the Epoch */ public static Date parseUTCDate(String utc) { int day = 0; int month = 0; int year = 0; int hour = 0; int minute = 0; int second = 0; Calendar calendar = null; day = Integer.parseInt(utc.substring(6, 8)); month = Integer.parseInt(utc.substring(4, 6)); year = Integer.parseInt(utc.substring(0, 4)); hour = Integer.parseInt(utc.substring(9, 11)); minute = Integer.parseInt(utc.substring(11, 13)); second = Integer.parseInt(utc.substring(13, 15)); calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_MONTH, day); calendar.set(Calendar.MONTH, month - 1); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.SECOND, second); Date date = calendar.getTime(); long dateInMillis = date.getTime(); date.setTime(dateInMillis+millisDeviceOffset); return date; } public static void setTimeZone(String timeZone){ if (timeZone == null || timeZone.length() < 5) { Log.error("setTimeZone: invalid timezone " + timeZone); } try { deviceOffset = timeZone; String hstmz = deviceOffset.substring(1, 3); String mstmz = deviceOffset.substring(3, 5); long hhtmz = Long.parseLong(hstmz); long mmtmz = Long.parseLong(mstmz); millisDeviceOffset = (hhtmz * 3600000) + (mmtmz * 60000); if(deviceOffset.charAt(0)=='-') { millisDeviceOffset *= -1; } } catch(Exception e) { Log.error("setTimeZone: " + e.toString()); e.printStackTrace(); } } //------------------------------------------------------------- Private methods /** * Get the number of the month, given the name. */ private static int getMonthNumber(String name) { for(int i=0, l=monthNames.length; i<l; i++) { if(monthNames[i].equals(name)) { return i; } } return -1; } /** * Get the name of the month, given the number. */ private static String getMonthName(int number) { if(number>0 && number<monthNames.length) { return monthNames[number]; } else return null; } private static String getAMPM(Calendar cal) { return (cal.get(Calendar.AM_PM)==Calendar.AM)?"a":"p"; } /** * Returns a string representation of number with at least 2 digits */ private static String printTwoDigits(int number) { if (number>9) { return String.valueOf(number); } else { return "0"+number; } } }
Java
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.util; import com.funambol.storage.DataAccessException; import java.util.Date; /** * Generic Log class */ public class Log { //---------------------------------------------------------------- Constants /** * Log level DISABLED: used to speed up applications using logging features */ public static final int DISABLED = -1; /** * Log level ERROR: used to log error messages. */ public static final int ERROR = 0; /** * Log level INFO: used to log information messages. */ public static final int INFO = 1; /** * Log level DEBUG: used to log debug messages. */ public static final int DEBUG = 2; /** * Log level TRACE: used to trace the program execution. */ public static final int TRACE = 3; private static final int PROFILING = -2; //---------------------------------------------------------------- Variables /** * The default appender is the console */ private static Appender out; /** * The default log level is INFO */ private static int level = INFO; /** * Last time stamp used to dump profiling information */ private static long initialTimeStamp = -1; //------------------------------------------------------------- Constructors /** * This class is static and cannot be intantiated */ private Log(){ } //----------------------------------------------------------- Public methods /** * Initialize log file with a specific log level. * With this implementation of initLog the initialization is skipped. * Only a delete of log is performed. * * @param object the appender object that write log file * @param level the log level */ public static void initLog(Appender object, int level){ setLogLevel(level); out = object; // Delete Log invocation removed to speed up startup initialization. // However if needed the log store will rotate //deleteLog(); if (level > Log.DISABLED) { writeLogMessage(level, "INITLOG","---------"); } } /** * Ititialize log file * @param object the appender object that write log file */ public static void initLog(Appender object){ out = object; out.initLogFile(); } /** * Delete log file * */ public static void deleteLog() { out.deleteLogFile(); } /** * Accessor method to define log level: * @param newlevel log level to be set */ public static void setLogLevel(int newlevel) { level = newlevel; } /** * Accessor method to retrieve log level: * @return actual log level */ public static int getLogLevel() { return level; } /** * ERROR: Error message * @param msg the message to be logged */ public static void error(String msg) { writeLogMessage(ERROR, "ERROR", msg); } /** * ERROR: Error message * @param msg the message to be logged * @param obj the object that send error message */ public static void error(Object obj, String msg) { String message = "["+ obj.getClass().getName() + "] " + msg; writeLogMessage(ERROR, "ERROR", message); } /** * INFO: Information message * @param msg the message to be logged */ public static void info(String msg) { writeLogMessage(INFO, "INFO", msg); } /** * INFO: Information message * @param msg the message to be logged * @param obj the object that send log message */ public static void info(Object obj, String msg) { writeLogMessage(INFO, "INFO", msg); } /** * DEBUG: Debug message * @param msg the message to be logged */ public static void debug(String msg) { writeLogMessage(DEBUG, "DEBUG", msg); } /** * DEBUG: Information message * @param msg the message to be logged * @param obj the object that send log message */ public static void debug(Object obj, String msg) { String message = "["+ obj.getClass().getName() + "] " +msg; writeLogMessage(DEBUG, "DEBUG", message); } /** * TRACE: Debugger mode */ public static void trace(String msg) { writeLogMessage(TRACE, "TRACE", msg); } /** * TRACE: Information message * @param msg the message to be logged * @param obj the object that send log message */ public static void trace(Object obj, String msg) { String message = "["+ obj.getClass().getName() + "] " +msg; writeLogMessage(TRACE, "TRACE", message); } /** * Dump memory statistics at this point. Dump if level >= DEBUG. * * @param msg message to be logged */ public static void memoryStats(String msg) { // Try to force a garbage collection, so we get the real amount of // available memory long available = Runtime.getRuntime().freeMemory(); Runtime.getRuntime().gc(); writeLogMessage(PROFILING, "PROFILING-MEMORY", msg + ":" + available + " [bytes]"); } /** * Dump memory statistics at this point. * * @param obj caller object * @param msg message to be logged */ public static void memoryStats(Object obj, String msg) { // Try to force a garbage collection, so we get the real amount of // available memory Runtime.getRuntime().gc(); long available = Runtime.getRuntime().freeMemory(); writeLogMessage(PROFILING, "PROFILING-MEMORY", obj.getClass().getName() + "::" + msg + ":" + available + " [bytes]"); } /** * Dump time statistics at this point. * * @param msg message to be logged */ public static void timeStats(String msg) { long time = System.currentTimeMillis(); if (initialTimeStamp == -1) { writeLogMessage(PROFILING, "PROFILING-TIME", msg + ": 0 [msec]"); initialTimeStamp = time; } else { long currentTime = time - initialTimeStamp; writeLogMessage(PROFILING, "PROFILING-TIME", msg + ": " + currentTime + "[msec]"); } } /** * Dump time statistics at this point. * * @param obj caller object * @param msg message to be logged */ public static void timeStats(Object obj, String msg) { // Try to force a garbage collection, so we get the real amount of // available memory long time = System.currentTimeMillis(); if (initialTimeStamp == -1) { writeLogMessage(PROFILING, "PROFILING-TIME", obj.getClass().getName() + "::" + msg + ": 0 [msec]"); initialTimeStamp = time; } else { long currentTime = time - initialTimeStamp; writeLogMessage(PROFILING, "PROFILING-TIME", obj.getClass().getName() + "::" + msg + ":" + currentTime + " [msec]"); } } /** * Dump time statistics at this point. * * @param msg message to be logged */ public static void stats(String msg) { memoryStats(msg); timeStats(msg); } /** * Dump time statistics at this point. * * @param obj caller object * @param msg message to be logged */ public static void stats(Object obj, String msg) { memoryStats(obj, msg); timeStats(obj, msg); } private static void writeLogMessage(int msgLevel, String levelMsg, String msg) { if (level >= msgLevel) { try { if (out != null) { out.writeLogMessage(levelMsg, msg); } else { System.out.print(MailDateFormatter.dateToUTC(new Date())); System.out.print(" [" + levelMsg + "] " ); System.out.println(msg); } } catch (DataAccessException ex) { ex.printStackTrace(); } } } }
Java
/* * Copyright 2011 BTI360 Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bti360.hackathon.listview; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.text.InputType; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; public class HackathonActivity extends Activity { protected static final int ADD_DIALOG = 0; List<String> mNames; NameAdapter mAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //Let's create a String List and retrieve the String Array from our Resources mNames = new ArrayList<String>(); mNames.addAll(Arrays.asList(getResources().getStringArray(R.array.names))); //grab the ListView ListView lv = (ListView) findViewById(R.id.listView1); //create a new ListAdapter and pass in our ArrayList of data mAdapter = new NameAdapter(this, R.layout.list_item, mNames); lv.setAdapter(mAdapter); //grab our button and set an onClickListener Button addButton = (Button) findViewById(R.id.button1); addButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { /*when the add button is clicked we will show the Add Dialog. * Opening a Dialog with showDialog causes the Activity to Manage the * dialog meaning it will control the lifecycle - create, show, hide, * destroy when Activity is killed, etc. */ showDialog(ADD_DIALOG); }}); } private class NameAdapter extends ArrayAdapter<String> { LayoutInflater mLayoutInflater; public NameAdapter(Context context, int textViewResourceId, List<String> objects) { super(context, textViewResourceId, objects); mLayoutInflater = getLayoutInflater(); } @Override public View getView(int position, View convertView, ViewGroup parent) { //check if our view is going to be recycled/reused if(convertView == null) { convertView = mLayoutInflater.inflate(R.layout.list_item, null); } //grab the TextView and set the text with the name at the position TextView textView = (TextView) convertView.findViewById(R.id.textView1); textView.setText(getItem(position)); //grab the ImageView and see if we have a picture for the name ImageView iv = (ImageView) convertView.findViewById(R.id.imageView1); String url = null; switch(position) { case 0: url = "http://www.bti360.com/uploads/Tim_thumb.jpg"; break; case 1: url = "http://www.bti360.com/uploads/Jonthan_thumb.jpg"; break; case 2: url = "http://www.bti360.com/uploads/Clinton_thumb2.jpg"; break; } if(url != null) { //if the ImageView is not null we create a new AsycTask and pass in our //ImageView and the url to the image resource new FetchTask(iv).execute(url); /* Comment out our old fetch code * try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet request = new HttpGet(url); HttpResponse response = httpClient.execute(request); Bitmap bm = BitmapFactory.decodeStream(response.getEntity().getContent()); iv.setImageBitmap(bm); } catch(IOException e) { }*/ } else { //if the url is null clear the ImageView iv.setImageBitmap(null); } return convertView; } } /* This is called whenever showDialog is called with a dialog that has not * yet been created. */ @Override protected Dialog onCreateDialog(int id) { switch(id) { case ADD_DIALOG: // We are going to create an AlertDialog with a single text input and a button // first we create the EditText final EditText edit = new EditText(this); // Next we create an AlertDialog.Builder which creates a styled AlertDialog based // on our specifications; AlertDialog.Builder builder = new AlertDialog.Builder(this); // set the title builder.setTitle("Add Person"); // set the icon to a built-in, this one is a + builder.setIcon(android.R.drawable.ic_input_add); // set the text of the only button, and add a click listener builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // on the Ok Button we grab the text from the EditText, // clear it and then add the Name to our list String name = edit.getText().toString(); edit.setText(""); addName(name); } }); // finally let's create the dialog final AlertDialog d = builder.create(); // and set the view to our EditText d.setView(edit); // we'll set a special InputType since we are collecting a name // other's exist such as email, address, phone number, etc // this allows the IME (keyboard) to customize itself based on // expected input, e.g. show @ and .com when Email edit.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME); // Respond to the default action on the IME (keyboard) By default it is // "Done" but it can be changed with setImeActionLabel to be something // else like a search hourglass. // In our case we want a click on "Done" to do the same thing as a click // on the Ok button in the Dialog. edit.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView tv, int actionId, KeyEvent arg2) { // same as the DialogClick Handler except we also dismiss the dialog String name = edit.getText().toString(); edit.setText(""); addName(name); d.dismiss(); return true; }}); return d; } return super.onCreateDialog(id); } /* * Add a name to our list. * notifySetDataChanged tells the Adapter that it may need to refresh itself */ protected void addName(String name) { mNames.add(name); mAdapter.notifyDataSetChanged(); } /* * AsyncTask is a way to do Background Tasks. Async Tasks have a ThreadPool * that they use. */ // The parameters are Params to execute(), Progress variable, Return Variable private class FetchTask extends AsyncTask<String, Void, Bitmap> { ImageView imageView; public FetchTask(ImageView imageView) { super(); this.imageView = imageView; } @Override protected Bitmap doInBackground(String... params) { // Download the image using Http client try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet request = new HttpGet(params[0]); HttpResponse response = httpClient.execute(request); // Use BitmapFactory to decode the bytes into a Bitmap and return it return BitmapFactory.decodeStream(response.getEntity().getContent()); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(Bitmap result) { // This runs on the UI/Main thread so its okay to update the ImageView if(result != null) { imageView.setImageBitmap(result); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // this will run when the menu is first created to add our // menu from the xml file. getMenuInflater().inflate(R.menu.menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // show the add dialog when the add menu item is selected switch(item.getItemId()) { case R.id.add: showDialog(ADD_DIALOG); break; } return super.onOptionsItemSelected(item); } }
Java
package org.bti.ws.model; import javax.xml.bind.annotation.XmlRootElement; /** * A simple word object that contains a name and some definitions. * * @author david */ @XmlRootElement public class Word { private String name; private String definition; public Word() { } public Word(String name) { this.name = name; } public Word(String name, String definition) { this.name = name; this.definition = definition; } public String getName() { return name; } public Word setName(String name) { this.name = name; return this; } public String getDefinition() { return definition; } public Word setDefinition(String definition) { this.definition = definition; return this; } }
Java
package org.bti.ws.persistence; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.bti.ws.model.Word; /** * This is an implementation of a very simple dictionary that remains in * memory. * * @author david */ public class InMemoryDictionary { private static InMemoryDictionary instance = null; private HashMap<String, Word> words = new HashMap<String, Word>(); /* * Private constructor that creates the Singleton instance. */ private InMemoryDictionary() { initialize(); } /** * Gets the single instance of this. * * @return the single <code>InMemoryDictionary</code> instance. */ public static InMemoryDictionary instance() { if(instance == null) { instance = new InMemoryDictionary(); } return instance; } private void initialize() { Word set = new Word("set"); set.setDefinition("A collection that contains no duplicate elements."); Word list = new Word("list"); list.setDefinition("An ordered collection (also known as a sequence)."); putWord(set); putWord(list); } /** * Gets all the words in the dictionary. * * @return a <code>Map</code> with all the words in the dictionary. */ public Map getWords() { return Collections.unmodifiableMap(words); } /** * Get the definition of a word. * * @param wordName the word for which the definition is requested. * @return if the word is in the dictionary, a <code>List</code> of * definitions will be returned. Else, <code>null</code> will * be returned. */ public Word getWord(String wordName) { return words.get(wordName); } public void putWord(Word word) { words.put(word.getName(), word); } public void removeWord(String wordName) { words.remove(wordName); } }
Java
package org.bti.ws.resource; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.Path; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import javax.xml.bind.JAXBElement; import org.bti.ws.model.Word; import org.bti.ws.persistence.InMemoryDictionary; /** * A RESTful dictionary service. */ @Path("/dictionary") public class DictionaryResource { private static InMemoryDictionary dictionary = InMemoryDictionary.instance(); @GET @Path("{word}") @Produces({"application/xml", "application/json"}) public Response get(@PathParam("word") String name) { Word word = dictionary.getWord(name); if(word == null) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok(word).build(); } @PUT @Path("{word}") @Consumes({"application/xml", "application/json"}) public Response put(JAXBElement<Word> wordElement) { dictionary.putWord(wordElement.getValue()); return Response.ok().build(); } @DELETE @Path("{word}") public Response delete(@PathParam("word") String name) { dictionary.removeWord(name); return Response.ok().build(); } }
Java
package com.bti.ws.model; import javax.xml.bind.annotation.XmlRootElement; /** * A simple word object that contains a name and some definitions. * * @author david */ @XmlRootElement public class Word { private String name; private String definition; public Word() { } public Word(String name) { this.name = name; } public Word(String name, String definition) { this.name = name; this.definition = definition; } public String getName() { return name; } public Word setName(String name) { this.name = name; return this; } public String getDefinition() { return definition; } public Word setDefinition(String definition) { this.definition = definition; return this; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Name: "); sb.append(name); sb.append(" Definition: "); sb.append(definition); return sb.toString(); } }
Java
package com.bti.ws.model; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name="words") public class WordList { private static final long serialVersionUID = 1L; @XmlElement(name="word") List<Word> list = new ArrayList<Word>(); public void addAll(List<Word> words) { list.addAll(words); } public List<Word> getWords() { return list; } }
Java
package com.bti.ws.persistence; import java.util.List; import com.bti.ws.model.Word; public interface DictionaryDao { void putWord(Word word); Word getWord(String word); void removeWord(String word); List<Word> getWords(); }
Java
package com.bti.ws.persistence; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.bti.ws.model.Word; @Repository public class DictionaryDaoImpl implements DictionaryDao { private Map<String, Word> map = new HashMap<String, Word>(); public DictionaryDaoImpl() { Word w = new Word(); w.setName("set"); w.setDefinition("A collection that can only contain unique elements"); map.put("set", w); w = new Word(); w.setName("list"); w.setDefinition("A collection that contains elements in a specific order"); map.put("list", w); } @Override public Word getWord(String word) { return map.get(word); } @Override public List<Word> getWords() { List<Word> wordList = new ArrayList<Word>(); for(Map.Entry<String, Word> entry : map.entrySet()) { wordList.add(entry.getValue()); } return wordList; } @Override public void putWord(Word word) { map.put(word.getName(), word); } @Override public void removeWord(String word) { map.remove(word); } }
Java
package com.bti.ws.controller; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.context.request.WebRequest; import com.bti.ws.model.Word; import com.bti.ws.model.WordList; import com.bti.ws.persistence.DictionaryDao; @Controller @RequestMapping("/dictionary") public class DictionaryController { @Autowired DictionaryDao dictionaryDao; @RequestMapping(method=RequestMethod.GET) @ResponseBody WordList get() { WordList wordList = new WordList(); wordList.addAll(dictionaryDao.getWords()); return wordList; } @RequestMapping(value="/{word}", method=RequestMethod.GET) @ResponseBody Word get(@PathVariable("word") String word) { Word w = dictionaryDao.getWord(word); if(w == null) { throw new NotFoundException(); } return w; } @RequestMapping(method=RequestMethod.POST) @ResponseStatus(HttpStatus.MOVED_PERMANENTLY) void post(@RequestBody Word word, WebRequest req, HttpServletResponse resp) { dictionaryDao.putWord(word); resp.addHeader("Location", req.getContextPath() + "/bti/dictionary/" + word.getName()); } @RequestMapping(value="/{word}", method=RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) void put(@PathVariable("word") String id, @RequestBody Word word) { dictionaryDao.putWord(word); } @RequestMapping(value="/{word}", method=RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) void remove(@PathVariable("word") String word) { dictionaryDao.removeWord(word); } @ExceptionHandler(NotFoundException.class) @ResponseStatus(value=HttpStatus.NOT_FOUND, reason="Word not found") void handleNotFound(NotFoundException exc) { } class NotFoundException extends RuntimeException { private static final long serialVersionUID = 1L; } }
Java
package org.bti.ws.model; import org.springframework.ui.ModelMap; public class ExtModelMap extends ModelMap { private static final long serialVersionUID = 1L; private static final String SUCCESS = "success"; private static final String ROOT = "data"; public ExtModelMap(){ this.addAttribute(SUCCESS, true); } public ExtModelMap(Object data){ this(); this.addAttribute(ROOT, data); } }
Java
package org.bti.ws.model; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name="root") public class ExtWrapper { private static final long serialVersionUID = 1L; @XmlElement(name="data") Word[] data; @XmlElement(name="success") boolean success = true; public ExtWrapper() {} public ExtWrapper(Word[] data){ this.data = data; } public Word[] getData() { return data; } public boolean isSuccess() { return success; } }
Java
package org.bti.ws.model; import javax.xml.bind.annotation.XmlRootElement; /** * A simple word object that contains a name and some definitions. */ @XmlRootElement public class Word { private Integer id; private String name; private String definition; public Word() { } public Word(String name) { this.name = name; } public Word(String name, String definition) { this.name = name; this.definition = definition; } public Integer getId() { return id; } public Word setId(Integer id) { this.id = id; return this; } public String getName() { return name; } public Word setName(String name) { this.name = name; return this; } public String getDefinition() { return definition; } public Word setDefinition(String definition) { this.definition = definition; return this; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Name: "); sb.append(name); sb.append(" Definition: "); sb.append(definition); return sb.toString(); } }
Java
package org.bti.ws.persistence; import java.util.List; import org.bti.ws.model.Word; public interface DictionaryDao { void putWord(Word word); Word getWord(int word); void removeWord(int word); List<Word> getWords(); }
Java
package org.bti.ws.persistence; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bti.ws.model.Word; import org.springframework.stereotype.Repository; @Repository public class DictionaryDaoImpl implements DictionaryDao { private Map<Integer, Word> map = new HashMap<Integer, Word>(); private int ctr = 0; public DictionaryDaoImpl() { putWord(new Word("set", "A collection that can only contain unique elements")); putWord(new Word("list", "A collection that can only contain unique elements")); } @Override public Word getWord(int id) { return map.get(id); } @Override public List<Word> getWords() { List<Word> wordList = new ArrayList<Word>(); for(Map.Entry<Integer, Word> entry : map.entrySet()) { wordList.add(entry.getValue()); } return wordList; } @Override public void putWord(Word word) { Integer id = word.getId(); if(id == null){ id = new Integer(ctr++); word.setId(id); } map.put(id, word); } @Override public void removeWord(int id) { map.remove(id); } }
Java
package org.bti.ws.controller; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.bti.ws.model.ExtModelMap; import org.bti.ws.model.ExtWrapper; import org.bti.ws.model.Word; import org.bti.ws.persistence.DictionaryDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.context.request.WebRequest; @Controller @RequestMapping("/dictionary") public class DictionaryController { @Autowired DictionaryDao dictionaryDao; @ResponseBody @RequestMapping(method = RequestMethod.GET) ExtWrapper get() { List<Word> l = dictionaryDao.getWords(); Word[] words = new Word[l.size()]; l.toArray(words); return new ExtWrapper(words); } @ResponseBody @RequestMapping(value = "/{id}", method = RequestMethod.GET) ExtModelMap get(@PathVariable("id") int id) { Word w = dictionaryDao.getWord(id); if (w == null) { throw new NotFoundException(); } return new ExtModelMap(w); } @ResponseBody @RequestMapping(method = RequestMethod.POST) ExtModelMap post(@RequestBody Word word, WebRequest req, HttpServletResponse resp) { dictionaryDao.putWord(word); return new ExtModelMap(word); } @ResponseBody @RequestMapping(value = "/{id}", method = RequestMethod.PUT) ExtModelMap put(@PathVariable("id") int id, @RequestBody Word word) { dictionaryDao.putWord(word); return new ExtModelMap(word); } @ResponseBody @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) ExtModelMap remove(@PathVariable("id") int id) { dictionaryDao.removeWord(id); return new ExtModelMap(); } @ExceptionHandler(NotFoundException.class) @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Word not found") void handleNotFound(NotFoundException exc) { } class NotFoundException extends RuntimeException { private static final long serialVersionUID = 1L; } }
Java
package com.bti.http.client; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.util.zip.GZIPInputStream; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; import org.springframework.util.StringUtils; public class GzipClientHttpResponse implements ClientHttpResponse { private final HttpURLConnection connection; private HttpHeaders headers; public GzipClientHttpResponse(HttpURLConnection connection) { this.connection = connection; } @Override public InputStream getBody() throws IOException { InputStream errorStream = this.connection.getErrorStream(); return (errorStream != null ? errorStream : StringUtils.hasLength( this.connection.getContentEncoding()) && this.connection.getContentEncoding().equalsIgnoreCase( GzipClientHttpRequest.ENCODING_GZIP) ? new GZIPInputStream( this.connection.getInputStream()) : this.connection.getInputStream()); } @Override public HttpHeaders getHeaders() { if (this.headers == null) { this.headers = new HttpHeaders(); // Header field 0 is the status line for most HttpURLConnections, but not on GAE String name = this.connection.getHeaderFieldKey(0); if (StringUtils.hasLength(name)) { this.headers.add(name, this.connection.getHeaderField(0)); } int i = 1; while (true) { name = this.connection.getHeaderFieldKey(i); if (!StringUtils.hasLength(name)) { break; } this.headers.add(name, this.connection.getHeaderField(i)); i++; } } return this.headers; } @Override public HttpStatus getStatusCode() throws IOException { return HttpStatus.valueOf(this.connection.getResponseCode()); } @Override public String getStatusText() throws IOException { return this.connection.getResponseMessage(); } @Override public void close() { this.connection.disconnect(); } }
Java
package com.bti.http.client; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.net.URL; import java.net.URLConnection; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.util.Assert; public class GzipClientHttpRequestFactory implements ClientHttpRequestFactory { @Override public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { HttpURLConnection connection = openConnection(uri.toURL()); prepareConnection(connection, httpMethod.name()); return new GzipClientHttpRequest(connection); } protected HttpURLConnection openConnection(URL url) throws IOException { URLConnection urlConnection = url.openConnection(); Assert.isInstanceOf(HttpURLConnection.class, urlConnection); return (HttpURLConnection) urlConnection; } protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { connection.setDoInput(true); if ("GET".equals(httpMethod)) { connection.setInstanceFollowRedirects(true); } else { connection.setInstanceFollowRedirects(false); } if ("PUT".equals(httpMethod) || "POST".equals(httpMethod)) { connection.setDoOutput(true); } else { connection.setDoOutput(false); } connection.setRequestMethod(httpMethod); } }
Java
package com.bti.http.client.test; import java.io.IOException; import java.net.URI; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.http.client.ClientHttpRequest; import org.springframework.util.StringUtils; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import com.bti.http.client.GzipClientHttpRequestFactory; public class GzipClient { private static String url = "http://search.twitter.com/search.json?q=#REST&rpp=100&until=2011-04-02"; public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(new GzipClientHttpRequestFactory()); try { ClientHttpRequest request = restTemplate.getRequestFactory().createRequest(URI.create(url), HttpMethod.GET); System.out.println("Request Headers"); printHeaders(request.getHeaders()); ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); System.out.println("Response Headers"); printHeaders(response.getHeaders()); } catch (RestClientException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void printHeaders(HttpHeaders headers) { for(String key : headers.keySet()) { System.out.println(key + ": " + StringUtils.collectionToCommaDelimitedString(headers.get(key))); } } }
Java
package com.bti.http.client; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Map; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.client.AbstractClientHttpRequest; import org.springframework.http.client.ClientHttpResponse; import org.springframework.util.FileCopyUtils; public class GzipClientHttpRequest extends AbstractClientHttpRequest { public static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding"; public static final String ENCODING_GZIP = "gzip"; private final HttpURLConnection connection; public GzipClientHttpRequest(HttpURLConnection connection) { this.connection = connection; this.getHeaders().add(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } @Override public HttpMethod getMethod() { return HttpMethod.valueOf(this.connection.getRequestMethod()); } @Override public URI getURI() { try { return this.connection.getURL().toURI(); } catch (URISyntaxException ex) { throw new IllegalStateException("Could not get HttpURLConnection URI: " + ex.getMessage(), ex); } } @Override protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException { for (Map.Entry<String, List<String>> entry : headers.entrySet()) { String headerName = entry.getKey(); for (String headerValue : entry.getValue()) { this.connection.addRequestProperty(headerName, headerValue); } } this.connection.connect(); if (bufferedOutput.length > 0) { FileCopyUtils.copy(bufferedOutput, this.connection.getOutputStream()); } return new GzipClientHttpResponse(this.connection); } }
Java
package com.bti.ws.controller; import com.bti.ws.domain.Word; import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @RooWebScaffold(path = "words", formBackingObject = Word.class) @RequestMapping("/words") @Controller public class WordController { }
Java
package com.bti.ws.controller; import org.springframework.format.FormatterRegistry; import org.springframework.format.support.FormattingConversionServiceFactoryBean; import org.springframework.roo.addon.web.mvc.controller.RooConversionService; /** * A central place to register application Converters and Formatters. */ @RooConversionService public class ApplicationConversionServiceFactoryBean extends FormattingConversionServiceFactoryBean { @Override protected void installFormatters(FormatterRegistry registry) { super.installFormatters(registry); // Register application converters and formatters } }
Java
package com.bti.ws.domain; import org.springframework.roo.addon.entity.RooEntity; import org.springframework.roo.addon.javabean.RooJavaBean; import org.springframework.roo.addon.tostring.RooToString; import javax.validation.constraints.NotNull; import javax.persistence.Column; import org.springframework.roo.addon.json.RooJson; @RooJavaBean @RooToString @RooEntity @RooJson public class Word { @NotNull @Column(unique = true) private String name; @NotNull private String definition; }
Java
package controllers; import play.*; import play.libs.WS; import play.libs.WS.HttpResponse; import play.libs.WS.WSRequest; import play.mvc.*; import java.io.IOException; import java.util.*; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import models.*; public class Dictionary extends Controller { private static final String url = "http://btiwst.appspot.com/bti/dictionary/"; public static void getWords() { String format = request.format; WSRequest req = WS.url(url).setHeader("Accept", "application/" + format); String response = req.get().getString(); if(format.equalsIgnoreCase("json")) { renderJSON(response); } else if(format.equalsIgnoreCase("xml")){ renderXml(response); } } public static void addWord() throws IOException { StringBuffer out = new StringBuffer(); byte[] b = new byte[4096]; for (int n; (n = request.body.read(b)) != -1;) { out.append(new String(b, 0, n)); } String format = request.format; WSRequest req = WS.url(url).setHeader("Content-Type", "application/" + format); req.body(out.toString()); HttpResponse resp = req.post(); response.status = resp.getStatus(); } public static void updateWord(String word) throws IOException { StringBuffer out = new StringBuffer(); byte[] b = new byte[4096]; for (int n; (n = request.body.read(b)) != -1;) { out.append(new String(b, 0, n)); } String format = request.format; WSRequest req = WS.url(url + "/" + word).setHeader("Content-Type", "application/" + format); req.body(out.toString()); HttpResponse resp = req.put(); response.status = resp.getStatus(); } public static void deleteWord(String word) { WSRequest req = WS.url(url + word); HttpResponse resp = req.delete(); response.status = resp.getStatus(); } }
Java
package com.bti.model; public class Word { private String name; private String definition; public Word() { } public Word(String name) { this.name = name; } public Word(String name, String definition) { this.name = name; this.definition = definition; } public String getName() { return name; } public Word setName(String name) { this.name = name; return this; } public String getDefinition() { return definition; } public Word setDefinition(String definition) { this.definition = definition; return this; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Name: "); sb.append(name); sb.append(" Definition: "); sb.append(definition); return sb.toString(); } }
Java
package com.bti.client; public class DictionaryClientException extends RuntimeException { /** * */ private static final long serialVersionUID = 1L; public DictionaryClientException(Exception e) { super(e); } public DictionaryClientException(String message) { super(message); } }
Java
package com.bti.client; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.json.JSONArray; import org.json.JSONObject; import com.bti.model.Word; public class DictionaryClientImpl implements DictionaryClient { private static String dictionaryServiceUrl = "http://btiwst.appspot.com/bti/dictionary"; private HttpClient httpClient; public DictionaryClientImpl() { HttpParams params = new BasicHttpParams(); // create a HttpParams object to customize the client HttpConnectionParams.setConnectionTimeout(params, 20000); // Add a 20 second connection timeout, default value is infinite. HttpConnectionParams.setSoTimeout(params, 20000); // Add a 20 second timeout when waiting for data, default value is infinite. httpClient = new DefaultHttpClient(params); // create a default client using the param } @Override public void post(String name, String definition) { Word word = new Word(); word.setName(name); word.setDefinition(definition); HttpPost post = new HttpPost(dictionaryServiceUrl); post.addHeader("Content-Type", "application/json; charset=UTF-8"); try { HttpEntity entity = encodeWord(word); post.setEntity(entity); HttpResponse resp = httpClient.execute(post); if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) { throw new DictionaryClientException(resp.getStatusLine().toString()); } resp.getEntity().consumeContent(); } catch (Exception e) { throw new DictionaryClientException(e); } } @Override public void put(Word word) { HttpPut put = new HttpPut(dictionaryServiceUrl + "/" + word.getName()); put.addHeader("Content-Type", "application/json; charset=UTF-8"); try { HttpEntity entity = encodeWord(word); put.setEntity(entity); HttpResponse resp = httpClient.execute(put); if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new DictionaryClientException(resp.getStatusLine().toString()); } resp.getEntity().consumeContent(); } catch (Exception e) { throw new DictionaryClientException(e); } } @Override public Word get(String name) { Word word = null; HttpGet get = new HttpGet(dictionaryServiceUrl + "/" + name); get.addHeader("Accept", "application/json"); try { HttpResponse resp = httpClient.execute(get); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = resp.getEntity(); word = parseWord(entity); } } catch (Exception e) { throw new DictionaryClientException(e); } return word; } @Override public List<Word> getAll() { List<Word> words = null; HttpGet getAll = new HttpGet(dictionaryServiceUrl); getAll.addHeader("Accept", "application/json"); try { HttpResponse resp = httpClient.execute(getAll); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = resp.getEntity(); words = parseWords(entity); } } catch (Exception e) { throw new DictionaryClientException(e); } return words; } @Override public void delete(String name) { HttpDelete delete = new HttpDelete(dictionaryServiceUrl + "/" + name); try { HttpResponse resp = httpClient.execute(delete); if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new DictionaryClientException(resp.getStatusLine().toString()); } resp.getEntity().consumeContent(); } catch (Exception e) { throw new DictionaryClientException(e); } } private Word parseWord(HttpEntity entity) throws Exception { InputStream inputStream = entity.getContent(); BufferedReader reader = new BufferedReader( new InputStreamReader(inputStream, "UTF-8")); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } JSONObject jsonObject = new JSONObject(sb.toString()); Word word = new Word(); word.setDefinition(jsonObject.getString("definition")); word.setName(jsonObject.getString("name")); inputStream.close(); entity.consumeContent(); return word; } private List<Word> parseWords(HttpEntity entity) throws Exception { List<Word> words = new ArrayList<Word>(); InputStream inputStream = entity.getContent(); BufferedReader reader = new BufferedReader( new InputStreamReader(inputStream, "UTF-8")); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } JSONObject jsonObject = new JSONObject(sb.toString()); JSONArray wordsArray = jsonObject.getJSONArray("words"); for (int i = 0; i < wordsArray.length(); i++) { JSONObject jsonWord = wordsArray.getJSONObject(i); Word word = new Word(); word.setDefinition(jsonWord.getString("definition")); word.setName(jsonWord.getString("name")); words.add(word); } inputStream.close(); entity.consumeContent(); return words; } private HttpEntity encodeWord(Word word) throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("name", word.getName()); jsonObject.put("definition", word.getDefinition()); return new StringEntity(jsonObject.toString()); } }
Java
package com.bti.client; import java.util.List; import com.bti.model.Word; public interface DictionaryClient { void post(String name, String definition); void put(Word word); Word get(String word); List<Word> getAll(); void delete(String word); }
Java
import java.util.*; import play.jobs.*; import play.test.*; import models.*; @OnApplicationStart public class Bootstrap extends Job { public void doJob() { if(Word.count() == 0) { Fixtures.load("data.yml"); } } }
Java
package models; import javax.persistence.Entity; import play.data.validation.Required; import play.db.jpa.Model; @Entity public class Word extends Model { @Required public String name; @Required public String definition; public Word(String name, String definition) { this.name = name; this.definition = definition; } }
Java
package controllers; import java.util.Date; import java.util.List; import models.Word; import play.data.validation.Valid; import play.mvc.Controller; public class Dictionary extends Controller { public static void all() { List<Word> words = Word.find("order by name").fetch(); renderJSON(words); } public static void create(@Valid Word word) { word.save(); } public static void read(Long id) { Word word = Word.findById(id); renderJSON(word); } public static void update(@Valid Word word) { word.save(); } public static void delete(Long id) { Word word = Word.findById(id); word.delete(); } }
Java
import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.text.DecimalFormat; public class LoanApplet extends JApplet { private JPanel panel; private JPanel pan; private JPanel pan1; private JPanel pan2; private JPanel pan3; private JPanel pan4; private JPanel pan5; private JLabel mess1; private JLabel mess2; private JLabel mess3; private JLabel mess4; private JLabel mess5; private JTextField annualInterestRate; private JTextField numYears; private JTextField loanAmount; private JTextField monthlyPayment; private JTextField totalPayment; private JButton calc; private DecimalFormat fmt = new DecimalFormat("$#,###.00"); public void init() { setLayout(new BorderLayout()); setSize(350,200); buildPanel(); buildPan5(); panel.list(); add(panel, BorderLayout.CENTER); add(pan5, BorderLayout.SOUTH); } private void buildPanel() { panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder("Enter interest rate, year and loan amount")); mess1 = new JLabel("Annual Interest Rate"); annualInterestRate = new JTextField(10); annualInterestRate.setHorizontalAlignment(JTextField.RIGHT); mess2 = new JLabel("Number of Years"); numYears = new JTextField(10); numYears.setHorizontalAlignment(JTextField.RIGHT); mess3 = new JLabel("Loan Amount"); loanAmount = new JTextField(10); loanAmount.setHorizontalAlignment(JTextField.RIGHT); mess4 = new JLabel("Monthly Payment"); monthlyPayment = new JTextField(10); monthlyPayment.setEditable(false); monthlyPayment.setHorizontalAlignment(JTextField.RIGHT); mess5 = new JLabel("Total Payment"); totalPayment = new JTextField(10); totalPayment.setEditable(false); totalPayment.setHorizontalAlignment(JTextField.RIGHT); panel.setLayout(new GridLayout(5,2)); panel.add(mess1); panel.add(annualInterestRate); panel.add(mess2); panel.add(numYears); panel.add(mess3); panel.add(loanAmount); panel.add(mess4); panel.add(monthlyPayment); panel.add(mess5); panel.add(totalPayment); } private void buildPan5() { calc = new JButton("Compute Payment"); calc.addActionListener(new convertButtonListener()); pan5 = new JPanel(); pan5.setLayout(new FlowLayout(FlowLayout.RIGHT)); pan5.add(calc); } private class convertButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { String text, text1, text2; Double monthlyPay; Double totalPay; text = annualInterestRate.getText(); text1 = numYears.getText(); text2 = loanAmount.getText(); Double months = 12.0; Double p = Double.parseDouble(text2); Double i = Double.parseDouble(text); Double t = Double.parseDouble(text1); monthlyPay = p*i/(months*100)/(1- Math.pow(i/(months*100)+1, -(t/1)*months)); totalPay = (monthlyPay * months) * t; monthlyPayment.setText(fmt.format(monthlyPay).toString()); totalPayment.setText(fmt.format(totalPay).toString()); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package conversores; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import modelo.CategoriaProduto; import persistencia.CategoriaProdutoDAO; @FacesConverter(forClass = CategoriaProduto.class, value = "conversorCategoriaProduto") public class ConversorCategoriaProduto implements Converter { //O método getAsObject recebe a string que descreve a conta e retorna para a aplicação //uma instância do objeto Conta. @Override public Object getAsObject(FacesContext context, UIComponent component, String nome) { CategoriaProduto categoriaProduto = null; try { CategoriaProdutoDAO categoriaProdutoDAO = new CategoriaProdutoDAO(); categoriaProduto = categoriaProdutoDAO.getCategoriaProdutoPorNome(nome); } catch (SQLException ex) { Logger.getLogger(ConversorCategoriaProduto.class.getName()).log(Level.SEVERE, null, ex); } return categoriaProduto; } //O método getAsString faz o contrário de getAsObject, ou seja, recebe um objeto do tipo //Conta e retorna uma string que representa o mesmo para a aplicação. @Override public String getAsString(FacesContext context, UIComponent component, Object value) { CategoriaProduto categoriaProduto = (CategoriaProduto) value; return categoriaProduto.getNome(); } }
Java
package modelo; import java.util.Objects; public class CategoriaProduto { private int id; private String nome; public CategoriaProduto(){ } public CategoriaProduto(int id, String nome){ this.setId(id); this.setNome(nome); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } @Override public String toString() { return this.nome; } @Override public int hashCode() { int hash = 3; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final CategoriaProduto other = (CategoriaProduto) obj; if (!Objects.equals(this.nome, other.nome)) { return false; } return true; } }
Java
package modelo; public class Produto { private int id; private String codigoInterno; private String nome; private float valor; private CategoriaProduto categoriaProduto; public Produto(){ } public Produto(int id, String codigoInterno, String nome, float valor, CategoriaProduto categoriaProduto){ this.setId(id); this.setCodigoInterno(codigoInterno); this.setNome(nome); this.setValor(valor); this.setCategoria(categoriaProduto); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCodigoInterno() { return codigoInterno; } public void setCodigoInterno(String codigoInterno) { this.codigoInterno = codigoInterno; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public float getValor() { return valor; } public void setValor(float valor) { this.valor = valor; } public CategoriaProduto getCategoria() { return categoriaProduto; } public void setCategoria(CategoriaProduto categoriaProduto) { this.categoriaProduto = categoriaProduto; } }
Java
package controle; import java.sql.SQLException; import java.util.List; import javax.enterprise.context.RequestScoped; import javax.inject.Named; import modelo.Produto; import persistencia.ProdutoDAO; import modelo.CategoriaProduto; import persistencia.CategoriaProdutoDAO; @Named(value = "produtoMB") @RequestScoped public class ProdutoMB { private Produto produto; private ProdutoDAO produtoDAO; private List<Produto> produtos; private int idInicial; private int idFinal; private String filtroNome; private String filtroCodigoInterno; private List<CategoriaProduto> categoriasProduto; private CategoriaProdutoDAO categoriaProdutoDAO; public ProdutoMB() throws SQLException { this.produto = new Produto(); this.produtoDAO = new ProdutoDAO(); this.produtos = this.listar(); this.categoriaProdutoDAO = new CategoriaProdutoDAO(); this.categoriasProduto = categoriaProdutoDAO.getCategoriasProduto("select * from gastro_categoriaproduto"); //this.listaProdutos("select * from gastro_produto"); this.listar(); } public void setProduto(Produto produto) { this.produto = produto; } public Produto getProduto() { return this.produto; } public List<Produto> getProdutos() { return this.produtos; } public void setProdutos(List<Produto> produtos) { this.produtos = produtos; } public List<CategoriaProduto> getCategoriasProduto() { return categoriasProduto; } public void setCategoriasProduto(List<CategoriaProduto> categoriasProduto) { this.categoriasProduto = categoriasProduto; } public void novo() { produto = new Produto(); } public int getIdInicial() { return idInicial; } public void setIdInicial(int idInicial) { this.idInicial = idInicial; } public int getIdFinal() { return idFinal; } public void setIdFinal(int idFinal) { this.idFinal = idFinal; } public String getNome() { return filtroNome; } public void setNome(String filtroNome) { this.filtroNome = filtroNome; } public String getCodigoInterno() { return filtroCodigoInterno; } public void setCodigoInterno(String filtroCodigoInterno) { this.filtroCodigoInterno = filtroCodigoInterno; } public void salvar() throws SQLException { if (this.produto.getId() == 0) { this.produtoDAO.inserir(this.produto); } else { this.produtoDAO.alterar(this.produto); } } public String editarProduto(Object o) throws SQLException { this.setProduto((Produto ) o); return "cadastrarProduto"; } public void excluir(Produto produto) throws SQLException { this.produtoDAO.excluir(produto); this.listar(); } public List<Produto> listar() throws SQLException { return this.produtoDAO.getProdutos("select * from gastro_produto"); } //ordenação public void ordenaId() throws SQLException { this.produtos = this.produtoDAO.getProdutos("select * from gastro_produto order by id"); } public void ordenaNome() throws SQLException { this.produtos = this.produtoDAO.getProdutos("select * from gastro_produto order by nome"); } public void ordenaValor() throws SQLException { this.produtos = this.produtoDAO.getProdutos("select * from gastro_produto order by valor"); } public void ordenaCodigoInterno() throws SQLException { this.produtos = this.produtoDAO.getProdutos("select * from gastro_produto order by codigointerno"); } public void ordenaCategoria() throws SQLException { this.produtos = this.produtoDAO.getProdutos("select * from gastro_produto order by categoria"); } public void filtraNome() throws SQLException { this.produtos = this.produtoDAO.getProdutos("select * from gastro_produto where nome ilike '%" + this.filtroNome + "%'"); } public void filtraID() throws SQLException { this.produtos = this.produtoDAO.getProdutos("select * from gastro_produto where id >= " + idInicial + " and id <= " + idFinal); } public void filtraCodigoInterno() throws SQLException { this.produtos = this.produtoDAO.getProdutos("select * from gastro_produto where codigointerno = " + "'" + this.filtroCodigoInterno + "'"); } } //end ordenação
Java
package controle; import java.sql.SQLException; import java.util.List; import javax.enterprise.context.RequestScoped; import javax.inject.Named; import modelo.CategoriaProduto; import persistencia.CategoriaProdutoDAO; @Named(value = "categoriaProdutoMB") @RequestScoped public class CategoriaProdutoMB { private CategoriaProduto categoriaProduto; private CategoriaProdutoDAO categoriaProdutoDAO; private List<CategoriaProduto> categoriasProduto; private int idInicial; private int idFinal; private String filtroNome; public CategoriaProdutoMB() throws SQLException { this.categoriaProduto = new CategoriaProduto(); this.categoriaProdutoDAO = new CategoriaProdutoDAO(); this.categoriasProduto = this.listar(); this.listar(); //this.listaCategoriaProdutos("select * from gastro_categoriaproduto"); } public void setCategoriaProduto(CategoriaProduto categoriaProduto) { this.categoriaProduto = categoriaProduto; } public CategoriaProduto getCategoriaProduto() { return this.categoriaProduto; } public List<CategoriaProduto> getCategoriasProduto() { return this.categoriasProduto; } public void setCategoriaProdutos(List<CategoriaProduto> categoriasProduto) { this.categoriasProduto = categoriasProduto; } public void novo() { categoriaProduto = new CategoriaProduto(); } public int getIdInicial() { return idInicial; } public void setIdInicial(int idInicial) { this.idInicial = idInicial; } public int getIdFinal() { return idFinal; } public void setIdFinal(int idFinal) { this.idFinal = idFinal; } public String getNome() { return filtroNome; } public void setNome(String filtroNome) { this.filtroNome = filtroNome; } public void salvar() throws SQLException { if (this.categoriaProduto.getId() == 0) { this.categoriaProdutoDAO.inserir(this.categoriaProduto); } else { this.categoriaProdutoDAO.alterar(this.categoriaProduto); } } public String editarCategoriaProduto(Object o) throws SQLException { this.setCategoriaProduto((CategoriaProduto ) o); return "cadastrarCategoriaProduto"; } public void excluir(CategoriaProduto categoriaProduto) throws SQLException { this.categoriaProdutoDAO.excluir(categoriaProduto); this.listar(); } public List<CategoriaProduto> listar() throws SQLException { return this.categoriaProdutoDAO.getCategoriasProduto("select * from gastro_categoriaproduto"); } //ordenação public void ordenaId() throws SQLException { this.categoriasProduto = this.categoriaProdutoDAO.getCategoriasProduto("select * from gastro_categoriaproduto order by id"); } public void ordenaNome() throws SQLException { this.categoriasProduto = this.categoriaProdutoDAO.getCategoriasProduto("select * from gastro_categoriaproduto order by nome"); } public void filtraNome() throws SQLException { this.categoriasProduto = this.categoriaProdutoDAO.getCategoriasProduto("select * from gastro_categoriaproduto where nome ilike '%" + this.filtroNome + "%'"); } public void filtraID() throws SQLException { this.categoriasProduto = this.categoriaProdutoDAO.getCategoriasProduto("select * from gastro_categoriaproduto where id >= " + idInicial + " and id <= " + idFinal); } } //end ordenação
Java
package persistencia; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Conexao { private Connection con; private PreparedStatement pstm; private ResultSet rs; public Conexao() throws SQLException{ DriverManager.registerDriver(new org.postgresql.Driver()); this.con = DriverManager.getConnection( "jdbc:postgresql://localhost/gastronomico", "postgres", "postgres"); } public Connection getConexao() throws SQLException{ if(this.con == null) this.con = DriverManager.getConnection( "jdbc:postgresql://localhost/gastronomico", "postgres", "postgres"); return this.con; } public PreparedStatement getPreparedStatement(){ return pstm; } public void setPreparedStatement(String sql) throws SQLException{ this.pstm = con.prepareStatement(sql); } public ResultSet getResultSet(){ return this.rs; } public void setResultSet(ResultSet rs){ this.rs = rs; } }
Java
package persistencia; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import modelo.CategoriaProduto; public class CategoriaProdutoDAO extends Conexao { public CategoriaProdutoDAO() throws SQLException { super(); } public void inserir(CategoriaProduto categoriaProduto) throws SQLException { this.setPreparedStatement("insert into gastro_categoriaproduto(id, nome) " + "values (nextval('gastro_categoriaproduto_id_seq'), ?)"); this.getPreparedStatement().setString(1, categoriaProduto.getNome()); this.getPreparedStatement().executeUpdate(); } public void alterar(CategoriaProduto categoriaProduto) throws SQLException { this.setPreparedStatement("update gastro_categoriaproduto set nome = ? where id = ?"); this.getPreparedStatement().setString(1, categoriaProduto.getNome()); this.getPreparedStatement().setInt(2, categoriaProduto.getId()); this.getPreparedStatement().executeUpdate(); } public void excluir(CategoriaProduto categoriaProduto) throws SQLException { this.setPreparedStatement("delete from gastro_categoriaproduto where id = ?"); this.getPreparedStatement().setInt(1, categoriaProduto.getId()); this.getPreparedStatement().executeUpdate(); } public CategoriaProduto getCategoriaProdutoPorID(int id) throws SQLException { CategoriaProduto categoriaProduto = new CategoriaProduto(); this.setPreparedStatement("select * from gastro_categoriaproduto where id = ?"); this.getPreparedStatement().setInt(1, id); this.setResultSet(getPreparedStatement().executeQuery()); while (this.getResultSet().next()) { categoriaProduto.setId(getResultSet().getInt("id")); categoriaProduto.setNome(getResultSet().getString("nome")); } return categoriaProduto; } public CategoriaProduto getCategoriaProdutoPorNome(String nome) throws SQLException { CategoriaProduto categoriaProduto = new CategoriaProduto(); this.setPreparedStatement("select * from gastro_categoriaproduto where nome = ?"); this.getPreparedStatement().setString(1, nome); this.setResultSet(getPreparedStatement().executeQuery()); while (this.getResultSet().next()) { categoriaProduto.setId(getResultSet().getInt("id")); categoriaProduto.setNome(getResultSet().getString("nome")); } return categoriaProduto; } public List<CategoriaProduto> getCategoriasProduto(String sql) throws SQLException { List<CategoriaProduto> categoriasProduto = new ArrayList<>(); this.setPreparedStatement(sql); this.setResultSet(this.getPreparedStatement().executeQuery()); while (this.getResultSet().next()) { CategoriaProduto categoriaProduto = new CategoriaProduto(); categoriaProduto.setId(this.getResultSet().getInt("id")); categoriaProduto.setNome(this.getResultSet().getString("nome")); categoriasProduto.add(categoriaProduto); } return categoriasProduto; } }
Java
package persistencia; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import modelo.Produto; public class ProdutoDAO extends Conexao { private CategoriaProdutoDAO categoriaProdutoDAO; public ProdutoDAO() throws SQLException { super(); categoriaProdutoDAO = new CategoriaProdutoDAO(); } public void inserir(Produto produto) throws SQLException { this.setPreparedStatement("insert into gastro_produto(id, codigointerno, nome, valor, idcategoriaproduto) " + "values (nextval('gastro_produto_id_seq'), ?, ?, ?, ?)"); this.getPreparedStatement().setString(1, produto.getCodigoInterno()); this.getPreparedStatement().setString(2, produto.getNome()); this.getPreparedStatement().setFloat(3, produto.getValor()); this.getPreparedStatement().setInt(4, produto.getCategoria().getId()); this.getPreparedStatement().executeUpdate(); } public void alterar(Produto produto) throws SQLException { this.setPreparedStatement("update gastro_produto set codigointerno = ?, nome = ?, valor = ?, idcategoriaproduto = ? where id = ?"); this.getPreparedStatement().setString(1, produto.getCodigoInterno()); this.getPreparedStatement().setString(2, produto.getNome()); this.getPreparedStatement().setFloat(3, produto.getValor()); this.getPreparedStatement().setInt(4, produto.getCategoria().getId()); this.getPreparedStatement().setInt(5, produto.getId()); this.getPreparedStatement().executeUpdate(); } public void excluir(Produto produto) throws SQLException { this.setPreparedStatement("delete from gastro_produto where id = ?"); this.getPreparedStatement().setInt(1, produto.getId()); this.getPreparedStatement().executeUpdate(); } // public Produto getProdutoPorID(int id) throws SQLException { // Produto produto = new Produto(); // this.setPreparedStatement("select * from gastro_produto where id = ?"); // this.getPreparedStatement().setInt(1, id); // this.setResultSet(getPreparedStatement().executeQuery()); // while (this.getResultSet().next()) { // produto.setId(getResultSet().getInt("id")); // produto.setCodigoInterno(getResultSet().getString("codigointerno")); // produto.setNome(getResultSet().getString("nome")); // produto.setValor(getResultSet().getFloat("valor")); // produto.setCategoria(getResultSet().getInt("idcategoriaproduto")); // // } // return produto; // } // // public Produto getProdutoPorDescricao(String descricao) throws SQLException { // Produto produto = new Produto(); // this.setPreparedStatement("select * from gastro_produto where descricao = ?"); // this.getPreparedStatement().setString(1, descricao); // this.setResultSet(getPreparedStatement().executeQuery()); // while (getResultSet().next()) { // produto.setId(getResultSet().getInt("id")); // produto.setCodigoInterno(getResultSet().getString("codigointerno")); // produto.setNome(getResultSet().getString("nome")); // produto.setValor(getResultSet().getFloat("valor")); // produto.setCategoria(getResultSet().getInt("idcategoriaproduto")); // } // return produto; // } //Listar public List<Produto> getProdutos(String sql) throws SQLException { List<Produto> produtos = new ArrayList<>(); this.setPreparedStatement(sql); this.setResultSet(this.getPreparedStatement().executeQuery()); while (this.getResultSet().next()) { Produto produto = new Produto(); produto.setId(this.getResultSet().getInt("id")); produto.setCodigoInterno(this.getResultSet().getString("codigointerno")); produto.setNome(this.getResultSet().getString("nome")); produto.setValor(this.getResultSet().getFloat("valor")); produto.setCategoria(categoriaProdutoDAO.getCategoriaProdutoPorID(this.getResultSet().getInt("idcategoriaproduto"))); produtos.add(produto); } return produtos; } }
Java