Merge commit 'upstream/master'

Conflicts:
	imageio/imageio-reference/pom.xml
	imageio/imageio-thumbsdb/pom.xml
	servlet/pom.xml
This commit is contained in:
Erlend Hamnaberg
2010-04-20 11:40:30 +02:00
687 changed files with 1893 additions and 1819 deletions

View File

@@ -0,0 +1,128 @@
/*
* Copyright (c) 2008, Harald Kuhr
* 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 "TwelveMonkeys" 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 com.twelvemonkeys.image;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.Kernel;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
/**
* ConvolveTester
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/image/ConvolveTester.java#1 $
*/
public class ConvolveTester {
// Initial sample timings (avg, 1000 iterations)
// PNG, type 0: JPEG, type 3:
// ZERO_FILL: 5.4 ms 4.6 ms
// NO_OP: 5.4 ms 4.6 ms
// REFLECT: 42.4 ms 24.9 ms
// WRAP: 86.9 ms 29.5 ms
final static int ITERATIONS = 1000;
public static void main(String[] pArgs) throws IOException {
File input = new File(pArgs[0]);
BufferedImage image = ImageIO.read(input);
BufferedImage result = null;
System.out.println("image: " + image);
if (pArgs.length > 1) {
float ammount = Float.parseFloat(pArgs[1]);
int edgeOp = pArgs.length > 2 ? Integer.parseInt(pArgs[2]) : ImageUtil.EDGE_REFLECT;
long start = System.currentTimeMillis();
for (int i = 0; i < ITERATIONS; i++) {
result = sharpen(image, ammount, edgeOp);
}
long end = System.currentTimeMillis();
System.out.println("Time: " + ((end - start) / (double) ITERATIONS) + "ms");
showIt(result, "Sharpened " + ammount + " " + input.getName());
}
else {
showIt(image, "Original " + input.getName());
}
}
public static void showIt(final BufferedImage pImage, final String pTitle) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JFrame frame = new JFrame(pTitle);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
JPanel pane = new JPanel(new BorderLayout());
GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
BufferedImageIcon icon = new BufferedImageIcon(ImageUtil.accelerate(pImage, gc));
JScrollPane scroll = new JScrollPane(new JLabel(icon));
scroll.setBorder(null);
pane.add(scroll);
frame.setContentPane(pane);
frame.pack();
frame.setVisible(true);
}
});
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
static BufferedImage sharpen(BufferedImage pOriginal, final float pAmmount, int pEdgeOp) {
if (pAmmount == 0f) {
return pOriginal;
}
// Create the convolution matrix
float[] data = new float[]{
0.0f, -pAmmount, 0.0f,
-pAmmount, 4f * pAmmount + 1f, -pAmmount,
0.0f, -pAmmount, 0.0f
};
// Do the filtering
return ImageUtil.convolve(pOriginal, new Kernel(3, 3, data), pEdgeOp);
}
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright (c) 2008, Harald Kuhr
* 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 "TwelveMonkeys" 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 com.twelvemonkeys.image;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.*;
import java.awt.image.renderable.RenderableImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* EasyImage
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/image/EasyImage.java#1 $
*/
public class EasyImage extends BufferedImage {
public EasyImage(InputStream pInput) throws IOException {
this(ImageIO.read(pInput));
}
public EasyImage(BufferedImage pImage) {
this(pImage.getColorModel(), pImage.getRaster());
}
public EasyImage(RenderableImage pImage) {
this(pImage.createDefaultRendering());
}
public EasyImage(RenderedImage pImage) {
this(pImage.getColorModel(), pImage.copyData(pImage.getColorModel().createCompatibleWritableRaster(pImage.getWidth(), pImage.getHeight())));
}
public EasyImage(ImageProducer pImage) {
this(new BufferedImageFactory(pImage).getBufferedImage());
}
public EasyImage(Image pImage) {
this(new BufferedImageFactory(pImage).getBufferedImage());
}
private EasyImage(ColorModel cm, WritableRaster raster) {
super(cm, raster, cm.isAlphaPremultiplied(), null);
}
public boolean write(String pFormat, OutputStream pOutput) throws IOException {
return ImageIO.write(this, pFormat, pOutput);
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright (c) 2008, Harald Kuhr
* 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 "TwelveMonkeys" 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 com.twelvemonkeys.image;
import java.awt.image.ImageConsumer;
import java.awt.image.ColorModel;
/**
* ExtendedImageConsumer
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/image/ExtendedImageConsumer.java#1 $
*/
public interface ExtendedImageConsumer extends ImageConsumer {
/**
*
* @param pX
* @param pY
* @param pWidth
* @param pHeight
* @param pModel
* @param pPixels
* @param pOffset
* @param pScanSize
*/
public void setPixels(int pX, int pY, int pWidth, int pHeight,
ColorModel pModel,
short[] pPixels, int pOffset, int pScanSize);
// Allow for packed and interleaved models
public void setPixels(int pX, int pY, int pWidth, int pHeight,
ColorModel pModel,
byte[] pPixels, int pOffset, int pScanSize);
}

View File

@@ -0,0 +1,163 @@
/*
* Copyright (c) 2008, Harald Kuhr
* 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 "TwelveMonkeys" 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 com.twelvemonkeys.image;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
/**
* SubsampleTester
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/image/SubsampleTester.java#1 $
*/
public class SubsampleTester {
// Initial testing shows we need at least 9 pixels (sampleFactor == 3) to make a good looking image..
// Also, using Lanczos is much better than (and allmost as fast as) halving using AffineTransform
// - But I guess those numbers depend on the data type of the input image...
public static void main(String[] pArgs) throws IOException {
// To/from larger than or equal to 4x4
//ImageUtil.createResampled(new BufferedImage(5, 5, BufferedImage.TYPE_INT_ARGB), 4, 4, BufferedImage.SCALE_SMOOTH);
//ImageUtil.createResampled(new BufferedImage(4, 4, BufferedImage.TYPE_INT_ARGB), 5, 5, BufferedImage.SCALE_SMOOTH);
// To/from smaller than or equal to 4x4 with fast scale
//ImageUtil.createResampled(new BufferedImage(3, 3, BufferedImage.TYPE_INT_ARGB), 10, 10, BufferedImage.SCALE_FAST);
//ImageUtil.createResampled(new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB), 3, 3, BufferedImage.SCALE_FAST);
// To/from smaller than or equal to 4x4 with default scale
//ImageUtil.createResampled(new BufferedImage(3, 3, BufferedImage.TYPE_INT_ARGB), 10, 10, BufferedImage.SCALE_DEFAULT);
//ImageUtil.createResampled(new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB), 3, 3, BufferedImage.SCALE_DEFAULT);
// To/from smaller than or equal to 4x4 with smooth scale
try {
ImageUtil.createResampled(new BufferedImage(3, 3, BufferedImage.TYPE_INT_ARGB), 10, 10, BufferedImage.SCALE_SMOOTH);
}
catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
//try {
// ImageUtil.createResampled(new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB), 3, 3, BufferedImage.SCALE_SMOOTH);
//}
//catch (IndexOutOfBoundsException e) {
// e.printStackTrace();
// return;
//}
File input = new File(pArgs[0]);
ImageInputStream stream = ImageIO.createImageInputStream(input);
Iterator<ImageReader> readers = ImageIO.getImageReaders(stream);
if (readers.hasNext()) {
if (stream == null) {
return;
}
ImageReader reader = readers.next();
reader.setInput(stream);
ImageReadParam param = reader.getDefaultReadParam();
for (int i = 0; i < 25; i++) {
//readImage(pArgs, reader, param);
}
long start = System.currentTimeMillis();
BufferedImage image = readImage(pArgs, reader, param);
long end = System.currentTimeMillis();
System.out.println("elapsed time: " + (end - start) + " ms");
int subX = param.getSourceXSubsampling();
int subY = param.getSourceYSubsampling();
System.out.println("image: " + image);
//ImageIO.write(image, "png", new File(input.getParentFile(), input.getName().replace('.', '_') + "_new.png"));
ConvolveTester.showIt(image, input.getName() + (subX > 1 || subY > 1 ? " (subsampled " + subX + " by " + subY + ")" : ""));
}
else {
System.err.println("No reader found for input: " + input.getAbsolutePath());
}
}
private static BufferedImage readImage(final String[] pArgs, final ImageReader pReader, final ImageReadParam pParam) throws IOException {
double sampleFactor; // Minimum number of samples (in each dimension) pr pixel in output
int width = pArgs.length > 1 ? Integer.parseInt(pArgs[1]) : 300;
int height = pArgs.length > 2 ? Integer.parseInt(pArgs[2]) : 200;
if (pArgs.length > 3 && (sampleFactor = Double.parseDouble(pArgs[3])) > 0) {
int originalWidth = pReader.getWidth(0);
int originalHeight = pReader.getHeight(0);
System.out.println("originalWidth: " + originalWidth);
System.out.println("originalHeight: " + originalHeight);
int subX = (int) Math.max(originalWidth / (double) (width * sampleFactor), 1.0);
int subY = (int) Math.max(originalHeight / (double) (height * sampleFactor), 1.0);
if (subX > 1 || subY > 1) {
System.out.println("subX: " + subX);
System.out.println("subY: " + subY);
pParam.setSourceSubsampling(subX, subY, subX > 1 ? subX / 2 : 0, subY > 1 ? subY / 2 : 0);
}
}
BufferedImage image = pReader.read(0, pParam);
System.out.println("image: " + image);
int algorithm = BufferedImage.SCALE_DEFAULT;
if (pArgs.length > 4) {
if ("smooth".equals(pArgs[4].toLowerCase())) {
algorithm = BufferedImage.SCALE_SMOOTH;
}
else if ("fast".equals(pArgs[4].toLowerCase())) {
algorithm = BufferedImage.SCALE_FAST;
}
}
if (image.getWidth() != width || image.getHeight() != height) {
image = ImageUtil.createScaled(image, width, height, algorithm);
}
return image;
}
}

View File

@@ -0,0 +1,90 @@
/*
* Copyright (c) 2008, Harald Kuhr
* 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 "TwelveMonkeys" 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 com.twelvemonkeys.io.enc;
import java.io.OutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
/**
* {@code Encoder} implementation for standard DEFLATE encoding.
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/io/enc/DeflateEncoder.java#2 $
*
* @see <a href="http://tools.ietf.org/html/rfc1951">RFC 1951</a>
* @see Deflater
* @see InflateDecoder
* @see java.util.zip.DeflaterOutputStream
*/
final class DeflateEncoder implements Encoder {
private final Deflater mDeflater;
private final byte[] mBuffer = new byte[1024];
public DeflateEncoder() {
// this(new Deflater());
this(new Deflater(Deflater.DEFAULT_COMPRESSION, true)); // TODO: Should we use "no wrap"?
}
public DeflateEncoder(final Deflater pDeflater) {
if (pDeflater == null) {
throw new IllegalArgumentException("deflater == null");
}
mDeflater = pDeflater;
}
public void encode(final OutputStream pStream, final byte[] pBuffer, final int pOffset, final int pLength)
throws IOException
{
System.out.println("DeflateEncoder.encode");
mDeflater.setInput(pBuffer, pOffset, pLength);
flushInputToStream(pStream);
}
private void flushInputToStream(final OutputStream pStream) throws IOException {
System.out.println("DeflateEncoder.flushInputToStream");
if (mDeflater.needsInput()) {
System.out.println("Foo");
}
while (!mDeflater.needsInput()) {
int deflated = mDeflater.deflate(mBuffer, 0, mBuffer.length);
pStream.write(mBuffer, 0, deflated);
System.out.println("flushed " + deflated);
}
}
// public void flush() {
// mDeflater.finish();
// }
}

View File

@@ -0,0 +1,109 @@
/*
* Copyright (c) 2008, Harald Kuhr
* 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 "TwelveMonkeys" 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 com.twelvemonkeys.io.enc;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
/**
* {@code Decoder} implementation for standard DEFLATE encoding.
* <p/>
*
* @see <a href="http://tools.ietf.org/html/rfc1951">RFC 1951</a>
*
* @see Inflater
* @see DeflateEncoder
* @see java.util.zip.InflaterInputStream
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/io/enc/InflateDecoder.java#2 $
*/
final class InflateDecoder implements Decoder {
private final Inflater mInflater;
private final byte[] mBuffer;
/**
* Creates an {@code InflateDecoder}
*
*/
public InflateDecoder() {
this(new Inflater(true));
}
/**
* Creates an {@code InflateDecoder}
*
* @param pInflater the inflater instance to use
*/
public InflateDecoder(final Inflater pInflater) {
if (pInflater == null) {
throw new IllegalArgumentException("inflater == null");
}
mInflater = pInflater;
mBuffer = new byte[1024];
}
public int decode(final InputStream pStream, final byte[] pBuffer) throws IOException {
try {
int decoded;
while ((decoded = mInflater.inflate(pBuffer, 0, pBuffer.length)) == 0) {
if (mInflater.finished() || mInflater.needsDictionary()) {
return 0;
}
if (mInflater.needsInput()) {
fill(pStream);
}
}
return decoded;
}
catch (DataFormatException e) {
String message = e.getMessage();
throw new DecodeException(message != null ? message : "Invalid ZLIB data format", e);
}
}
private void fill(final InputStream pStream) throws IOException {
int available = pStream.read(mBuffer, 0, mBuffer.length);
if (available == -1) {
throw new EOFException("Unexpected end of ZLIB stream");
}
mInflater.setInput(mBuffer, 0, available);
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright (c) 2008, Harald Kuhr
* 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 "TwelveMonkeys" 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 com.twelvemonkeys.io.enc;
import java.io.InputStream;
import java.io.IOException;
/**
* LZWDecoder.
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/io/enc/LZWDecoder.java#2 $
*/
final class LZWDecoder implements Decoder {
public int decode(InputStream pStream, byte[] pBuffer) throws IOException {
return 0; // TODO: Implement
// TODO: We probably need a GIF specific subclass
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright (c) 2008, Harald Kuhr
* 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 "TwelveMonkeys" 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 com.twelvemonkeys.io.enc;
import java.io.OutputStream;
import java.io.IOException;
/**
* LZWEncoder.
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/io/enc/LZWEncoder.java#2 $
*/
final class LZWEncoder implements Encoder {
public void encode(OutputStream pStream, byte[] pBuffer, int pOffset, int pLength) throws IOException {
// TODO: Implement
// TODO: We probably need a GIF specific subclass
}
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright (c) 2008, Harald Kuhr
* 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 "TwelveMonkeys" 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 com.twelvemonkeys.lang;
/**
* MostUnfortunateException
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/lang/MostUnfortunateException.java#1 $
*/
class MostUnfortunateException extends RuntimeException {
public MostUnfortunateException() {
this("Most unfortunate.");
}
public MostUnfortunateException(Throwable pCause) {
this(pCause.getMessage(), pCause);
}
public MostUnfortunateException(String pMessage, Throwable pCause) {
this(pMessage);
initCause(pCause);
}
public MostUnfortunateException(String pMessage) {
super("A most unfortunate exception has occured: " + pMessage);
}
}

View File

@@ -0,0 +1,398 @@
/*
* Copyright (c) 2008, Harald Kuhr
* 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 "TwelveMonkeys" 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 com.twelvemonkeys.lang;
import com.twelvemonkeys.io.FileUtil;
import com.twelvemonkeys.util.FilterIterator;
import com.twelvemonkeys.util.service.ServiceRegistry;
import java.io.*;
import java.util.Iterator;
import java.util.Arrays;
/**
* NativeLoader
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/lang/NativeLoader.java#2 $
*/
final class NativeLoader {
// TODO: Considerations:
// - Rename all libs like the current code, to <library>.(so|dll|dylib)?
// - Keep library filename from jar, and rather store a separate
// properties-file with the library->library-file mappings?
// - As all invocations are with library file name, we could probably skip
// both renaming and properties-file altogether...
// TODO: The real trick here, is how to load the correct library for the
// current platform...
// - Change String pResource to String[] pResources?
// - NativeResource class, that has a list of multiple resources?
// NativeResource(Map<String, String>) os->native lib mapping
// TODO: Consider exposing the method from SystemUtil
// TODO: How about a SPI based solution?!
// public interface com.twelvemonkeys.lang.NativeResourceProvider
//
// imlementations return a pointer to the correct resource for a given (by
// this class) OS.
//
// String getResourceName(...)
//
// See http://tolstoy.com/samizdat/sysprops.html
// System properties:
// "os.name"
// Windows, Linux, Solaris/SunOS,
// Mac OS/Mac OS X/Rhapsody (aka Mac OS X Server)
// General Unix (AIX, Digital Unix, FreeBSD, HP-UX, Irix)
// OS/2
// "os.arch"
// Windows: x86
// Linux: x86, i386, i686, x86_64, ia64,
// Solaris: sparc, sparcv9, x86
// Mac OS: PowerPC, ppc, i386
// AIX: x86, ppc
// Digital Unix: alpha
// FreeBSD: x86, sparc
// HP-UX: PA-RISC
// Irix: mips
// OS/2: x86
// "os.version"
// Windows: 4.0 -> NT/95, 5.0 -> 2000, 5.1 -> XP (don't care about old versions, CE etc)
// Mac OS: 8.0, 8.1, 10.0 -> OS X, 10.x.x -> OS X, 5.6 -> Rhapsody (!)
//
// Normalize os.name, os.arch and os.version?!
///** Normalized operating system constant */
//static final OperatingSystem OS_NAME = normalizeOperatingSystem();
//
///** Normalized system architecture constant */
//static final Architecture OS_ARCHITECTURE = normalizeArchitecture();
//
///** Unormalized operating system version constant (for completeness) */
//static final String OS_VERSION = System.getProperty("os.version");
static final NativeResourceRegistry sRegistry = new NativeResourceRegistry();
private NativeLoader() {
}
/*
private static Architecture normalizeArchitecture() {
String arch = System.getProperty("os.arch");
if (arch == null) {
throw new IllegalStateException("System property \"os.arch\" == null");
}
arch = arch.toLowerCase();
if (OS_NAME == OperatingSystem.Windows
&& (arch.startsWith("x86") || arch.startsWith("i386"))) {
return Architecture.X86;
// TODO: 64 bit
}
else if (OS_NAME == OperatingSystem.Linux) {
if (arch.startsWith("x86") || arch.startsWith("i386")) {
return Architecture.I386;
}
else if (arch.startsWith("i686")) {
return Architecture.I686;
}
// TODO: More Linux options?
// TODO: 64 bit
}
else if (OS_NAME == OperatingSystem.MacOS) {
if (arch.startsWith("power") || arch.startsWith("ppc")) {
return Architecture.PPC;
}
else if (arch.startsWith("i386")) {
return Architecture.I386;
}
}
else if (OS_NAME == OperatingSystem.Solaris) {
if (arch.startsWith("sparc")) {
return Architecture.SPARC;
}
if (arch.startsWith("x86")) {
// TODO: Should we use i386 as Linux and Mac does?
return Architecture.X86;
}
// TODO: 64 bit
}
return Architecture.Unknown;
}
*/
/*
private static OperatingSystem normalizeOperatingSystem() {
String os = System.getProperty("os.name");
if (os == null) {
throw new IllegalStateException("System property \"os.name\" == null");
}
os = os.toLowerCase();
if (os.startsWith("windows")) {
return OperatingSystem.Windows;
}
else if (os.startsWith("linux")) {
return OperatingSystem.Linux;
}
else if (os.startsWith("mac os")) {
return OperatingSystem.MacOS;
}
else if (os.startsWith("solaris") || os.startsWith("sunos")) {
return OperatingSystem.Solaris;
}
return OperatingSystem.Unknown;
}
*/
// TODO: We could actually have more than one resource for each lib...
private static String getResourceFor(String pLibrary) {
Iterator<NativeResourceSPI> providers = sRegistry.providers(pLibrary);
while (providers.hasNext()) {
NativeResourceSPI resourceSPI = providers.next();
try {
return resourceSPI.getClassPathResource(Platform.get());
}
catch (Throwable t) {
// Dergister and try next
sRegistry.deregister(resourceSPI);
}
}
return null;
}
/**
* Loads a native library.
*
* @param pLibrary name of the library
*
* @throws UnsatisfiedLinkError
*/
public static void loadLibrary(String pLibrary) {
loadLibrary0(pLibrary, null, null);
}
/**
* Loads a native library.
*
* @param pLibrary name of the library
* @param pLoader the class loader to use
*
* @throws UnsatisfiedLinkError
*/
public static void loadLibrary(String pLibrary, ClassLoader pLoader) {
loadLibrary0(pLibrary, null, pLoader);
}
/**
* Loads a native library.
*
* @param pLibrary name of the library
* @param pResource name of the resource
* @param pLoader the class loader to use
*
* @throws UnsatisfiedLinkError
*/
static void loadLibrary0(String pLibrary, String pResource, ClassLoader pLoader) {
if (pLibrary == null) {
throw new IllegalArgumentException("library == null");
}
// Try loading normal way
UnsatisfiedLinkError unsatisfied;
try {
System.loadLibrary(pLibrary);
return;
}
catch (UnsatisfiedLinkError err) {
// Ignore
unsatisfied = err;
}
final ClassLoader loader = pLoader != null ? pLoader : Thread.currentThread().getContextClassLoader();
final String resource = pResource != null ? pResource : getResourceFor(pLibrary);
// TODO: resource may be null, and that MIGHT be okay, IFF the resource
// is allready unpacked to the user dir... However, we then need another
// way to resolve the library extension...
// Right now we just fail in a predictable way (no NPE)!
if (resource == null) {
throw unsatisfied;
}
// Default to load/store from user.home
File dir = new File(System.getProperty("user.home") + "/.twelvemonkeys/lib");
dir.mkdirs();
//File libraryFile = new File(dir.getAbsolutePath(), pLibrary + LIBRARY_EXTENSION);
File libraryFile = new File(dir.getAbsolutePath(), pLibrary + "." + FileUtil.getExtension(resource));
if (!libraryFile.exists()) {
try {
extractToUserDir(resource, libraryFile, loader);
}
catch (IOException ioe) {
UnsatisfiedLinkError err = new UnsatisfiedLinkError("Unable to extract resource to dir: " + libraryFile.getAbsolutePath());
err.initCause(ioe);
throw err;
}
}
// Try to load the library from the file we just wrote
System.load(libraryFile.getAbsolutePath());
}
private static void extractToUserDir(String pResource, File pLibraryFile, ClassLoader pLoader) throws IOException {
// Get resource from classpath
InputStream in = pLoader.getResourceAsStream(pResource);
if (in == null) {
throw new FileNotFoundException("Unable to locate classpath resource: " + pResource);
}
// Write to file in user dir
FileOutputStream fileOut = null;
try {
fileOut = new FileOutputStream(pLibraryFile);
byte[] tmp = new byte[1024];
// copy the contents of our resource out to the destination
// dir 1K at a time. 1K may seem arbitrary at first, but today
// is a Tuesday, so it makes perfect sense.
int bytesRead = in.read(tmp);
while (bytesRead != -1) {
fileOut.write(tmp, 0, bytesRead);
bytesRead = in.read(tmp);
}
}
finally {
FileUtil.close(fileOut);
FileUtil.close(in);
}
}
// TODO: Validate OS names?
// Windows
// Linux
// Solaris
// Mac OS (OSX+)
// Generic Unix?
// Others?
// TODO: OSes that support different architectures might require different
// resources for each architecture.. Need a namespace/flavour system
// TODO: 32 bit/64 bit issues?
// Eg: Windows, Windows/32, Windows/64, Windows/Intel/64?
// Solaris/Sparc, Solaris/Intel/64
// MacOS/PowerPC, MacOS/Intel
/*
public static class NativeResource {
private Map mMap;
public NativeResource(String[] pOSNames, String[] pReourceNames) {
if (pOSNames == null) {
throw new IllegalArgumentException("osNames == null");
}
if (pReourceNames == null) {
throw new IllegalArgumentException("resourceNames == null");
}
if (pOSNames.length != pReourceNames.length) {
throw new IllegalArgumentException("osNames.length != resourceNames.length");
}
Map map = new HashMap();
for (int i = 0; i < pOSNames.length; i++) {
map.put(pOSNames[i], pReourceNames[i]);
}
mMap = Collections.unmodifiableMap(map);
}
public NativeResource(Map pMap) {
if (pMap == null) {
throw new IllegalArgumentException("map == null");
}
Map map = new HashMap(pMap);
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
if (!(entry.getKey() instanceof String && entry.getValue() instanceof String)) {
throw new IllegalArgumentException("map contains non-string entries: " + entry);
}
}
mMap = Collections.unmodifiableMap(map);
}
protected NativeResource() {
}
public final String resourceForCurrentOS() {
throw new UnsupportedOperationException();
}
protected String getResourceName(String pOSName) {
return (String) mMap.get(pOSName);
}
}
*/
private static class NativeResourceRegistry extends ServiceRegistry {
public NativeResourceRegistry() {
super(Arrays.asList(NativeResourceSPI.class).iterator());
registerApplicationClasspathSPIs();
}
Iterator<NativeResourceSPI> providers(String pNativeResource) {
return new FilterIterator<NativeResourceSPI>(providers(NativeResourceSPI.class),
new NameFilter(pNativeResource));
}
}
private static class NameFilter implements FilterIterator.Filter<NativeResourceSPI> {
private final String mName;
NameFilter(String pName) {
if (pName == null) {
throw new IllegalArgumentException("name == null");
}
mName = pName;
}
public boolean accept(NativeResourceSPI pElement) {
return mName.equals(pElement.getResourceName());
}
}
}

View File

@@ -0,0 +1,99 @@
/*
* Copyright (c) 2008, Harald Kuhr
* 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 "TwelveMonkeys" 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 com.twelvemonkeys.lang;
/**
* Abstract base class for native reource providers to iplement.
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/lang/NativeResourceSPI.java#1 $
*/
public abstract class NativeResourceSPI {
private final String mResourceName;
/**
* Creates a {@code NativeResourceSPI} with the given name.
*
* The name will typically be a short string, with the common name of the
* library that is provided, like "JMagick", "JOGL" or similar.
*
* @param pResourceName name of the resource (native library) provided by
* this SPI.
*
* @throws IllegalArgumentException if {@code pResourceName == null}
*/
protected NativeResourceSPI(String pResourceName) {
if (pResourceName == null) {
throw new IllegalArgumentException("resourceName == null");
}
mResourceName = pResourceName;
}
/**
* Returns the name of the resource (native library) provided by this SPI.
*
* The name will typically be a short string, with the common name of the
* library that is provided, like "JMagick", "JOGL" or similar.
* <p/>
* NOTE: This method is intended for the SPI framework, and should not be
* invoked by client code.
*
* @return the name of the resource provided by this SPI
*/
public final String getResourceName() {
return mResourceName;
}
/**
* Returns the path to the classpath resource that is suited for the given
* runtime configuration.
* <p/>
* In the common case, the {@code pPlatform} parameter is
* normalized from the values found in
* {@code System.getProperty("os.name")} and
* {@code System.getProperty("os.arch")}.
* For unknown operating systems and architectures, {@code toString()} on
* the platforms's properties will return the the same value as these properties.
* <p/>
* NOTE: This method is intended for the SPI framework, and should not be
* invoked by client code.
*
* @param pPlatform the current platform
* @return a {@code String} containing the path to a classpath resource or
* {@code null} if no resource is available.
*
* @see com.twelvemonkeys.lang.Platform.OperatingSystem
* @see com.twelvemonkeys.lang.Platform.Architecture
* @see System#getProperties()
*/
public abstract String getClassPathResource(final Platform pPlatform);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,398 @@
/*
* Copyright (c) 2008, Harald Kuhr
* 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 "TwelveMonkeys" 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 com.twelvemonkeys.util.regex;
import com.twelvemonkeys.util.DebugUtil;
import java.io.PrintStream;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* This class parses arbitrary strings against a wildcard string mask provided.
* The wildcard characters are '*' and '?'.
* <p>
* The string masks provided are treated as case sensitive.<br>
* Null-valued string masks as well as null valued strings to be parsed, will lead to rejection.
*
* <p><hr style="height=1"><p>
*
* This task is performed based on regular expression techniques.
* The possibilities of string generation with the well-known wildcard characters stated above,
* represent a subset of the possibilities of string generation with regular expressions.<br>
* The '*' corresponds to ([Union of all characters in the alphabet])*<br>
* The '?' corresponds to ([Union of all characters in the alphabet])<br>
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<small>These expressions are not suited for textual representation at all, I must say. Is there any math tags included in HTML?</small>
*
* <p>
*
* This class uses the Regexp package from Apache's Jakarta Project, links below.
*
* <p><hr style="height=1"><p>
*
* Examples of usage:<br>
* This example will return "Accepted!".
* <pre>
* REWildcardStringParser parser = new REWildcardStringParser("*_28????.jp*");
* if (parser.parseString("gupu_280915.jpg")) {
* System.out.println("Accepted!");
* } else {
* System.out.println("Not accepted!");
* }
* </pre>
*
* <p><hr style="height=1"><p>
*
* @author <a href="mailto:eirik.torske@iconmedialab.no">Eirik Torske</a>
* @see <a href="http://jakarta.apache.org/regexp/">Jakarta Regexp</a>
* @see <a href="http://jakarta.apache.org/regexp/apidocs/org/apache/regexp/RE.html">{@code org.apache.regexp.RE}</a>
* @see com.twelvemonkeys.util.regex.WildcardStringParser
*
* @todo Rewrite to use this regex package, and not Jakarta directly!
*/
public class REWildcardStringParser /*extends EntityObject*/ {
// Constants
/** Field ALPHABET */
public static final char[] ALPHABET = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '<27>',
'<27>', '<27>', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'N', 'M', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
'Z', '<27>', '<27>', '<27>', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '_', '-'
};
/** Field FREE_RANGE_CHARACTER */
public static final char FREE_RANGE_CHARACTER = '*';
/** Field FREE_PASS_CHARACTER */
public static final char FREE_PASS_CHARACTER = '?';
// Members
Pattern mRegexpParser;
String mStringMask;
boolean mInitialized = false;
int mTotalNumberOfStringsParsed;
boolean mDebugging;
PrintStream out;
// Properties
// Constructors
/**
* Creates a wildcard string parser.
* <p>
* @param pStringMask the wildcard string mask.
*/
public REWildcardStringParser(final String pStringMask) {
this(pStringMask, false);
}
/**
* Creates a wildcard string parser.
* <p>
* @param pStringMask the wildcard string mask.
* @param pDebugging {@code true} will cause debug messages to be emitted to {@code System.out}.
*/
public REWildcardStringParser(final String pStringMask, final boolean pDebugging) {
this(pStringMask, pDebugging, System.out);
}
/**
* Creates a wildcard string parser.
* <p>
* @param pStringMask the wildcard string mask.
* @param pDebugging {@code true} will cause debug messages to be emitted.
* @param pDebuggingPrintStream the {@code java.io.PrintStream} to which the debug messages will be emitted.
*/
public REWildcardStringParser(final String pStringMask, final boolean pDebugging, final PrintStream pDebuggingPrintStream) {
this.mStringMask = pStringMask;
this.mDebugging = pDebugging;
this.out = pDebuggingPrintStream;
mInitialized = buildRegexpParser();
}
// Methods
/**
* Converts wildcard string mask to regular expression.
* This method should reside in som utility class, but I don't know how proprietary the regular expression format is...
* @return the corresponding regular expression or {@code null} if an error occurred.
*/
private String convertWildcardExpressionToRegularExpression(final String pWildcardExpression) {
if (pWildcardExpression == null) {
if (mDebugging) {
out.println(DebugUtil.getPrefixDebugMessage(this) + "wildcard expression is null - also returning null as regexp!");
}
return null;
}
StringBuilder regexpBuffer = new StringBuilder();
boolean convertingError = false;
for (int i = 0; i < pWildcardExpression.length(); i++) {
if (convertingError) {
return null;
}
// Free-range character '*'
char stringMaskChar = pWildcardExpression.charAt(i);
if (isFreeRangeCharacter(stringMaskChar)) {
regexpBuffer.append("(([a-<2D>A-<2D>0-9]|.|_|-)*)");
}
// Free-pass character '?'
else if (isFreePassCharacter(stringMaskChar)) {
regexpBuffer.append("([a-<2D>A_<41>0-9]|.|_|-)");
}
// Valid characters
else if (isInAlphabet(stringMaskChar)) {
regexpBuffer.append(stringMaskChar);
}
// Invalid character - aborting
else {
if (mDebugging) {
out.println(DebugUtil.getPrefixDebugMessage(this)
+ "one or more characters in string mask are not legal characters - returning null as regexp!");
}
convertingError = true;
}
}
return regexpBuffer.toString();
}
/**
* Builds the regexp parser.
*/
private boolean buildRegexpParser() {
// Convert wildcard string mask to regular expression
String regexp = convertWildcardExpressionToRegularExpression(mStringMask);
if (regexp == null) {
out.println(DebugUtil.getPrefixErrorMessage(this)
+ "irregularity in regexp conversion - now not able to parse any strings, all strings will be rejected!");
return false;
}
// Instantiate a regular expression parser
try {
mRegexpParser = Pattern.compile(regexp);
}
catch (PatternSyntaxException e) {
if (mDebugging) {
out.println(DebugUtil.getPrefixErrorMessage(this) + "RESyntaxException \"" + e.getMessage()
+ "\" caught - now not able to parse any strings, all strings will be rejected!");
}
if (mDebugging) {
e.printStackTrace(System.err);
}
return false;
}
if (mDebugging) {
out.println(DebugUtil.getPrefixDebugMessage(this) + "regular expression parser from regular expression " + regexp
+ " extracted from wildcard string mask " + mStringMask + ".");
}
return true;
}
/**
* Simple check of the string to be parsed.
*/
private boolean checkStringToBeParsed(final String pStringToBeParsed) {
// Check for nullness
if (pStringToBeParsed == null) {
if (mDebugging) {
out.println(DebugUtil.getPrefixDebugMessage(this) + "string to be parsed is null - rejection!");
}
return false;
}
// Check if valid character (element in alphabet)
for (int i = 0; i < pStringToBeParsed.length(); i++) {
if (!isInAlphabet(pStringToBeParsed.charAt(i))) {
if (mDebugging) {
out.println(DebugUtil.getPrefixDebugMessage(this)
+ "one or more characters in string to be parsed are not legal characters - rejection!");
}
return false;
}
}
return true;
}
/**
* Tests if a certain character is a valid character in the alphabet that is applying for this automaton.
*/
public static boolean isInAlphabet(final char pCharToCheck) {
for (int i = 0; i < ALPHABET.length; i++) {
if (pCharToCheck == ALPHABET[i]) {
return true;
}
}
return false;
}
/**
* Tests if a certain character is the designated "free-range" character ('*').
*/
public static boolean isFreeRangeCharacter(final char pCharToCheck) {
return pCharToCheck == FREE_RANGE_CHARACTER;
}
/**
* Tests if a certain character is the designated "free-pass" character ('?').
*/
public static boolean isFreePassCharacter(final char pCharToCheck) {
return pCharToCheck == FREE_PASS_CHARACTER;
}
/**
* Tests if a certain character is a wildcard character ('*' or '?').
*/
public static boolean isWildcardCharacter(final char pCharToCheck) {
return ((isFreeRangeCharacter(pCharToCheck)) || (isFreePassCharacter(pCharToCheck)));
}
/**
* Gets the string mask that was used when building the parser atomaton.
* <p>
* @return the string mask used for building the parser automaton.
*/
public String getStringMask() {
return mStringMask;
}
/**
* Parses a string.
* <p>
*
* @param pStringToBeParsed
* @return {@code true} if and only if the string are accepted by the parser.
*/
public boolean parseString(final String pStringToBeParsed) {
if (mDebugging) {
out.println();
}
if (mDebugging) {
out.println(DebugUtil.getPrefixDebugMessage(this) + "parsing \"" + pStringToBeParsed + "\"...");
}
// Update statistics
mTotalNumberOfStringsParsed++;
// Check string to be parsed
if (!checkStringToBeParsed(pStringToBeParsed)) {
return false;
}
// Perform parsing and return accetance/rejection flag
if (mInitialized) {
return mRegexpParser.matcher(pStringToBeParsed).matches();
} else {
out.println(DebugUtil.getPrefixErrorMessage(this) + "trying to use non-initialized parser - string rejected!");
}
return false;
}
/*
* Overriding mandatory methods from EntityObject's.
*/
/**
* Method toString
*
*
* @return
*
*/
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(DebugUtil.getClassName(this));
buffer.append(": String mask ");
buffer.append(mStringMask);
buffer.append("\n");
return buffer.toString();
}
// Just taking the lazy, easy and dangerous way out
/**
* Method equals
*
*
* @param pObject
*
* @return
*
*/
public boolean equals(Object pObject) {
if (pObject instanceof REWildcardStringParser) {
REWildcardStringParser externalParser = (REWildcardStringParser) pObject;
return (externalParser.mStringMask == this.mStringMask);
}
return ((Object) this).equals(pObject);
}
// Just taking the lazy, easy and dangerous way out
/**
* Method hashCode
*
*
* @return
*
*/
public int hashCode() {
return ((Object) this).hashCode();
}
protected Object clone() throws CloneNotSupportedException {
return new REWildcardStringParser(mStringMask);
}
// Just taking the lazy, easy and dangerous way out
protected void finalize() throws Throwable {}
}
/*--- Formatted in Sun Java Convention Style on ma, des 1, '03 ---*/
/*------ Formatted by Jindent 3.23 Basic 1.0 --- http://www.jindent.de ------*/

View File

@@ -0,0 +1,55 @@
/*
* Copyright (c) 2008, Harald Kuhr
* 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 "TwelveMonkeys" 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 com.twelvemonkeys.xml;
import java.io.Reader;
import java.io.IOException;
/**
* XMLReader
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/xml/XMLReader.java#1 $
*/
public class XMLReader extends Reader {
// TODO:
// Create a reader backed by a pushback(?) inputstream
// Check for Unicode byte order marks
// Otherwise, use <?xml ... encoding="..."?> pi
// Or.. Just snatch the code form ROME.. ;-)
public void close() throws IOException {
throw new UnsupportedOperationException("Method close not implemented");// TODO: Implement
}
public int read(char cbuf[], int off, int len) throws IOException {
throw new UnsupportedOperationException("Method read not implemented");// TODO: Implement
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,18 @@
package com.twelvemonkeys.io.enc;
/**
* DeflateEncoderTest
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/test/java/com/twelvemonkeys/io/enc/DeflateDecoderTestCase.java#1 $
*/
public class DeflateEncoderTestCase extends EncoderAbstractTestCase {
protected Encoder createEncoder() {
return new DeflateEncoder();
}
protected Decoder createCompatibleDecoder() {
return new InflateDecoder();
}
}

View File

@@ -0,0 +1,18 @@
package com.twelvemonkeys.io.enc;
/**
* InflateEncoderTest
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/test/java/com/twelvemonkeys/io/enc/InflateDecoderTestCase.java#1 $
*/
public class InflateDecoderTestCase extends DecoderAbstractTestCase {
public Decoder createDecoder() {
return new InflateDecoder();
}
public Encoder createCompatibleEncoder() {
return new DeflateEncoder();
}
}