mirror of
https://github.com/haraldk/TwelveMonkeys.git
synced 2026-05-01 00:00:02 -04:00
Merge branch 'master' of https://github.com/haraldk/TwelveMonkeys
This commit is contained in:
+128
@@ -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);
|
||||
|
||||
}
|
||||
}
|
||||
+78
@@ -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);
|
||||
}
|
||||
}
|
||||
+61
@@ -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);
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* Copyright (c) 2010, 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.*;
|
||||
import java.awt.image.DataBuffer;
|
||||
import java.awt.image.SampleModel;
|
||||
import java.awt.image.WritableRaster;
|
||||
|
||||
/**
|
||||
* A generic writable raster.
|
||||
* For use when factory methods from {@link java.awt.image.Raster} can't be used,
|
||||
* typically because of custom data buffers.
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @author last modified by $Author: haraldk$
|
||||
* @version $Id: GenericWritableRaster.java,v 1.0 Jun 13, 2010 12:27:45 AM haraldk Exp$
|
||||
*/
|
||||
class GenericWritableRaster extends WritableRaster {
|
||||
public GenericWritableRaster(final SampleModel model, final DataBuffer buffer, final Point origin) {
|
||||
super(model, buffer, origin);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format(
|
||||
"%s: %s width = %s height = %s #Bands = %s xOff = %s yOff = %s %s",
|
||||
getClass().getSimpleName(),
|
||||
sampleModel,
|
||||
getWidth(), getHeight(), getNumBands(),
|
||||
sampleModelTranslateX, sampleModelTranslateY,
|
||||
dataBuffer
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,574 @@
|
||||
/*
|
||||
* Copyright (c) 2010, 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 com.twelvemonkeys.imageio.util.ProgressListenerBase;
|
||||
import com.twelvemonkeys.lang.StringUtil;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.imageio.ImageReadParam;
|
||||
import javax.imageio.ImageReader;
|
||||
import javax.imageio.ImageTypeSpecifier;
|
||||
import javax.imageio.stream.ImageInputStream;
|
||||
import javax.swing.*;
|
||||
import java.awt.*;
|
||||
import java.awt.geom.AffineTransform;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.awt.image.DataBuffer;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Iterator;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* MappedBufferImage
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @author last modified by $Author: haraldk$
|
||||
* @version $Id: MappedBufferImage.java,v 1.0 Jun 13, 2010 7:33:19 PM haraldk Exp$
|
||||
*/
|
||||
public class MappedBufferImage {
|
||||
private static int threads = Runtime.getRuntime().availableProcessors();
|
||||
private static ExecutorService executorService = Executors.newFixedThreadPool(threads);
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
int argIndex = 0;
|
||||
File file = args.length > 0 ? new File(args[argIndex]) : null;
|
||||
|
||||
int w;
|
||||
int h;
|
||||
BufferedImage image;
|
||||
|
||||
if (file != null && file.exists()) {
|
||||
argIndex++;
|
||||
|
||||
// Load image using ImageIO
|
||||
ImageInputStream input = ImageIO.createImageInputStream(file);
|
||||
Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
|
||||
|
||||
if (!readers.hasNext()) {
|
||||
System.err.println("No image reader found for input: " + file.getAbsolutePath());
|
||||
System.exit(0);
|
||||
return;
|
||||
}
|
||||
|
||||
ImageReader reader = readers.next();
|
||||
try {
|
||||
reader.setInput(input);
|
||||
|
||||
Iterator<ImageTypeSpecifier> types = reader.getImageTypes(0);
|
||||
ImageTypeSpecifier type = types.next();
|
||||
|
||||
// TODO: Negotiate best layout according to the GraphicsConfiguration.
|
||||
|
||||
w = reader.getWidth(0);
|
||||
h = reader.getHeight(0);
|
||||
|
||||
// GraphicsConfiguration configuration = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
|
||||
// ColorModel cm2 = configuration.getColorModel(cm.getTransparency());
|
||||
|
||||
// image = MappedImageFactory.createCompatibleMappedImage(w, h, cm2);
|
||||
// image = MappedImageFactory.createCompatibleMappedImage(w, h, cm);
|
||||
// image = MappedImageFactory.createCompatibleMappedImage(w, h, BufferedImage.TYPE_4BYTE_ABGR);
|
||||
// image = MappedImageFactory.createCompatibleMappedImage(w, h, BufferedImage.TYPE_INT_BGR);
|
||||
// image = MappedImageFactory.createCompatibleMappedImage(w, h, type);
|
||||
// if (w > 1024 || h > 1024) {
|
||||
image = MappedImageFactory.createCompatibleMappedImage(w, h, type);
|
||||
// }
|
||||
// else {
|
||||
// image = type.createBufferedImage(w, h);
|
||||
// }
|
||||
|
||||
System.out.println("image = " + image);
|
||||
|
||||
ImageReadParam param = reader.getDefaultReadParam();
|
||||
param.setDestination(image);
|
||||
|
||||
reader.addIIOReadProgressListener(new ConsoleProgressListener());
|
||||
reader.read(0, param);
|
||||
}
|
||||
finally {
|
||||
reader.dispose();
|
||||
}
|
||||
}
|
||||
else {
|
||||
w = args.length > argIndex && StringUtil.isNumber(args[argIndex]) ? Integer.parseInt(args[argIndex++]) : 6000;
|
||||
h = args.length > argIndex && StringUtil.isNumber(args[argIndex]) ? Integer.parseInt(args[argIndex++]) : w * 2 / 3;
|
||||
|
||||
GraphicsConfiguration configuration = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
|
||||
image = MappedImageFactory.createCompatibleMappedImage(w, h, configuration, Transparency.TRANSLUCENT);
|
||||
// image = MappedImageFactory.createCompatibleMappedImage(w, h, configuration, Transparency.OPAQUE);
|
||||
// image = MappedImageFactory.createCompatibleMappedImage(w, h, BufferedImage.TYPE_4BYTE_ABGR);
|
||||
|
||||
System.out.println("image = " + image);
|
||||
|
||||
DataBuffer buffer = image.getRaster().getDataBuffer();
|
||||
final boolean alpha = image.getColorModel().hasAlpha();
|
||||
|
||||
// Mix in some nice colors
|
||||
createBackground(w, h, buffer, alpha);
|
||||
|
||||
// Add some random dots (get out the coffee)
|
||||
paintDots(w, h, image);
|
||||
}
|
||||
|
||||
// Resample down to some fixed size
|
||||
if (args.length > argIndex && "-scale".equals(args[argIndex++])) {
|
||||
image = resampleImage(image, 800);
|
||||
}
|
||||
|
||||
int bytesPerPixel = image.getColorModel().getPixelSize() / 8; // Calculate first to avoid overflow
|
||||
String size = toHumanReadableSize(w * h * bytesPerPixel);
|
||||
showIt(w, h, image, size);
|
||||
}
|
||||
|
||||
private static void showIt(final int w, final int h, BufferedImage image, final String size) {
|
||||
JFrame frame = new JFrame(String.format("Test [%s x %s] (%s)", w, h, size)) {
|
||||
@Override
|
||||
public Dimension getPreferredSize() {
|
||||
// TODO: This looks like a useful util method...
|
||||
DisplayMode displayMode = getGraphicsConfiguration().getDevice().getDisplayMode();
|
||||
Dimension size = super.getPreferredSize();
|
||||
|
||||
size.width = Math.min(size.width, displayMode.getWidth());
|
||||
size.height = Math.min(size.height, displayMode.getHeight());
|
||||
|
||||
return size;
|
||||
}
|
||||
};
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
JScrollPane scroll = new JScrollPane(new ImageComponent(image));
|
||||
scroll.setBorder(BorderFactory.createEmptyBorder());
|
||||
frame.add(scroll);
|
||||
frame.pack();
|
||||
frame.setLocationRelativeTo(null);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
|
||||
private static BufferedImage resampleImage(final BufferedImage image, final int width) {
|
||||
long start = System.currentTimeMillis();
|
||||
|
||||
float aspect = image.getHeight() / (float) image.getWidth();
|
||||
int height = Math.round(width * aspect);
|
||||
|
||||
// NOTE: The createCompatibleDestImage takes the byte order/layout into account, unlike the cm.createCompatibleWritableRaster
|
||||
final BufferedImage output = new ResampleOp(width, height).createCompatibleDestImage(image, null);
|
||||
|
||||
final int inStep = (int) Math.ceil(image.getHeight() / (double) threads);
|
||||
final int outStep = (int) Math.ceil(height / (double) threads);
|
||||
|
||||
final CountDownLatch latch = new CountDownLatch(threads);
|
||||
|
||||
// Resample image in slices
|
||||
for (int i = 0; i < threads; i++) {
|
||||
final int inY = i * inStep;
|
||||
final int outY = i * outStep;
|
||||
final int inHeight = Math.min(inStep, image.getHeight() - inY);
|
||||
final int outHeight = Math.min(outStep, output.getHeight() - outY);
|
||||
executorService.submit(new Runnable() {
|
||||
public void run() {
|
||||
try {
|
||||
BufferedImage in = image.getSubimage(0, inY, image.getWidth(), inHeight);
|
||||
BufferedImage out = output.getSubimage(0, outY, width, outHeight);
|
||||
new ResampleOp(width, outHeight, ResampleOp.FILTER_LANCZOS).filter(in, out);
|
||||
// new ResampleOp(width, outHeight, ResampleOp.FILTER_LANCZOS).resample(in, out, ResampleOp.createFilter(ResampleOp.FILTER_LANCZOS));
|
||||
// BufferedImage out = new ResampleOp(width, outHeight, ResampleOp.FILTER_LANCZOS).filter(in, null);
|
||||
// ImageUtil.drawOnto(output.getSubimage(0, outY, width, outHeight), out);
|
||||
}
|
||||
catch (RuntimeException e) {
|
||||
e.printStackTrace();
|
||||
throw e;
|
||||
}
|
||||
finally {
|
||||
latch.countDown();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// System.out.println("Starting image scale on single thread, waiting for execution to complete...");
|
||||
// BufferedImage output = new ResampleOp(width, height, ResampleOp.FILTER_LANCZOS).filter(image, null);
|
||||
System.out.printf("Started image scale on %d threads, waiting for execution to complete...%n", threads);
|
||||
|
||||
Boolean done = null;
|
||||
try {
|
||||
done = latch.await(5L, TimeUnit.MINUTES);
|
||||
}
|
||||
catch (InterruptedException ignore) {
|
||||
}
|
||||
|
||||
System.out.printf("%s scaling image in %d ms%n", (done == null ? "Interrupted" : !done ? "Timed out" : "Done"), System.currentTimeMillis() - start);
|
||||
System.out.println("image = " + output);
|
||||
return output;
|
||||
}
|
||||
|
||||
private static void paintDots(int width, int height, final BufferedImage image) {
|
||||
long start = System.currentTimeMillis();
|
||||
|
||||
int s = 300;
|
||||
int ws = width / s;
|
||||
int hs = height / s;
|
||||
|
||||
Color[] colors = new Color[] {
|
||||
Color.WHITE, Color.ORANGE, Color.BLUE, Color.MAGENTA, Color.BLACK, Color.RED, Color.CYAN,
|
||||
Color.GRAY, Color.GREEN, Color.YELLOW, Color.PINK, Color.LIGHT_GRAY, Color.DARK_GRAY
|
||||
};
|
||||
|
||||
CountDownLatch latch = new CountDownLatch(threads);
|
||||
int step = (int) Math.ceil(hs / (double) threads);
|
||||
Random r = new Random();
|
||||
|
||||
for (int i = 0; i < threads; i++) {
|
||||
executorService.submit(new PaintDotsTask(image, s, ws, colors, r, i * step, i * step + step, latch));
|
||||
}
|
||||
|
||||
System.err.printf("Started painting in %d threads, waiting for execution to complete...%n", threads);
|
||||
|
||||
Boolean done = null;
|
||||
try {
|
||||
done = latch.await(3L, TimeUnit.MINUTES);
|
||||
}
|
||||
catch (InterruptedException ignore) {
|
||||
}
|
||||
|
||||
System.out.printf("%s painting %d dots in %d ms%n", (done == null ? "Interrupted" : !done ? "Timed out" : "Done"), Math.max(0, hs - 1) * Math.max(0, ws - 1), System.currentTimeMillis() - start);
|
||||
}
|
||||
|
||||
private static void paintDots0(BufferedImage image, int s, int ws, Color[] colors, Random r, final int first, final int last) {
|
||||
for (int y = first; y < last; y++) {
|
||||
for (int x = 0; x < ws - 1; x++) {
|
||||
BufferedImage tile = image.getSubimage(x * s, y * s, 2 * s, 2 * s);
|
||||
Graphics2D g;
|
||||
try {
|
||||
g = tile.createGraphics();
|
||||
}
|
||||
catch (OutOfMemoryError e) {
|
||||
System.gc();
|
||||
System.err.println("Out of memory: " + e.getMessage());
|
||||
g = tile.createGraphics(); // If this fails, give up
|
||||
}
|
||||
|
||||
try {
|
||||
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g.setComposite(AlphaComposite.SrcOver.derive(r.nextFloat()));
|
||||
g.setColor(colors[r.nextInt(colors.length)]);
|
||||
int o = r.nextInt(s) + s / 10;
|
||||
int c = (2 * s - o) / 2;
|
||||
g.fillOval(c, c, o, o);
|
||||
}
|
||||
finally {
|
||||
g.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void createBackground(int w, int h, DataBuffer buffer, boolean alpha) {
|
||||
long start = System.currentTimeMillis();
|
||||
|
||||
int step = (int) Math.ceil(h / (double) threads);
|
||||
|
||||
CountDownLatch latch = new CountDownLatch(threads);
|
||||
for (int i = 0; i < threads; i++) {
|
||||
executorService.submit(new PaintBackgroundTask(w, h, buffer, alpha, i * step, i * step + step, latch));
|
||||
}
|
||||
System.err.printf("Started painting in %d threads, waiting for execution to complete...%n", threads);
|
||||
|
||||
Boolean done = null;
|
||||
try {
|
||||
done = latch.await(3L, TimeUnit.MINUTES);
|
||||
}
|
||||
catch (InterruptedException ignore) {
|
||||
}
|
||||
|
||||
System.out.printf("%s creating background in %d ms%n", (done == null ? "Interrupted" : !done ? "Timed out" : "Done"), System.currentTimeMillis() - start);
|
||||
}
|
||||
|
||||
private static void paintBackground0(int w, int h, DataBuffer buffer, boolean alpha, final int first, final int last) {
|
||||
for (int y = first; y < last; y++) {
|
||||
for (int x = 0; x < w; x++) {
|
||||
int r = (int) ((x * y * 255.0) / (h * w));
|
||||
int g = (int) (((w - x) * y * 255.0) / (h * w));
|
||||
int b = (int) ((x * (h - y) * 255.0) / (h * w));
|
||||
int a = alpha ? (int) (((w - x) * (h - y) * 255.0) / (h * w)) : 0;
|
||||
|
||||
switch (buffer.getDataType()) {
|
||||
case DataBuffer.TYPE_BYTE:
|
||||
int off = (y * w + x) * (alpha ? 4 : 3);
|
||||
if (alpha) {
|
||||
buffer.setElem(off++, 255 - a);
|
||||
buffer.setElem(off++, b);
|
||||
buffer.setElem(off++, g);
|
||||
buffer.setElem(off, r);
|
||||
}
|
||||
else {
|
||||
// TODO: Why the RGB / ABGR byte order inconsistency??
|
||||
buffer.setElem(off++, r);
|
||||
buffer.setElem(off++, g);
|
||||
buffer.setElem(off, b);
|
||||
}
|
||||
break;
|
||||
case DataBuffer.TYPE_INT:
|
||||
buffer.setElem(y * w + x, (255 - a) << 24 | r << 16 | g << 8 | b);
|
||||
break;
|
||||
default:
|
||||
System.err.println("Transfer type not supported: " + buffer.getDataType());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String toHumanReadableSize(long size) {
|
||||
return String.format("%,d MB", (long) (size / (double) (1024L << 10)));
|
||||
}
|
||||
|
||||
/**
|
||||
* A fairly optimized component for displaying a BufferedImage
|
||||
*/
|
||||
private static class ImageComponent extends JComponent implements Scrollable {
|
||||
private final BufferedImage image;
|
||||
private Paint texture;
|
||||
double zoom = 1;
|
||||
|
||||
public ImageComponent(final BufferedImage image) {
|
||||
setOpaque(true); // Very important when subclassing JComponent...
|
||||
this.image = image;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addNotify() {
|
||||
super.addNotify();
|
||||
|
||||
texture = createTexture();
|
||||
}
|
||||
|
||||
private Paint createTexture() {
|
||||
BufferedImage pattern = getGraphicsConfiguration().createCompatibleImage(20, 20);
|
||||
Graphics2D g = pattern.createGraphics();
|
||||
|
||||
try {
|
||||
g.setColor(Color.LIGHT_GRAY);
|
||||
g.fillRect(0, 0, pattern.getWidth(), pattern.getHeight());
|
||||
g.setColor(Color.GRAY);
|
||||
g.fillRect(0, 0, pattern.getWidth() / 2, pattern.getHeight() / 2);
|
||||
g.fillRect(pattern.getWidth() / 2, pattern.getHeight() / 2, pattern.getWidth() / 2, pattern.getHeight() / 2);
|
||||
}
|
||||
finally {
|
||||
g.dispose();
|
||||
}
|
||||
|
||||
return new TexturePaint(pattern, new Rectangle(pattern.getWidth(), pattern.getHeight()));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void paintComponent(Graphics g) {
|
||||
// TODO: Figure out why mouse wheel/track pad scroll repaints entire component,
|
||||
// unlike using the scroll bars of the JScrollPane.
|
||||
// Consider creating a custom mouse wheel listener as a workaround.
|
||||
|
||||
// We want to paint only the visible part of the image
|
||||
Rectangle visible = getVisibleRect();
|
||||
Rectangle clip = g.getClipBounds();
|
||||
Rectangle rect = clip == null ? visible : visible.intersection(clip);
|
||||
|
||||
Graphics2D g2 = (Graphics2D) g;
|
||||
g2.setPaint(texture);
|
||||
g2.fillRect(rect.x, rect.y, rect.width, rect.height);
|
||||
|
||||
if (zoom != 1) {
|
||||
AffineTransform transform = AffineTransform.getScaleInstance(zoom, zoom);
|
||||
g2.setTransform(transform);
|
||||
}
|
||||
|
||||
long start = System.currentTimeMillis();
|
||||
repaintImage(rect, g2);
|
||||
System.err.println("repaint: " + (System.currentTimeMillis() - start) + " ms");
|
||||
}
|
||||
|
||||
private void repaintImage(Rectangle rect, Graphics2D g2) {
|
||||
try {
|
||||
// Paint tiles of the image, to preserve memory
|
||||
int sliceSize = 200;
|
||||
|
||||
int slicesW = rect.width / sliceSize;
|
||||
int slicesH = rect.height / sliceSize;
|
||||
|
||||
for (int sliceY = 0; sliceY <= slicesH; sliceY++) {
|
||||
for (int sliceX = 0; sliceX <= slicesW; sliceX++) {
|
||||
int x = rect.x + sliceX * sliceSize;
|
||||
int y = rect.y + sliceY * sliceSize;
|
||||
|
||||
int w = sliceX == slicesW ? Math.min(sliceSize, rect.x + rect.width - x) : sliceSize;
|
||||
int h = sliceY == slicesH ? Math.min(sliceSize, rect.y + rect.height - y) : sliceSize;
|
||||
|
||||
if (w == 0 || h == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// System.err.printf("%04d, %04d, %04d, %04d%n", x, y, w, h);
|
||||
BufferedImage img = image.getSubimage(x, y, w, h);
|
||||
g2.drawImage(img, x, y, null);
|
||||
}
|
||||
}
|
||||
|
||||
// BufferedImage img = image.getSubimage(rect.x, rect.y, rect.width, rect.height);
|
||||
// g2.drawImage(img, rect.x, rect.y, null);
|
||||
}
|
||||
catch (NullPointerException e) {
|
||||
// e.printStackTrace();
|
||||
// Happens whenever apple.awt.OSXCachingSufraceManager runs out of memory
|
||||
// TODO: Figure out why repaint(x,y,w,h) doesn't work any more..?
|
||||
repaint(); // NOTE: Might cause a brief flash while the component is redrawn
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Dimension getPreferredSize() {
|
||||
return new Dimension((int) (image.getWidth() * zoom), (int) (image.getHeight() * zoom));
|
||||
}
|
||||
|
||||
public Dimension getPreferredScrollableViewportSize() {
|
||||
return getPreferredSize();
|
||||
}
|
||||
|
||||
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
|
||||
return 10;
|
||||
}
|
||||
|
||||
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
|
||||
switch (orientation) {
|
||||
case SwingConstants.HORIZONTAL:
|
||||
return visibleRect.width * 3 / 4;
|
||||
case SwingConstants.VERTICAL:
|
||||
default:
|
||||
return visibleRect.height * 3 / 4;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean getScrollableTracksViewportWidth() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean getScrollableTracksViewportHeight() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static class PaintDotsTask implements Runnable {
|
||||
private final BufferedImage image;
|
||||
private final int s;
|
||||
private final int wstep;
|
||||
private final Color[] colors;
|
||||
private final Random random;
|
||||
private final int last;
|
||||
private final int first;
|
||||
private final CountDownLatch latch;
|
||||
|
||||
public PaintDotsTask(BufferedImage image, int s, int wstep, Color[] colors, Random random, int first, int last, CountDownLatch latch) {
|
||||
this.image = image;
|
||||
this.s = s;
|
||||
this.wstep = wstep;
|
||||
this.colors = colors;
|
||||
this.random = random;
|
||||
this.last = last;
|
||||
this.first = first;
|
||||
this.latch = latch;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
try {
|
||||
paintDots0(image, s, wstep, colors, random, first, last);
|
||||
}
|
||||
finally {
|
||||
latch.countDown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class PaintBackgroundTask implements Runnable {
|
||||
private final int w;
|
||||
private final int h;
|
||||
private final DataBuffer buffer;
|
||||
private final boolean alpha;
|
||||
private final int first;
|
||||
private final int last;
|
||||
private final CountDownLatch latch;
|
||||
|
||||
public PaintBackgroundTask(int w, int h, DataBuffer buffer, boolean alpha, int first, int last, CountDownLatch latch) {
|
||||
this.w = w;
|
||||
this.h = h;
|
||||
this.buffer = buffer;
|
||||
this.alpha = alpha;
|
||||
this.first = first;
|
||||
this.last = last;
|
||||
this.latch = latch;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
try {
|
||||
paintBackground0(w, h, buffer, alpha, first, last);
|
||||
}
|
||||
finally {
|
||||
latch.countDown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class ConsoleProgressListener extends ProgressListenerBase {
|
||||
static final int COLUMNS = System.getenv("COLUMNS") != null ? Integer.parseInt(System.getenv("COLUMNS")) - 2 : 78;
|
||||
int left = COLUMNS;
|
||||
|
||||
@Override
|
||||
public void imageComplete(ImageReader source) {
|
||||
for (; left > 0; left--) {
|
||||
System.out.print(".");
|
||||
}
|
||||
System.out.println("]");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void imageProgress(ImageReader source, float percentageDone) {
|
||||
int progress = COLUMNS - Math.round(COLUMNS * percentageDone / 100f);
|
||||
if (progress < left) {
|
||||
for (; left > progress; left--) {
|
||||
System.out.print(".");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void imageStarted(ImageReader source, int imageIndex) {
|
||||
System.out.print("[");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
/*
|
||||
* Copyright (c) 2010, 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 com.twelvemonkeys.lang.Validate;
|
||||
|
||||
import java.awt.image.DataBuffer;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.*;
|
||||
import java.nio.channels.FileChannel;
|
||||
|
||||
/**
|
||||
* A {@code DataBuffer} implementation that is backed by a memory mapped file.
|
||||
* Memory will be allocated outside the normal JVM heap, allowing more efficient
|
||||
* memory usage for large buffers.
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @author last modified by $Author: haraldk$
|
||||
* @version $Id: MappedFileBuffer.java,v 1.0 Jun 12, 2010 4:56:51 PM haraldk Exp$
|
||||
*
|
||||
* @see java.nio.channels.FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)
|
||||
*/
|
||||
public abstract class MappedFileBuffer extends DataBuffer {
|
||||
private final Buffer buffer;
|
||||
|
||||
private MappedFileBuffer(final int type, final int size, final int numBanks) throws IOException {
|
||||
super(type, Validate.isTrue(size >= 0, size, "Integer overflow for size: %d"), Validate.isTrue(numBanks >= 0, numBanks, "Number of banks must be positive"));
|
||||
|
||||
int componentSize = DataBuffer.getDataTypeSize(type) / 8;
|
||||
|
||||
// Create temp file to get a file handle to use for memory mapping
|
||||
File tempFile = File.createTempFile(String.format("%s-", getClass().getSimpleName().toLowerCase()), ".tmp");
|
||||
|
||||
try {
|
||||
RandomAccessFile raf = new RandomAccessFile(tempFile, "rw");
|
||||
|
||||
long length = ((long) size) * componentSize * numBanks;
|
||||
|
||||
raf.setLength(length);
|
||||
FileChannel channel = raf.getChannel();
|
||||
|
||||
// Map entire file into memory, let OS virtual memory/paging do the heavy lifting
|
||||
MappedByteBuffer byteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, length);
|
||||
|
||||
switch (type) {
|
||||
case DataBuffer.TYPE_BYTE:
|
||||
buffer = byteBuffer;
|
||||
break;
|
||||
case DataBuffer.TYPE_USHORT:
|
||||
buffer = byteBuffer.asShortBuffer();
|
||||
break;
|
||||
case DataBuffer.TYPE_INT:
|
||||
buffer = byteBuffer.asIntBuffer();
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException("Unsupported data type: " + type);
|
||||
}
|
||||
|
||||
// According to the docs, we can safely close the channel and delete the file now
|
||||
channel.close();
|
||||
}
|
||||
finally {
|
||||
// NOTE: File can't be deleted right now on Windows, as the file is open. Let JVM clean up later
|
||||
if (!tempFile.delete()) {
|
||||
tempFile.deleteOnExit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("MappedFileBuffer: %s", buffer);
|
||||
}
|
||||
|
||||
// TODO: Is throws IOException a good idea?
|
||||
|
||||
public static DataBuffer create(final int type, final int size, final int numBanks) throws IOException {
|
||||
switch (type) {
|
||||
case DataBuffer.TYPE_BYTE:
|
||||
return new DataBufferByte(size, numBanks);
|
||||
case DataBuffer.TYPE_USHORT:
|
||||
return new DataBufferUShort(size, numBanks);
|
||||
case DataBuffer.TYPE_INT:
|
||||
return new DataBufferInt(size, numBanks);
|
||||
default:
|
||||
throw new IllegalArgumentException("Unsupported data type: " + type);
|
||||
}
|
||||
}
|
||||
|
||||
final static class DataBufferByte extends MappedFileBuffer {
|
||||
private final ByteBuffer buffer;
|
||||
|
||||
public DataBufferByte(int size, int numBanks) throws IOException {
|
||||
super(DataBuffer.TYPE_BYTE, size, numBanks);
|
||||
buffer = (ByteBuffer) super.buffer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getElem(int bank, int i) {
|
||||
return buffer.get(bank * size + i) & 0xff;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setElem(int bank, int i, int val) {
|
||||
buffer.put(bank * size + i, (byte) val);
|
||||
}
|
||||
}
|
||||
|
||||
final static class DataBufferUShort extends MappedFileBuffer {
|
||||
private final ShortBuffer buffer;
|
||||
|
||||
public DataBufferUShort(int size, int numBanks) throws IOException {
|
||||
super(DataBuffer.TYPE_USHORT, size, numBanks);
|
||||
buffer = (ShortBuffer) super.buffer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getElem(int bank, int i) {
|
||||
return buffer.get(bank * size + i) & 0xffff;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setElem(int bank, int i, int val) {
|
||||
buffer.put(bank * size + i, (short) val);
|
||||
}
|
||||
}
|
||||
|
||||
final static class DataBufferInt extends MappedFileBuffer {
|
||||
private final IntBuffer buffer;
|
||||
|
||||
public DataBufferInt(int size, int numBanks) throws IOException {
|
||||
super(DataBuffer.TYPE_INT, size, numBanks);
|
||||
buffer = (IntBuffer) super.buffer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getElem(int bank, int i) {
|
||||
return buffer.get(bank * size + i);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setElem(int bank, int i, int val) {
|
||||
buffer.put(bank * size + i, val);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Copyright (c) 2010, 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.ImageTypeSpecifier;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.awt.image.ColorModel;
|
||||
import java.awt.image.DataBuffer;
|
||||
import java.awt.image.SampleModel;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* A factory for creating {@link BufferedImage}s backed by memory mapped files.
|
||||
* The data buffers will be allocated outside the normal JVM heap, allowing more efficient
|
||||
* memory usage for large images.
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @author last modified by $Author: haraldk$
|
||||
* @version $Id: MappedImageFactory.java,v 1.0 May 26, 2010 5:07:01 PM haraldk Exp$
|
||||
*/
|
||||
public final class MappedImageFactory {
|
||||
|
||||
// TODO: Create a way to do ColorConvertOp (or other color space conversion) on these images.
|
||||
// - Current implementation of CCOp delegates to internal sun.awt classes that assumes java.awt.DataBufferByte for type byte buffers :-/
|
||||
|
||||
private MappedImageFactory() {}
|
||||
|
||||
public static BufferedImage createCompatibleMappedImage(int width, int height, int type) throws IOException {
|
||||
BufferedImage temp = new BufferedImage(1, 1, type);
|
||||
return createCompatibleMappedImage(width, height, temp.getSampleModel().createCompatibleSampleModel(width, height), temp.getColorModel());
|
||||
}
|
||||
|
||||
public static BufferedImage createCompatibleMappedImage(int width, int height, GraphicsConfiguration configuration, int transparency) throws IOException {
|
||||
// TODO: Should we also use the sample model?
|
||||
return createCompatibleMappedImage(width, height, configuration.getColorModel(transparency));
|
||||
}
|
||||
|
||||
public static BufferedImage createCompatibleMappedImage(int width, int height, ImageTypeSpecifier type) throws IOException {
|
||||
return createCompatibleMappedImage(width, height, type.getSampleModel(width, height), type.getColorModel());
|
||||
}
|
||||
|
||||
static BufferedImage createCompatibleMappedImage(int width, int height, ColorModel cm) throws IOException {
|
||||
return createCompatibleMappedImage(width, height, cm.createCompatibleSampleModel(width, height), cm);
|
||||
}
|
||||
|
||||
static BufferedImage createCompatibleMappedImage(int width, int height, SampleModel sm, ColorModel cm) throws IOException {
|
||||
DataBuffer buffer = MappedFileBuffer.create(sm.getTransferType(), width * height * sm.getNumDataElements(), 1);
|
||||
|
||||
return new BufferedImage(cm, new GenericWritableRaster(sm, buffer, new Point()), cm.isAlphaPremultiplied(), null);
|
||||
}
|
||||
}
|
||||
+163
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
/*
|
||||
* This software is copyrighted as noted below. It may be freely copied,
|
||||
* modified, and redistributed, provided that the copyright notice is
|
||||
* preserved on all copies.
|
||||
*
|
||||
* There is no warranty or other guarantee of fitness for this software,
|
||||
* it is provided solely "as is". Bug reports or fixes may be sent
|
||||
* to the author, who may or may not act on them as he desires.
|
||||
*
|
||||
* You may not include this software in a program or other software product
|
||||
* without supplying the source, or without informing the end-user that the
|
||||
* source is available for no extra charge.
|
||||
*
|
||||
* If you modify this software, you should include a notice giving the
|
||||
* name of the person performing the modification, the date of modification,
|
||||
* and the reason for such modification.
|
||||
*/
|
||||
/*
|
||||
* inv_cmap.c - Compute an inverse colormap.
|
||||
*
|
||||
* Author: Spencer W. Thomas
|
||||
* EECS Dept.
|
||||
* University of Michigan
|
||||
* Date: Thu Sep 20 1990
|
||||
* Copyright (c) 1990, University of Michigan
|
||||
*
|
||||
* $Id: inv_cmap.c,v 3.0.1.3 1992/04/30 14:07:28 spencer Exp $
|
||||
*/
|
||||
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
|
||||
|
||||
static int bcenter, gcenter, rcenter;
|
||||
static long gdist, rdist, cdist;
|
||||
static long cbinc, cginc, crinc;
|
||||
static unsigned long *gdp, *rdp, *cdp;
|
||||
static unsigned char *grgbp, *rrgbp, *crgbp;
|
||||
static gstride, rstride;
|
||||
static long x, xsqr, colormax;
|
||||
static int cindex;
|
||||
|
||||
#ifdef USE_PROTOTYPES
|
||||
static void maxfill( unsigned long *, long );
|
||||
static int redloop( void );
|
||||
static int greenloop( int );
|
||||
static int blueloop( int );
|
||||
#else
|
||||
static void maxfill();
|
||||
static int redloop();
|
||||
static int greenloop();
|
||||
static int blueloop();
|
||||
#endif
|
||||
|
||||
|
||||
/*****************************************************************
|
||||
* TAG( inv_cmap )
|
||||
*
|
||||
* Compute an inverse colormap efficiently.
|
||||
* Inputs:
|
||||
* colors: Number of colors in the forward colormap.
|
||||
* colormap: The forward colormap.
|
||||
* bits: Number of quantization bits. The inverse
|
||||
* colormap will have (2^bits)^3 entries.
|
||||
* dist_buf: An array of (2^bits)^3 long integers to be
|
||||
* used as scratch space.
|
||||
* Outputs:
|
||||
* rgbmap: The output inverse colormap. The entry
|
||||
* rgbmap[(r<<(2*bits)) + (g<<bits) + b]
|
||||
* is the colormap entry that is closest to the
|
||||
* (quantized) color (r,g,b).
|
||||
* Assumptions:
|
||||
* Quantization is performed by right shift (low order bits are
|
||||
* truncated). Thus, the distance to a quantized color is
|
||||
* actually measured to the color at the center of the cell
|
||||
* (i.e., to r+.5, g+.5, b+.5, if (r,g,b) is a quantized color).
|
||||
* Algorithm:
|
||||
* Uses a "distance buffer" algorithm:
|
||||
* The distance from each representative in the forward color map
|
||||
* to each point in the rgb space is computed. If it is less
|
||||
* than the distance currently stored in dist_buf, then the
|
||||
* corresponding entry in rgbmap is replaced with the current
|
||||
* representative (and the dist_buf entry is replaced with the
|
||||
* new distance).
|
||||
*
|
||||
* The distance computation uses an efficient incremental formulation.
|
||||
*
|
||||
* Distances are computed "outward" from each color. If the
|
||||
* colors are evenly distributed in color space, the expected
|
||||
* number of cells visited for color I is N^3/I.
|
||||
* Thus, the complexity of the algorithm is O(log(K) N^3),
|
||||
* where K = colors, and N = 2^bits.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Here's the idea: scan from the "center" of each cell "out"
|
||||
* until we hit the "edge" of the cell -- that is, the point
|
||||
* at which some other color is closer -- and stop. In 1-D,
|
||||
* this is simple:
|
||||
* for i := here to max do
|
||||
* if closer then buffer[i] = this color
|
||||
* else break
|
||||
* repeat above loop with i := here-1 to min by -1
|
||||
*
|
||||
* In 2-D, it's trickier, because along a "scan-line", the
|
||||
* region might start "after" the "center" point. A picture
|
||||
* might clarify:
|
||||
* | ...
|
||||
* | ... .
|
||||
* ... .
|
||||
* ... | .
|
||||
* . + .
|
||||
* . .
|
||||
* . .
|
||||
* .........
|
||||
*
|
||||
* The + marks the "center" of the above region. On the top 2
|
||||
* lines, the region "begins" to the right of the "center".
|
||||
*
|
||||
* Thus, we need a loop like this:
|
||||
* detect := false
|
||||
* for i := here to max do
|
||||
* if closer then
|
||||
* buffer[..., i] := this color
|
||||
* if !detect then
|
||||
* here = i
|
||||
* detect = true
|
||||
* else
|
||||
* if detect then
|
||||
* break
|
||||
*
|
||||
* Repeat the above loop with i := here-1 to min by -1. Note that
|
||||
* the "detect" value should not be reinitialized. If it was
|
||||
* "true", and center is not inside the cell, then none of the
|
||||
* cell lies to the left and this loop should exit
|
||||
* immediately.
|
||||
*
|
||||
* The outer loops are similar, except that the "closer" test
|
||||
* is replaced by a call to the "next in" loop; its "detect"
|
||||
* value serves as the test. (No assignment to the buffer is
|
||||
* done, either.)
|
||||
*
|
||||
* Each time an outer loop starts, the "here", "min", and
|
||||
* "max" values of the next inner loop should be
|
||||
* re-initialized to the center of the cell, 0, and cube size,
|
||||
* respectively. Otherwise, these values will carry over from
|
||||
* one "call" to the inner loop to the next. This tracks the
|
||||
* edges of the cell and minimizes the number of
|
||||
* "unproductive" comparisons that must be made.
|
||||
*
|
||||
* Finally, the inner-most loop can have the "if !detect"
|
||||
* optimized out of it by splitting it into two loops: one
|
||||
* that finds the first color value on the scan line that is
|
||||
* in this cell, and a second that fills the cell until
|
||||
* another one is closer:
|
||||
* if !detect then {needed for "down" loop}
|
||||
* for i := here to max do
|
||||
* if closer then
|
||||
* buffer[..., i] := this color
|
||||
* detect := true
|
||||
* break
|
||||
* for i := i+1 to max do
|
||||
* if closer then
|
||||
* buffer[..., i] := this color
|
||||
* else
|
||||
* break
|
||||
*
|
||||
* In this implementation, each level will require the
|
||||
* following variables. Variables labelled (l) are local to each
|
||||
* procedure. The ? should be replaced with r, g, or b:
|
||||
* cdist: The distance at the starting point.
|
||||
* ?center: The value of this component of the color
|
||||
* c?inc: The initial increment at the ?center position.
|
||||
* ?stride: The amount to add to the buffer
|
||||
* pointers (dp and rgbp) to get to the
|
||||
* "next row".
|
||||
* min(l): The "low edge" of the cell, init to 0
|
||||
* max(l): The "high edge" of the cell, init to
|
||||
* colormax-1
|
||||
* detect(l): True if this row has changed some
|
||||
* buffer entries.
|
||||
* i(l): The index for this row.
|
||||
* ?xx: The accumulated increment value.
|
||||
*
|
||||
* here(l): The starting index for this color. The
|
||||
* following variables are associated with here,
|
||||
* in the sense that they must be updated if here
|
||||
* is changed.
|
||||
* ?dist: The current distance for this level. The
|
||||
* value of dist from the previous level (g or r,
|
||||
* for level b or g) initializes dist on this
|
||||
* level. Thus gdist is associated with here(b)).
|
||||
* ?inc: The initial increment for the row.
|
||||
* ?dp: Pointer into the distance buffer. The value
|
||||
* from the previous level initializes this level.
|
||||
* ?rgbp: Pointer into the rgb buffer. The value
|
||||
* from the previous level initializes this level.
|
||||
*
|
||||
* The blue and green levels modify 'here-associated' variables (dp,
|
||||
* rgbp, dist) on the green and red levels, respectively, when here is
|
||||
* changed.
|
||||
*/
|
||||
|
||||
void
|
||||
inv_cmap( colors, colormap, bits, dist_buf, rgbmap )
|
||||
int colors, bits;
|
||||
unsigned char *colormap[3], *rgbmap;
|
||||
unsigned long *dist_buf;
|
||||
{
|
||||
int nbits = 8 - bits;
|
||||
|
||||
colormax = 1 << bits;
|
||||
x = 1 << nbits;
|
||||
xsqr = 1 << (2 * nbits);
|
||||
|
||||
/* Compute "strides" for accessing the arrays. */
|
||||
gstride = colormax;
|
||||
rstride = colormax * colormax;
|
||||
|
||||
maxfill( dist_buf, colormax );
|
||||
|
||||
for ( cindex = 0; cindex < colors; cindex++ )
|
||||
{
|
||||
/*
|
||||
* Distance formula is
|
||||
* (red - map[0])^2 + (green - map[1])^2 + (blue - map[2])^2
|
||||
*
|
||||
* Because of quantization, we will measure from the center of
|
||||
* each quantized "cube", so blue distance is
|
||||
* (blue + x/2 - map[2])^2,
|
||||
* where x = 2^(8 - bits).
|
||||
* The step size is x, so the blue increment is
|
||||
* 2*x*blue - 2*x*map[2] + 2*x^2
|
||||
*
|
||||
* Now, b in the code below is actually blue/x, so our
|
||||
* increment will be 2*(b*x^2 + x^2 - x*map[2]). For
|
||||
* efficiency, we will maintain this quantity in a separate variable
|
||||
* that will be updated incrementally by adding 2*x^2 each time.
|
||||
*/
|
||||
/* The initial position is the cell containing the colormap
|
||||
* entry. We get this by quantizing the colormap values.
|
||||
*/
|
||||
rcenter = colormap[0][cindex] >> nbits;
|
||||
gcenter = colormap[1][cindex] >> nbits;
|
||||
bcenter = colormap[2][cindex] >> nbits;
|
||||
|
||||
rdist = colormap[0][cindex] - (rcenter * x + x/2);
|
||||
gdist = colormap[1][cindex] - (gcenter * x + x/2);
|
||||
cdist = colormap[2][cindex] - (bcenter * x + x/2);
|
||||
cdist = rdist*rdist + gdist*gdist + cdist*cdist;
|
||||
|
||||
crinc = 2 * ((rcenter + 1) * xsqr - (colormap[0][cindex] * x));
|
||||
cginc = 2 * ((gcenter + 1) * xsqr - (colormap[1][cindex] * x));
|
||||
cbinc = 2 * ((bcenter + 1) * xsqr - (colormap[2][cindex] * x));
|
||||
|
||||
/* Array starting points. */
|
||||
cdp = dist_buf + rcenter * rstride + gcenter * gstride + bcenter;
|
||||
crgbp = rgbmap + rcenter * rstride + gcenter * gstride + bcenter;
|
||||
|
||||
(void)redloop();
|
||||
}
|
||||
}
|
||||
|
||||
/* redloop -- loop up and down from red center. */
|
||||
static int
|
||||
redloop()
|
||||
{
|
||||
int detect;
|
||||
int r;
|
||||
int first;
|
||||
long txsqr = xsqr + xsqr;
|
||||
static long rxx;
|
||||
|
||||
detect = 0;
|
||||
|
||||
/* Basic loop up. */
|
||||
for ( r = rcenter, rdist = cdist, rxx = crinc,
|
||||
rdp = cdp, rrgbp = crgbp, first = 1;
|
||||
r < colormax;
|
||||
r++, rdp += rstride, rrgbp += rstride,
|
||||
rdist += rxx, rxx += txsqr, first = 0 )
|
||||
{
|
||||
if ( greenloop( first ) )
|
||||
detect = 1;
|
||||
else if ( detect )
|
||||
break;
|
||||
}
|
||||
|
||||
/* Basic loop down. */
|
||||
for ( r = rcenter - 1, rxx = crinc - txsqr, rdist = cdist - rxx,
|
||||
rdp = cdp - rstride, rrgbp = crgbp - rstride, first = 1;
|
||||
r >= 0;
|
||||
r--, rdp -= rstride, rrgbp -= rstride,
|
||||
rxx -= txsqr, rdist -= rxx, first = 0 )
|
||||
{
|
||||
if ( greenloop( first ) )
|
||||
detect = 1;
|
||||
else if ( detect )
|
||||
break;
|
||||
}
|
||||
|
||||
return detect;
|
||||
}
|
||||
|
||||
/* greenloop -- loop up and down from green center. */
|
||||
static int
|
||||
greenloop( restart )
|
||||
int restart;
|
||||
{
|
||||
int detect;
|
||||
int g;
|
||||
int first;
|
||||
long txsqr = xsqr + xsqr;
|
||||
static int here, min, max;
|
||||
static long ginc, gxx, gcdist; /* "gc" variables maintain correct */
|
||||
static unsigned long *gcdp; /* values for bcenter position, */
|
||||
static unsigned char *gcrgbp; /* despite modifications by blueloop */
|
||||
/* to gdist, gdp, grgbp. */
|
||||
|
||||
if ( restart )
|
||||
{
|
||||
here = gcenter;
|
||||
min = 0;
|
||||
max = colormax - 1;
|
||||
ginc = cginc;
|
||||
}
|
||||
|
||||
detect = 0;
|
||||
|
||||
/* Basic loop up. */
|
||||
for ( g = here, gcdist = gdist = rdist, gxx = ginc,
|
||||
gcdp = gdp = rdp, gcrgbp = grgbp = rrgbp, first = 1;
|
||||
g <= max;
|
||||
g++, gdp += gstride, gcdp += gstride, grgbp += gstride, gcrgbp += gstride,
|
||||
gdist += gxx, gcdist += gxx, gxx += txsqr, first = 0 )
|
||||
{
|
||||
if ( blueloop( first ) )
|
||||
{
|
||||
if ( !detect )
|
||||
{
|
||||
/* Remember here and associated data! */
|
||||
if ( g > here )
|
||||
{
|
||||
here = g;
|
||||
rdp = gcdp;
|
||||
rrgbp = gcrgbp;
|
||||
rdist = gcdist;
|
||||
ginc = gxx;
|
||||
}
|
||||
detect = 1;
|
||||
}
|
||||
}
|
||||
else if ( detect )
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* Basic loop down. */
|
||||
for ( g = here - 1, gxx = ginc - txsqr, gcdist = gdist = rdist - gxx,
|
||||
gcdp = gdp = rdp - gstride, gcrgbp = grgbp = rrgbp - gstride,
|
||||
first = 1;
|
||||
g >= min;
|
||||
g--, gdp -= gstride, gcdp -= gstride, grgbp -= gstride, gcrgbp -= gstride,
|
||||
gxx -= txsqr, gdist -= gxx, gcdist -= gxx, first = 0 )
|
||||
{
|
||||
if ( blueloop( first ) )
|
||||
{
|
||||
if ( !detect )
|
||||
{
|
||||
/* Remember here! */
|
||||
here = g;
|
||||
rdp = gcdp;
|
||||
rrgbp = gcrgbp;
|
||||
rdist = gcdist;
|
||||
ginc = gxx;
|
||||
detect = 1;
|
||||
}
|
||||
}
|
||||
else if ( detect )
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return detect;
|
||||
}
|
||||
|
||||
/* blueloop -- loop up and down from blue center. */
|
||||
static int
|
||||
blueloop( restart )
|
||||
int restart;
|
||||
{
|
||||
int detect;
|
||||
register unsigned long *dp;
|
||||
register unsigned char *rgbp;
|
||||
register long bdist, bxx;
|
||||
register int b, i = cindex;
|
||||
register long txsqr = xsqr + xsqr;
|
||||
register int lim;
|
||||
static int here, min, max;
|
||||
static long binc;
|
||||
|
||||
if ( restart )
|
||||
{
|
||||
here = bcenter;
|
||||
min = 0;
|
||||
max = colormax - 1;
|
||||
binc = cbinc;
|
||||
}
|
||||
|
||||
detect = 0;
|
||||
|
||||
/* Basic loop up. */
|
||||
/* First loop just finds first applicable cell. */
|
||||
for ( b = here, bdist = gdist, bxx = binc, dp = gdp, rgbp = grgbp, lim = max;
|
||||
b <= lim;
|
||||
b++, dp++, rgbp++,
|
||||
bdist += bxx, bxx += txsqr )
|
||||
{
|
||||
if ( *dp > bdist )
|
||||
{
|
||||
/* Remember new 'here' and associated data! */
|
||||
if ( b > here )
|
||||
{
|
||||
here = b;
|
||||
gdp = dp;
|
||||
grgbp = rgbp;
|
||||
gdist = bdist;
|
||||
binc = bxx;
|
||||
}
|
||||
detect = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
/* Second loop fills in a run of closer cells. */
|
||||
for ( ;
|
||||
b <= lim;
|
||||
b++, dp++, rgbp++,
|
||||
bdist += bxx, bxx += txsqr )
|
||||
{
|
||||
if ( *dp > bdist )
|
||||
{
|
||||
*dp = bdist;
|
||||
*rgbp = i;
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* Basic loop down. */
|
||||
/* Do initializations here, since the 'find' loop might not get
|
||||
* executed.
|
||||
*/
|
||||
lim = min;
|
||||
b = here - 1;
|
||||
bxx = binc - txsqr;
|
||||
bdist = gdist - bxx;
|
||||
dp = gdp - 1;
|
||||
rgbp = grgbp - 1;
|
||||
/* The 'find' loop is executed only if we didn't already find
|
||||
* something.
|
||||
*/
|
||||
if ( !detect )
|
||||
for ( ;
|
||||
b >= lim;
|
||||
b--, dp--, rgbp--,
|
||||
bxx -= txsqr, bdist -= bxx )
|
||||
{
|
||||
if ( *dp > bdist )
|
||||
{
|
||||
/* Remember here! */
|
||||
/* No test for b against here necessary because b <
|
||||
* here by definition.
|
||||
*/
|
||||
here = b;
|
||||
gdp = dp;
|
||||
grgbp = rgbp;
|
||||
gdist = bdist;
|
||||
binc = bxx;
|
||||
detect = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
/* The 'update' loop. */
|
||||
for ( ;
|
||||
b >= lim;
|
||||
b--, dp--, rgbp--,
|
||||
bxx -= txsqr, bdist -= bxx )
|
||||
{
|
||||
if ( *dp > bdist )
|
||||
{
|
||||
*dp = bdist;
|
||||
*rgbp = i;
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* If we saw something, update the edge trackers. */
|
||||
|
||||
return detect;
|
||||
}
|
||||
|
||||
static void
|
||||
maxfill( buffer, side )
|
||||
unsigned long *buffer;
|
||||
long side;
|
||||
{
|
||||
register unsigned long maxv = ~0L;
|
||||
register long i;
|
||||
register unsigned long *bp;
|
||||
|
||||
for ( i = side * side * side, bp = buffer;
|
||||
i > 0;
|
||||
i--, bp++ )
|
||||
*bp = maxv;
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright (c) 2009, 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;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.channels.Channels;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.FileLock;
|
||||
|
||||
/**
|
||||
* FileLockingTest
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @author last modified by $Author: haraldk$
|
||||
* @version $Id: FileLockingTest.java,v 1.0 May 12, 2009 7:15:38 PM haraldk Exp$
|
||||
*/
|
||||
public class FileLockingTest {
|
||||
public static void main(final String[] pArgs) throws IOException {
|
||||
FileChannel channel = new RandomAccessFile(pArgs[0], "rw").getChannel();
|
||||
FileLock lock = channel.tryLock(0, Long.MAX_VALUE, pArgs.length <= 1 || !"false".equalsIgnoreCase(pArgs[1])); // Shared lock for entire file
|
||||
|
||||
System.out.println("lock: " + lock);
|
||||
|
||||
if (lock != null) {
|
||||
System.in.read();
|
||||
|
||||
InputStream stream = Channels.newInputStream(channel);
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
System.out.println(line);
|
||||
}
|
||||
}
|
||||
else {
|
||||
System.out.println("Already locked");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* Copyright (c) 2009, 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;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* Allows monitoring a file on the file system.
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @author last modified by $Author: haraldk$
|
||||
* @version $Id: FileMonitor.java,v 1.0 May 12, 2009 6:58:55 PM haraldk Exp$
|
||||
*/
|
||||
public class FileMonitor {
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Listens for changes to a file.
|
||||
*
|
||||
*/
|
||||
public interface FileChangeListener {
|
||||
|
||||
public void fileCreated(File pFile) throws Exception; // TODO: Is this a good thing?
|
||||
|
||||
public void fileUpdated(File pFile) throws Exception;
|
||||
|
||||
public void fileDeleted(File pFile) throws Exception;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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 deflater;
|
||||
private final byte[] buffer = 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");
|
||||
}
|
||||
|
||||
deflater = pDeflater;
|
||||
}
|
||||
|
||||
public void encode(final OutputStream pStream, final byte[] pBuffer, final int pOffset, final int pLength)
|
||||
throws IOException
|
||||
{
|
||||
System.out.println("DeflateEncoder.encode");
|
||||
deflater.setInput(pBuffer, pOffset, pLength);
|
||||
flushInputToStream(pStream);
|
||||
}
|
||||
|
||||
private void flushInputToStream(final OutputStream pStream) throws IOException {
|
||||
System.out.println("DeflateEncoder.flushInputToStream");
|
||||
|
||||
if (deflater.needsInput()) {
|
||||
System.out.println("Foo");
|
||||
}
|
||||
|
||||
while (!deflater.needsInput()) {
|
||||
int deflated = deflater.deflate(buffer, 0, buffer.length);
|
||||
pStream.write(buffer, 0, deflated);
|
||||
System.out.println("flushed " + deflated);
|
||||
}
|
||||
}
|
||||
|
||||
// public void flush() {
|
||||
// deflater.finish();
|
||||
// }
|
||||
}
|
||||
@@ -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 inflater;
|
||||
|
||||
private final byte[] buffer;
|
||||
|
||||
/**
|
||||
* 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");
|
||||
}
|
||||
|
||||
inflater = pInflater;
|
||||
buffer = new byte[1024];
|
||||
}
|
||||
|
||||
public int decode(final InputStream pStream, final byte[] pBuffer) throws IOException {
|
||||
try {
|
||||
int decoded;
|
||||
|
||||
while ((decoded = inflater.inflate(pBuffer, 0, pBuffer.length)) == 0) {
|
||||
if (inflater.finished() || inflater.needsDictionary()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (inflater.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(buffer, 0, buffer.length);
|
||||
|
||||
if (available == -1) {
|
||||
throw new EOFException("Unexpected end of ZLIB stream");
|
||||
}
|
||||
|
||||
inflater.setInput(buffer, 0, available);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
/*
|
||||
* 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 java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* “If it walks like a duck, looks like a duck, quacks like a duck, it must be…”.
|
||||
* <p/>
|
||||
* Based on an idea found at
|
||||
* <a href="http://www.coconut-palm-software.com/the_visual_editor/?p=25">The Visual Editor</a>
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-sandbox/src/main/java/com/twelvemonkeys/lang/DuckType.java#1 $
|
||||
*
|
||||
* @see java.lang.reflect.Proxy
|
||||
*/
|
||||
public final class DuckType {
|
||||
/*
|
||||
EXAMPLE:
|
||||
public ImageMgr(Object receiver, Image image) {
|
||||
if (!DuckType.instanceOf(IImageHolder.class, receiver)) {
|
||||
throw new ClassCastException("Cannot implement IImageHolder");
|
||||
}
|
||||
|
||||
this.image = image;
|
||||
|
||||
IImageHolder imageHolder = (IImageHolder) DuckType.implement(IImageHolder.class, receiver);
|
||||
imageHolder.setImage(image);
|
||||
imageHolder.addDisposeListener(this);
|
||||
}
|
||||
*/
|
||||
|
||||
// TODO: Implement some weak caching of proxy classes and instances
|
||||
// TODO: Make the proxy classes serializable...
|
||||
|
||||
private DuckType() {}
|
||||
|
||||
public static boolean instanceOf(Class pInterface, Object pObject) {
|
||||
return instanceOf(new Class[] {pInterface}, new Object[] {pObject});
|
||||
}
|
||||
|
||||
public static boolean instanceOf(Class[] pInterfaces, Object pObject) {
|
||||
return instanceOf(pInterfaces, new Object[] {pObject});
|
||||
}
|
||||
|
||||
public static boolean instanceOf(final Class[] pInterfaces, final Object[] pObjects) {
|
||||
// Get all methods of all Class in pInterfaces, and see if pObjects has
|
||||
// matching implementations
|
||||
|
||||
// TODO: Possible optimization: If any of the interfaces are implemented
|
||||
// by one of the objects' classes, we don't need to find every method...
|
||||
|
||||
for (int i = 0; i < pInterfaces.length; i++) {
|
||||
Class interfce = pInterfaces[i];
|
||||
|
||||
Method[] methods = interfce.getMethods();
|
||||
|
||||
for (int j = 0; j < methods.length; j++) {
|
||||
Method method = methods[j];
|
||||
|
||||
//if (findMethodImplementation(method, getClasses(pObjects)) < 0) {
|
||||
//if (findMethodImplementation(method, getClasses(pObjects)) == null) {
|
||||
if (findMethodImplementation(method, pObjects) == null) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// TODO: Might be moved to ReflectUtil
|
||||
private static Class[] getClasses(final Object[] pObjects) {
|
||||
Class[] classes = new Class[pObjects.length];
|
||||
|
||||
for (int i = 0; i < pObjects.length; i++) {
|
||||
classes[i] = pObjects[i].getClass();
|
||||
}
|
||||
|
||||
return classes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches for a class that has a method maching the given signature.
|
||||
* Returns the index of the class in the {@code pClasses} array that has a
|
||||
* matching method.
|
||||
* If there is more than one class that has a matching method the first
|
||||
* index will be returned.
|
||||
* If there is no match in any of the classes, {@code -1} is returned.
|
||||
*
|
||||
* @param pMethod
|
||||
* @param pObjects
|
||||
*
|
||||
* @return the first index of the object in the {@code pObjects} array that
|
||||
* has a matching method, or {@code -1} if none was found.
|
||||
*/
|
||||
// TODO: Might be moved to ReflectUtil
|
||||
//static int findMethodImplementation(final Method pMethod, final Class[] pClasses) {
|
||||
static MethodProxy findMethodImplementation(final Method pMethod, final Object[] pObjects) {
|
||||
// TODO: Optimization: Each getParameterTypes() invokation creates a
|
||||
// new clone of the array. If we do it once and store the refs, that
|
||||
// would be a good idea
|
||||
|
||||
// Optimization, don't test class more than once
|
||||
Set tested = new HashSet(pObjects.length);
|
||||
|
||||
for (int i = 0; i < pObjects.length; i++) {
|
||||
Class cls = pObjects[i].getClass();
|
||||
|
||||
if (tested.contains(cls)) {
|
||||
continue;
|
||||
}
|
||||
else {
|
||||
tested.add(cls);
|
||||
}
|
||||
|
||||
try {
|
||||
// NOTE: This test might be too restrictive
|
||||
// We could actually go ahead with
|
||||
// supertype parameters or subtype return types...
|
||||
// However, we should only do that after we have tried all
|
||||
// classes for direct mathces.
|
||||
Method method = cls.getMethod(pMethod.getName(),
|
||||
pMethod.getParameterTypes());
|
||||
|
||||
if (matches(pMethod, method)) {
|
||||
//return i;
|
||||
// TODO: This is a waste of time if we are only testing if there's a method here...
|
||||
return new MethodProxy(method, pObjects[i]);
|
||||
}
|
||||
}
|
||||
catch (NoSuchMethodException e) {
|
||||
// Ingore
|
||||
}
|
||||
}
|
||||
|
||||
if (hasSuperTypes(pMethod.getParameterTypes())) {
|
||||
SortedSet uniqueMethods = new TreeSet();
|
||||
for (int i = 0; i < pObjects.length; i++) {
|
||||
Class cls = pObjects[i].getClass();
|
||||
|
||||
Method[] methods = cls.getMethods();
|
||||
|
||||
for (int j = 0; j < methods.length; j++) {
|
||||
Method method = methods[j];
|
||||
|
||||
// Now, for each method
|
||||
// 1 test if the name matches
|
||||
// 2 test if the parameter types match for superclass
|
||||
// 3 Test return types for assignability?
|
||||
if (pMethod.getName().equals(method.getName())
|
||||
&& isAssignableFrom(method.getParameterTypes(), pMethod.getParameterTypes())
|
||||
&& pMethod.getReturnType().isAssignableFrom(method.getReturnType())) {
|
||||
// 4 TODO: How to find the most specific match?!
|
||||
//return new MethodProxy(method, pObjects[i]);
|
||||
uniqueMethods.add(new MethodProxy(method, pObjects[i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (uniqueMethods.size() == 1) {
|
||||
return (MethodProxy) uniqueMethods.first();
|
||||
}
|
||||
else {
|
||||
// TODO: We need to figure out what method is the best match..
|
||||
}
|
||||
}
|
||||
|
||||
//return -1;
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean isAssignableFrom(Class[] pTypes, Class[] pSubTypes) {
|
||||
if (pTypes.length != pSubTypes.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < pTypes.length; i++) {
|
||||
if (!pTypes[i].isAssignableFrom(pSubTypes[i])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean hasSuperTypes(Class[] pParameterTypes) {
|
||||
for (int i = 0; i < pParameterTypes.length; i++) {
|
||||
Class type = pParameterTypes[i];
|
||||
|
||||
if (type != Object.class
|
||||
&& (type.isInterface() || type.getSuperclass() != null)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests two {@code Method}s for match.
|
||||
* That is, they have same name and equal parameters.
|
||||
*
|
||||
* @param pLeft
|
||||
* @param pRight
|
||||
*
|
||||
* @return
|
||||
*
|
||||
* @see Method#equals(Object)
|
||||
*/
|
||||
private static boolean matches(Method pLeft, Method pRight) {
|
||||
if (pLeft == pRight) {
|
||||
return true;
|
||||
}
|
||||
else if (pLeft.getName().equals(pRight.getName())
|
||||
&& pLeft.getReturnType().isAssignableFrom(pRight.getReturnType())) {
|
||||
|
||||
// Avoid unnecessary cloning
|
||||
Class[] params1 = pLeft.getParameterTypes();
|
||||
Class[] params2 = pRight.getParameterTypes();
|
||||
if (params1.length == params2.length) {
|
||||
for (int i = 0; i < params1.length; i++) {
|
||||
if (params1[i] != params2[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static Object implement(Class pInterface, Object pObject) throws NoMatchingMethodException {
|
||||
return implement(new Class[] {pInterface}, new Object[] {pObject}, false);
|
||||
}
|
||||
|
||||
public static Object implement(Class[] pInterfaces, Object pObject) throws NoMatchingMethodException {
|
||||
return implement(pInterfaces, new Object[] {pObject}, false);
|
||||
}
|
||||
|
||||
// TODO: What about the interfaces pObjects allready implements?
|
||||
// TODO: Use first object as "identity"? Allow user to supply "indentity"
|
||||
// that is not exposed as part of the implemented interfaces?
|
||||
public static Object implement(final Class[] pInterfaces, final Object[] pObjects) throws NoMatchingMethodException {
|
||||
return implement(pInterfaces, pObjects, false);
|
||||
}
|
||||
|
||||
public static Object implement(final Class[] pInterfaces, final Object[] pObjects, boolean pStubAbstract) throws NoMatchingMethodException {
|
||||
Map delegates = new HashMap(pObjects.length * 10);
|
||||
|
||||
for (int i = 0; i < pInterfaces.length; i++) {
|
||||
Class interfce = pInterfaces[i];
|
||||
|
||||
Method[] methods = interfce.getMethods();
|
||||
|
||||
for (int j = 0; j < methods.length; j++) {
|
||||
Method method = methods[j];
|
||||
|
||||
//int idx = findMethodImplementation(method, getClasses(pObjects));
|
||||
//Method impl = findMethodImplementation(method, getClasses(pObjects));
|
||||
MethodProxy impl = findMethodImplementation(method, pObjects);
|
||||
//if (idx < 0) {
|
||||
if (impl == null) {
|
||||
// TODO: Maybe optionally create stubs that fails when invoked?!
|
||||
if (pStubAbstract) {
|
||||
impl = MethodProxy.createAbstract(method);
|
||||
}
|
||||
else {
|
||||
throw new NoMatchingMethodException(interfce.getName() + "."
|
||||
+ method.getName()
|
||||
+ parameterTypesToString(method.getParameterTypes()));
|
||||
}
|
||||
}
|
||||
|
||||
if (!delegates.containsKey(method)) {
|
||||
// TODO: Must find the correct object...
|
||||
//delegates.put(method, new MethodProxy(method, pObjects[idx]));
|
||||
delegates.put(method, impl);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: It's probably not good enough to use the current context class loader
|
||||
// TODO: Either let user specify classloader directly
|
||||
// TODO: ...or use one of the classloaders from pInterfaces or pObjects
|
||||
return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
|
||||
pInterfaces, new DelegationHandler(delegates));
|
||||
}
|
||||
|
||||
private static String parameterTypesToString(Class[] pTypes) {
|
||||
StringBuilder buf = new StringBuilder();
|
||||
buf.append("(");
|
||||
if (pTypes != null) {
|
||||
for (int i = 0; i < pTypes.length; i++) {
|
||||
if (i > 0) {
|
||||
buf.append(", ");
|
||||
}
|
||||
Class c = pTypes[i];
|
||||
buf.append((c == null) ? "null" : c.getName());
|
||||
}
|
||||
}
|
||||
buf.append(")");
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
static class MethodProxy {
|
||||
private final Method mMethod;
|
||||
private final Object mDelegate;
|
||||
|
||||
private final static Object ABSTRACT_METHOD_DELEGATE = new Object() {
|
||||
};
|
||||
|
||||
public static MethodProxy createAbstract(Method pMethod) {
|
||||
return new MethodProxy(pMethod, ABSTRACT_METHOD_DELEGATE) {
|
||||
public Object invoke(Object[] pArguments) throws Throwable {
|
||||
throw abstractMehthodError();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public MethodProxy(Method pMethod, Object pDelegate) {
|
||||
if (pMethod == null) {
|
||||
throw new IllegalArgumentException("method == null");
|
||||
}
|
||||
if (pDelegate == null) {
|
||||
throw new IllegalArgumentException("delegate == null");
|
||||
}
|
||||
|
||||
mMethod = pMethod;
|
||||
mDelegate = pDelegate;
|
||||
}
|
||||
|
||||
public Object invoke(Object[] pArguments) throws Throwable {
|
||||
try {
|
||||
return mMethod.invoke(mDelegate, pArguments);
|
||||
}
|
||||
catch (IllegalAccessException e) {
|
||||
throw new Error(e); // This is an error in the impl
|
||||
}
|
||||
catch (InvocationTargetException e) {
|
||||
throw e.getCause();
|
||||
}
|
||||
}
|
||||
|
||||
Error abstractMehthodError() {
|
||||
return new AbstractMethodError(mMethod.toString());
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return mMethod.hashCode() ^ mDelegate.hashCode();
|
||||
}
|
||||
|
||||
public boolean equals(Object pOther) {
|
||||
if (pOther == this) {
|
||||
return true;
|
||||
}
|
||||
if (pOther instanceof MethodProxy) {
|
||||
MethodProxy other = (MethodProxy) pOther;
|
||||
return mMethod.equals(other.mMethod) && mDelegate.equals(other.mDelegate);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return mMethod.toString() + mDelegate.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static class NoMatchingMethodException extends IllegalArgumentException {
|
||||
public NoMatchingMethodException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public NoMatchingMethodException(String s) {
|
||||
super(s);
|
||||
}
|
||||
|
||||
public NoMatchingMethodException(Exception e) {
|
||||
super(e.getMessage());
|
||||
initCause(e);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Must handle identity...
|
||||
// TODO: equals/hashCode
|
||||
// TODO: Allow clients to pass in Identity subclasses?
|
||||
private static class DelegationHandler implements InvocationHandler {
|
||||
private final Map mDelegates;
|
||||
|
||||
public DelegationHandler(Map pDelegates) {
|
||||
mDelegates = pDelegates;
|
||||
}
|
||||
|
||||
public final Object invoke(Object pProxy, Method pMethod, Object[] pArguments)
|
||||
throws Throwable
|
||||
{
|
||||
if (pMethod.getDeclaringClass() == Object.class) {
|
||||
// Intercept equals/hashCode/toString
|
||||
String name = pMethod.getName();
|
||||
if (name.equals("equals")) {
|
||||
return proxyEquals(pProxy, pArguments[0]);
|
||||
}
|
||||
else if (name.equals("hashCode")) {
|
||||
return proxyHashCode(pProxy);
|
||||
}
|
||||
else if (name.equals("toString")) {
|
||||
return proxyToString(pProxy);
|
||||
}
|
||||
|
||||
// Other methods are handled by their default Object
|
||||
// implementations
|
||||
return pMethod.invoke(this, pArguments);
|
||||
}
|
||||
|
||||
MethodProxy mp = (MethodProxy) mDelegates.get(pMethod);
|
||||
|
||||
return mp.invoke(pArguments);
|
||||
}
|
||||
|
||||
protected Integer proxyHashCode(Object pProxy) {
|
||||
//return new Integer(System.identityHashCode(pProxy));
|
||||
return new Integer(mDelegates.hashCode());
|
||||
}
|
||||
|
||||
protected Boolean proxyEquals(Object pProxy, Object pOther) {
|
||||
return pProxy == pOther ||
|
||||
(Proxy.isProxyClass(pOther.getClass())
|
||||
&& Proxy.getInvocationHandler(pOther) instanceof DelegationHandler
|
||||
&& ((DelegationHandler) Proxy.getInvocationHandler(pOther)).mDelegates.equals(mDelegates))
|
||||
? Boolean.TRUE : Boolean.FALSE;
|
||||
}
|
||||
|
||||
protected String proxyToString(Object pProxy) {
|
||||
return pProxy.getClass().getName() + '@' +
|
||||
Integer.toHexString(pProxy.hashCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package com.twelvemonkeys.lang;
|
||||
|
||||
import java.lang.reflect.UndeclaredThrowableException;
|
||||
|
||||
import static com.twelvemonkeys.lang.Validate.notNull;
|
||||
|
||||
/**
|
||||
* ExceptionUtil
|
||||
*
|
||||
* @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/lang/ExceptionUtil.java#2 $
|
||||
*/
|
||||
public final class ExceptionUtil {
|
||||
|
||||
/**
|
||||
* Re-throws an exception, either as-is if the exception was already unchecked, otherwise wrapped in
|
||||
* a {@link RuntimeException} subtype.
|
||||
* "Expected" exception types are wrapped in {@link RuntimeException}s directly, while
|
||||
* "unexpected" exception types are wrapped in {@link java.lang.reflect.UndeclaredThrowableException}s.
|
||||
*
|
||||
* @param pThrowable the exception to launder
|
||||
* @param pExpectedTypes the types of exception the code is expected to throw
|
||||
*/
|
||||
/*public*/ static void launder(final Throwable pThrowable, Class<? extends Throwable>... pExpectedTypes) {
|
||||
if (pThrowable instanceof Error) {
|
||||
throw (Error) pThrowable;
|
||||
}
|
||||
if (pThrowable instanceof RuntimeException) {
|
||||
throw (RuntimeException) pThrowable;
|
||||
}
|
||||
|
||||
for (Class<? extends Throwable> expectedType : pExpectedTypes) {
|
||||
if (expectedType.isInstance(pThrowable)) {
|
||||
throw new RuntimeException(pThrowable);
|
||||
}
|
||||
}
|
||||
|
||||
throw new UndeclaredThrowableException(pThrowable);
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "UnusedDeclaration"})
|
||||
static <T extends Throwable> void throwAs(final Class<T> pType, final Throwable pThrowable) throws T {
|
||||
throw (T) pThrowable;
|
||||
}
|
||||
|
||||
public static void throwUnchecked(final Throwable pThrowable) {
|
||||
throwAs(RuntimeException.class, pThrowable);
|
||||
}
|
||||
|
||||
/*@SafeVarargs*/
|
||||
@SuppressWarnings({"unchecked", "varargs"})
|
||||
/*public*/ static void handle(final Throwable pThrowable, final ThrowableHandler<? extends Throwable>... pHandlers) {
|
||||
handleImpl(pThrowable, (ThrowableHandler<Throwable>[]) pHandlers);
|
||||
}
|
||||
|
||||
private static void handleImpl(final Throwable pThrowable, final ThrowableHandler<Throwable>... pHandlers) {
|
||||
// TODO: Sort more specific throwable handlers before less specific?
|
||||
for (ThrowableHandler<Throwable> handler : pHandlers) {
|
||||
if (handler.handles(pThrowable)) {
|
||||
handler.handle(pThrowable);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Not handled, re-throw
|
||||
throwUnchecked(pThrowable);
|
||||
}
|
||||
|
||||
public static abstract class ThrowableHandler<T extends Throwable> {
|
||||
private final Class<? extends T>[] throwables;
|
||||
|
||||
protected ThrowableHandler(final Class<? extends T>... pThrowables) {
|
||||
throwables = notNull(pThrowables).clone();
|
||||
}
|
||||
|
||||
final public boolean handles(final Throwable pThrowable) {
|
||||
for (Class<? extends T> throwable : throwables) {
|
||||
if (throwable.isAssignableFrom(pThrowable.getClass())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public abstract void handle(T pThrowable);
|
||||
}
|
||||
}
|
||||
Executable
+55
@@ -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);
|
||||
}
|
||||
}
|
||||
+401
@@ -0,0 +1,401 @@
|
||||
/*
|
||||
* 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.Collections;
|
||||
import java.util.Iterator;
|
||||
|
||||
/**
|
||||
* 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(Collections.singletonList(NativeResourceSPI.class).iterator());
|
||||
registerApplicationClasspathSPIs();
|
||||
}
|
||||
|
||||
Iterator<NativeResourceSPI> providers(final String nativeResource) {
|
||||
return new FilterIterator<NativeResourceSPI>(
|
||||
providers(NativeResourceSPI.class),
|
||||
new NameFilter(nativeResource)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private static class NameFilter implements FilterIterator.Filter<NativeResourceSPI> {
|
||||
private final String name;
|
||||
|
||||
NameFilter(String pName) {
|
||||
if (pName == null) {
|
||||
throw new IllegalArgumentException("name == null");
|
||||
}
|
||||
name = pName;
|
||||
}
|
||||
public boolean accept(NativeResourceSPI pElement) {
|
||||
return name.equals(pElement.getResourceName());
|
||||
}
|
||||
}
|
||||
}
|
||||
+99
@@ -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);
|
||||
}
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
/*
|
||||
* 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.sql;
|
||||
|
||||
import com.twelvemonkeys.lang.SystemUtil;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* A class that holds a JDBC Connection. The class can be configured by a
|
||||
* properties file. However, the approach is rather lame, and only lets you
|
||||
* configure one connection...
|
||||
* <P/>
|
||||
* Tested with jConnect (Sybase), I-net Sprinta2000 (MS SQL) and Oracle.
|
||||
* <P/>
|
||||
* @todo be able to register more drivers, trough properties and runtime
|
||||
* @todo be able to register more connections, trough properties and runtime
|
||||
* <P/>
|
||||
* <STRONG>Example properties file</STRONG></BR>
|
||||
* # filename: com.twelvemonkeys.sql.DatabaseConnection.properties
|
||||
* driver=com.inet.tds.TdsDriver
|
||||
* url=jdbc:inetdae7:127.0.0.1:1433?database\=mydb
|
||||
* user=scott
|
||||
* password=tiger
|
||||
* # What do you expect, really?
|
||||
* logDebug=true
|
||||
*
|
||||
* @author Philippe Béal (phbe@iconmedialab.no)
|
||||
* @author Harald Kuhr (haraldk@iconmedialab.no)
|
||||
* @author last modified by $Author: haku $
|
||||
*
|
||||
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-sandbox/src/main/java/com/twelvemonkeys/sql/DatabaseConnection.java#1 $
|
||||
*
|
||||
* @todo Use org.apache.commons.logging instead of proprietary logging.
|
||||
*
|
||||
*/
|
||||
|
||||
public class DatabaseConnection {
|
||||
|
||||
// Default driver
|
||||
public final static String DEFAULT_DRIVER = "NO_DRIVER";
|
||||
// Default URL
|
||||
public final static String DEFAULT_URL = "NO_URL";
|
||||
|
||||
protected static String mDriver = null;
|
||||
protected static String mUrl = null;
|
||||
|
||||
// Default debug is true
|
||||
// private static boolean debug = true;
|
||||
|
||||
protected static Properties mConfig = null;
|
||||
//protected static Log mLog = null;
|
||||
protected static Log mLog = null;
|
||||
|
||||
protected static boolean mInitialized = false;
|
||||
|
||||
// Must be like this...
|
||||
// http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html :-)
|
||||
private static DatabaseConnection sInstance = new DatabaseConnection();
|
||||
|
||||
/**
|
||||
* Creates the DatabaseConnection.
|
||||
*/
|
||||
|
||||
private DatabaseConnection() {
|
||||
init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the single DatabaseConnection instance.
|
||||
*/
|
||||
|
||||
protected static DatabaseConnection getInstance() {
|
||||
/*
|
||||
if (sInstance == null) {
|
||||
sInstance = new DatabaseConnection();
|
||||
sInstance.init();
|
||||
}
|
||||
*/
|
||||
return sInstance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the DatabaseConnection, called from the constructor.
|
||||
*
|
||||
* @exception IllegalStateException if an attempt to call init() is made
|
||||
* after the instance is allready initialized.
|
||||
*/
|
||||
|
||||
protected synchronized void init() {
|
||||
// Make sure init is executed only once!
|
||||
if (mInitialized) {
|
||||
throw new IllegalStateException("init() may only be called once!");
|
||||
}
|
||||
|
||||
mInitialized = true;
|
||||
|
||||
try {
|
||||
mConfig = SystemUtil.loadProperties(DatabaseConnection.class);
|
||||
}
|
||||
catch (FileNotFoundException fnf) {
|
||||
// Ignore
|
||||
}
|
||||
catch (IOException ioe) {
|
||||
//LogFactory.getLog(getClass()).error("Caught IOException: ", ioe);
|
||||
new Log(this).logError(ioe);
|
||||
//ioe.printStackTrace();
|
||||
}
|
||||
finally {
|
||||
if (mConfig == null) {
|
||||
mConfig = new Properties();
|
||||
}
|
||||
}
|
||||
|
||||
mLog = new Log(this, mConfig);
|
||||
//mLog = LogFactory.getLog(getClass());
|
||||
// debug = new Boolean(config.getProperty("debug", "true")).booleanValue();
|
||||
// config.list(System.out);
|
||||
|
||||
mDriver = mConfig.getProperty("driver", DEFAULT_DRIVER);
|
||||
mUrl = mConfig.getProperty("url", DEFAULT_URL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the default JDBC Connection. The connection is configured through
|
||||
* the properties file.
|
||||
*
|
||||
* @return the default jdbc Connection
|
||||
*/
|
||||
|
||||
public static Connection getConnection() {
|
||||
return getConnection(null, null, getInstance().mUrl);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a JDBC Connection with the given parameters. The connection is
|
||||
* configured through the properties file.
|
||||
*
|
||||
* @param pUser the database user name
|
||||
* @param pPassword the password of the database user
|
||||
* @param pURL the url to connect to
|
||||
*
|
||||
* @return a jdbc Connection
|
||||
*/
|
||||
|
||||
public static Connection getConnection(String pUser,
|
||||
String pPassword,
|
||||
String pURL) {
|
||||
return getInstance().getConnectionInstance(pUser, pPassword, pURL);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a JDBC Connection with the given parameters. The connection is
|
||||
* configured through the properties file.
|
||||
*
|
||||
* @param pUser the database user name
|
||||
* @param pPassword the password of the database user
|
||||
* @param pURL the url to connect to
|
||||
*
|
||||
* @return a jdbc Connection
|
||||
*/
|
||||
|
||||
protected Connection getConnectionInstance(String pUser,
|
||||
String pPassword,
|
||||
String pURL) {
|
||||
Properties props = (Properties) mConfig.clone();
|
||||
|
||||
if (pUser != null) {
|
||||
props.put("user", pUser);
|
||||
}
|
||||
if (pPassword != null) {
|
||||
props.put("password", pPassword);
|
||||
}
|
||||
|
||||
// props.list(System.out);
|
||||
|
||||
try {
|
||||
// Load & register the JDBC Driver
|
||||
if (!DEFAULT_DRIVER.equals(mDriver)) {
|
||||
Class.forName(mDriver).newInstance();
|
||||
}
|
||||
|
||||
Connection conn = DriverManager.getConnection(pURL, props);
|
||||
|
||||
if (mLog.getLogDebug()) {
|
||||
//if (mLog.isDebugEnabled()) {
|
||||
DatabaseMetaData dma = conn.getMetaData();
|
||||
mLog.logDebug("Connected to " + dma.getURL());
|
||||
mLog.logDebug("Driver " + dma.getDriverName());
|
||||
mLog.logDebug("Version " + dma.getDriverVersion());
|
||||
|
||||
//mLog.debug("Connected to " + dma.getURL());
|
||||
//mLog.debug("Driver " + dma.getDriverName());
|
||||
//mLog.debug("Version " + dma.getDriverVersion());
|
||||
}
|
||||
|
||||
return conn;
|
||||
}
|
||||
catch (Exception e) {
|
||||
mLog.logError(e.getMessage());
|
||||
|
||||
// Get chained excpetions
|
||||
if (e instanceof SQLException) {
|
||||
SQLException sqle = (SQLException) e;
|
||||
while ((sqle = sqle.getNextException()) != null) {
|
||||
mLog.logWarning(sqle);
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
/*
|
||||
* 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.sql;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* DatabaseProduct
|
||||
* <p/>
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-sandbox/src/main/java/com/twelvemonkeys/sql/DatabaseProduct.java#1 $
|
||||
*/
|
||||
public final class DatabaseProduct implements Serializable {
|
||||
private static final String UNKNOWN_NAME = "Unknown";
|
||||
private static final String GENERIC_NAME = "Generic";
|
||||
private static final String CACHE_NAME = "Caché";
|
||||
private static final String DB2_NAME = "DB2";
|
||||
private static final String MSSQL_NAME = "MSSQL";
|
||||
private static final String ORACLE_NAME = "Oracle";
|
||||
private static final String POSTGRESS_NAME = "PostgreSQL";
|
||||
private static final String SYBASE_NAME = "Sybase";
|
||||
|
||||
/*public*/ static final DatabaseProduct UNKNOWN = new DatabaseProduct(UNKNOWN_NAME);
|
||||
public static final DatabaseProduct GENERIC = new DatabaseProduct(GENERIC_NAME);
|
||||
public static final DatabaseProduct CACHE = new DatabaseProduct(CACHE_NAME);
|
||||
public static final DatabaseProduct DB2 = new DatabaseProduct(DB2_NAME);
|
||||
public static final DatabaseProduct MSSQL = new DatabaseProduct(MSSQL_NAME);
|
||||
public static final DatabaseProduct ORACLE = new DatabaseProduct(ORACLE_NAME);
|
||||
public static final DatabaseProduct POSTGRES = new DatabaseProduct(POSTGRESS_NAME);
|
||||
public static final DatabaseProduct SYBASE = new DatabaseProduct(SYBASE_NAME);
|
||||
|
||||
private static final DatabaseProduct[] VALUES = {
|
||||
GENERIC, CACHE, DB2, MSSQL, ORACLE, POSTGRES, SYBASE,
|
||||
};
|
||||
|
||||
private static int sNextOrdinal = -1;
|
||||
private final int mOrdinal = sNextOrdinal++;
|
||||
|
||||
private final String mKey;
|
||||
|
||||
private DatabaseProduct(String pName) {
|
||||
mKey = pName;
|
||||
}
|
||||
|
||||
static int enumSize() {
|
||||
return sNextOrdinal;
|
||||
}
|
||||
|
||||
final int id() {
|
||||
return mOrdinal;
|
||||
}
|
||||
|
||||
final String key() {
|
||||
return mKey;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return mKey + " [id=" + mOrdinal+ "]";
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@code DatabaseProduct} known by the given name.
|
||||
*
|
||||
* @param pName
|
||||
* @return the {@code DatabaseProduct} known by the given name
|
||||
* @throws IllegalArgumentException if there's no such name
|
||||
*/
|
||||
public static DatabaseProduct resolve(String pName) {
|
||||
if ("ANSI".equalsIgnoreCase(pName) || GENERIC_NAME.equalsIgnoreCase(pName)) {
|
||||
return GENERIC;
|
||||
}
|
||||
else if ("Cache".equalsIgnoreCase(pName) || CACHE_NAME.equalsIgnoreCase(pName)) {
|
||||
return CACHE;
|
||||
}
|
||||
else if (DB2_NAME.equalsIgnoreCase(pName)) {
|
||||
return DB2;
|
||||
}
|
||||
else if (MSSQL_NAME.equalsIgnoreCase(pName)) {
|
||||
return MSSQL;
|
||||
}
|
||||
else if (ORACLE_NAME.equalsIgnoreCase(pName)) {
|
||||
return ORACLE;
|
||||
}
|
||||
else if ("Postgres".equalsIgnoreCase(pName) || POSTGRESS_NAME.equalsIgnoreCase(pName)) {
|
||||
return POSTGRES;
|
||||
}
|
||||
else if (SYBASE_NAME.equalsIgnoreCase(pName)) {
|
||||
return SYBASE;
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Unknown database product \"" + pName
|
||||
+ "\", try any of the known products, or \"Generic\"");
|
||||
}
|
||||
}
|
||||
|
||||
private Object readResolve() {
|
||||
return VALUES[mOrdinal]; // Canonicalize
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* 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.sql;
|
||||
|
||||
import java.util.Hashtable;
|
||||
|
||||
/**
|
||||
* Interface for classes that is to be read from a database, using the
|
||||
* ObjectReader class.
|
||||
*
|
||||
* @author Harald Kuhr (haraldk@iconmedialab.no)
|
||||
* @author last modified by $Author: haku $
|
||||
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-sandbox/src/main/java/com/twelvemonkeys/sql/DatabaseReadable.java#1 $
|
||||
*
|
||||
* @todo Use JDK logging instead of proprietary logging.
|
||||
*
|
||||
*/
|
||||
public interface DatabaseReadable {
|
||||
|
||||
/**
|
||||
* Gets the unique identifier of this DatabaseReadable object.
|
||||
*
|
||||
* @return An object that uniqely identifies this DatabaseReadable.
|
||||
*/
|
||||
|
||||
public Object getId();
|
||||
|
||||
/**
|
||||
* Sets the unique identifier of this DatabaseReadable object.
|
||||
*
|
||||
* @param id An object that uniqely identifies this DatabaseReadable.
|
||||
*/
|
||||
|
||||
public void setId(Object id);
|
||||
|
||||
/**
|
||||
* Gets the object to database mapping of this DatabaseReadable.
|
||||
*
|
||||
* @return A Hashtable cotaining the database mapping for this
|
||||
* DatabaseReadable.
|
||||
*/
|
||||
|
||||
public Hashtable getMapping();
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
/*
|
||||
* 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.sql;
|
||||
|
||||
/**
|
||||
* AbstractHelper
|
||||
* <p/>
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-sandbox/src/main/java/com/twelvemonkeys/sql/JDBCHelper.java#1 $
|
||||
*/
|
||||
public abstract class JDBCHelper {
|
||||
|
||||
private static JDBCHelper[] sHelpers = new JDBCHelper[DatabaseProduct.enumSize()];
|
||||
|
||||
static {
|
||||
DatabaseProduct product = DatabaseProduct.resolve(System.getProperty("com.twelvemonkeys.sql.databaseProduct", "Generic"));
|
||||
sHelpers[0] = createInstance(product);
|
||||
}
|
||||
|
||||
private JDBCHelper() {
|
||||
}
|
||||
|
||||
private static JDBCHelper createInstance(DatabaseProduct pProduct) {
|
||||
// Get database name
|
||||
// Instantiate helper
|
||||
if (pProduct == DatabaseProduct.GENERIC) {
|
||||
return new GenericHelper();
|
||||
}
|
||||
else if (pProduct == DatabaseProduct.CACHE) {
|
||||
return new CacheHelper();
|
||||
}
|
||||
else if (pProduct == DatabaseProduct.DB2) {
|
||||
return new DB2Helper();
|
||||
}
|
||||
else if (pProduct == DatabaseProduct.MSSQL) {
|
||||
return new MSSQLHelper();
|
||||
}
|
||||
else if (pProduct == DatabaseProduct.ORACLE) {
|
||||
return new OracleHelper();
|
||||
}
|
||||
else if (pProduct == DatabaseProduct.POSTGRES) {
|
||||
return new PostgreSQLHelper();
|
||||
}
|
||||
else if (pProduct == DatabaseProduct.SYBASE) {
|
||||
return new SybaseHelper();
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Unknown database product, try any of the known products, or \"generic\"");
|
||||
}
|
||||
}
|
||||
|
||||
public final static JDBCHelper getInstance() {
|
||||
return sHelpers[0];
|
||||
}
|
||||
|
||||
public final static JDBCHelper getInstance(DatabaseProduct pProuct) {
|
||||
JDBCHelper helper = sHelpers[pProuct.id()];
|
||||
if (helper == null) {
|
||||
// This is ok, iff sHelpers[pProuct] = helper is an atomic op...
|
||||
synchronized (sHelpers) {
|
||||
helper = sHelpers[pProuct.id()];
|
||||
if (helper == null) {
|
||||
helper = createInstance(pProuct);
|
||||
sHelpers[pProuct.id()] = helper;
|
||||
}
|
||||
}
|
||||
}
|
||||
return helper;
|
||||
}
|
||||
|
||||
// Abstract or ANSI SQL implementations of different stuff
|
||||
|
||||
public String getDefaultDriverName() {
|
||||
return "";
|
||||
}
|
||||
|
||||
public String getDefaultURL() {
|
||||
return "jdbc:{$DRIVER}://localhost:{$PORT}/{$DATABASE}";
|
||||
}
|
||||
|
||||
// Vendor specific concrete implementations
|
||||
|
||||
static class GenericHelper extends JDBCHelper {
|
||||
// Nothing here
|
||||
}
|
||||
|
||||
static class CacheHelper extends JDBCHelper {
|
||||
public String getDefaultDriverName() {
|
||||
return "com.intersys.jdbc.CacheDriver";
|
||||
}
|
||||
|
||||
public String getDefaultURL() {
|
||||
return "jdbc:Cache://localhost:1972/{$DATABASE}";
|
||||
}
|
||||
}
|
||||
|
||||
static class DB2Helper extends JDBCHelper {
|
||||
public String getDefaultDriverName() {
|
||||
return "COM.ibm.db2.jdbc.net.DB2Driver";
|
||||
}
|
||||
|
||||
public String getDefaultURL() {
|
||||
return "jdbc:db2:{$DATABASE}";
|
||||
}
|
||||
}
|
||||
|
||||
static class MSSQLHelper extends JDBCHelper {
|
||||
public String getDefaultDriverName() {
|
||||
return "com.microsoft.jdbc.sqlserver.SQLServerDriver";
|
||||
}
|
||||
|
||||
public String getDefaultURL() {
|
||||
return "jdbc:microsoft:sqlserver://localhost:1433;databasename={$DATABASE};SelectMethod=cursor";
|
||||
}
|
||||
}
|
||||
|
||||
static class OracleHelper extends JDBCHelper {
|
||||
public String getDefaultDriverName() {
|
||||
return "oracle.jdbc.driver.OracleDriver";
|
||||
}
|
||||
|
||||
public String getDefaultURL() {
|
||||
return "jdbc:oracle:thin:@localhost:1521:{$DATABASE}";
|
||||
}
|
||||
}
|
||||
|
||||
static class PostgreSQLHelper extends JDBCHelper {
|
||||
public String getDefaultDriverName() {
|
||||
return "org.postgresql.Driver";
|
||||
}
|
||||
|
||||
public String getDefaultURL() {
|
||||
return "jdbc:postgresql://localhost/{$DATABASE}";
|
||||
}
|
||||
}
|
||||
|
||||
static class SybaseHelper extends JDBCHelper {
|
||||
public String getDefaultDriverName() {
|
||||
return "com.sybase.jdbc2.jdbc.SybDriver";
|
||||
}
|
||||
|
||||
public String getDefaultURL() {
|
||||
return "jdbc:sybase:Tds:localhost:4100/";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,673 @@
|
||||
/*
|
||||
* 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.sql;
|
||||
|
||||
|
||||
import com.twelvemonkeys.lang.SystemUtil;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.Date;
|
||||
import java.util.Hashtable;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* Class used for logging.
|
||||
* The class currently supports four levels of logging (debug, warning, error
|
||||
* and info).
|
||||
* <P>
|
||||
* The class maintains a cahce of OutputStreams, to avoid more than one stream
|
||||
* logging to a specific file. The class should also be thread safe, in that no
|
||||
* more than one instance of the class can log to the same OuputStream.
|
||||
* <P>
|
||||
* <STRONG>
|
||||
* WARNING: The uniqueness of logfiles is based on filenames alone, meaning
|
||||
* "info.log" and "./info.log" will probably be treated as different files,
|
||||
* and have different streams attatched to them.
|
||||
* </STRONG>
|
||||
* <P>
|
||||
* <STRONG>
|
||||
* WARNING: The cached OutputStreams can possibly be in error state or be
|
||||
* closed without warning. Should be fixed in later versions!
|
||||
* </STRONG>
|
||||
*
|
||||
* @author Harald Kuhr (haraldk@iconmedialab.no)
|
||||
* @author last modified by $Author: haku $
|
||||
*
|
||||
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-sandbox/src/main/java/com/twelvemonkeys/sql/Log.java#1 $
|
||||
*
|
||||
* @deprecated Use the JDK java.util.logging for logging.
|
||||
* This class is old and outdated, and is here only for compatibility. It will
|
||||
* be removed from the library in later releases.
|
||||
* <P>
|
||||
* All new code are strongly encouraged to use the org.apache.commons.logging
|
||||
* package for logging.
|
||||
*
|
||||
* @see java.util.logging.Logger
|
||||
*
|
||||
*/
|
||||
|
||||
class Log {
|
||||
private static Hashtable streamCache = new Hashtable();
|
||||
|
||||
static {
|
||||
streamCache.put("System.out", System.out);
|
||||
streamCache.put("System.err", System.err);
|
||||
}
|
||||
|
||||
private static Log globalLog = null;
|
||||
|
||||
private String owner = null;
|
||||
|
||||
private boolean logDebug = false;
|
||||
private boolean logWarning = false;
|
||||
private boolean logError = true; // Log errors!
|
||||
private boolean logInfo = false;
|
||||
|
||||
private PrintStream debugLog = null;
|
||||
private PrintStream warningLog = null;
|
||||
private PrintStream errorLog = null;
|
||||
private PrintStream infoLog = null;
|
||||
|
||||
/**
|
||||
* Init global log
|
||||
*/
|
||||
|
||||
static {
|
||||
Properties config = null;
|
||||
try {
|
||||
config = SystemUtil.loadProperties(Log.class);
|
||||
}
|
||||
catch (FileNotFoundException fnf) {
|
||||
// That's okay.
|
||||
}
|
||||
catch (IOException ioe) {
|
||||
// Not so good
|
||||
log(System.err, "ERROR", Log.class.getName(), null, ioe);
|
||||
}
|
||||
|
||||
globalLog = new Log(new Log(), config);
|
||||
|
||||
// Defaults
|
||||
if (globalLog.debugLog == null)
|
||||
globalLog.setDebugLog(System.out);
|
||||
if (globalLog.warningLog == null)
|
||||
globalLog.setWarningLog(System.err);
|
||||
if (globalLog.errorLog == null)
|
||||
globalLog.setErrorLog(System.err);
|
||||
if (globalLog.infoLog == null)
|
||||
globalLog.setInfoLog(System.out);
|
||||
|
||||
// Info
|
||||
globalLog.logDebug("Logging system started.");
|
||||
log(globalLog.infoLog, "INFO", Log.class.getName(),
|
||||
"Logging system started.", null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal use only
|
||||
*/
|
||||
|
||||
private Log() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a log
|
||||
*/
|
||||
|
||||
public Log(Object owner) {
|
||||
this.owner = owner.getClass().getName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a log
|
||||
*/
|
||||
|
||||
public Log(Object owner, Properties config) {
|
||||
this(owner);
|
||||
|
||||
if (config == null)
|
||||
return;
|
||||
|
||||
// Set logging levels
|
||||
logDebug = new Boolean(config.getProperty("logDebug",
|
||||
"false")).booleanValue();
|
||||
logWarning = new Boolean(config.getProperty("logWarning",
|
||||
"false")).booleanValue();
|
||||
logError = new Boolean(config.getProperty("logError",
|
||||
"true")).booleanValue();
|
||||
logInfo = new Boolean(config.getProperty("logInfo",
|
||||
"true")).booleanValue();
|
||||
|
||||
// Set logging streams
|
||||
String fileName;
|
||||
try {
|
||||
if ((fileName = config.getProperty("debugLog")) != null)
|
||||
setDebugLog(fileName);
|
||||
|
||||
if ((fileName = config.getProperty("warningLog")) != null)
|
||||
setWarningLog(fileName);
|
||||
|
||||
if ((fileName = config.getProperty("errorLog")) != null)
|
||||
setErrorLog(fileName);
|
||||
|
||||
if ((fileName = config.getProperty("infoLog")) != null)
|
||||
setInfoLog(fileName);
|
||||
}
|
||||
catch (IOException ioe) {
|
||||
if (errorLog == null)
|
||||
setErrorLog(System.err);
|
||||
logError("Could not create one or more logging streams! ", ioe);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if we log debug info
|
||||
*
|
||||
* @return True if logging
|
||||
*/
|
||||
|
||||
public boolean getLogDebug() {
|
||||
return logDebug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets wheter we are to log debug info
|
||||
*
|
||||
* @param logDebug Boolean, true if we want to log debug info
|
||||
*/
|
||||
|
||||
public void setLogDebug(boolean logDebug) {
|
||||
this.logDebug = logDebug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if we globally log debug info
|
||||
*
|
||||
* @return True if global logging
|
||||
*/
|
||||
/*
|
||||
public static boolean getGlobalDebug() {
|
||||
return globalDebug;
|
||||
}
|
||||
*/
|
||||
/**
|
||||
* Sets wheter we are to globally log debug info
|
||||
*
|
||||
* @param logDebug Boolean, true if we want to globally log debug info
|
||||
*/
|
||||
/*
|
||||
public static void setGlobalDebug(boolean globalDebug) {
|
||||
Log.globalDebug = globalDebug;
|
||||
}
|
||||
/*
|
||||
/**
|
||||
* Sets the OutputStream we want to print to
|
||||
*
|
||||
* @param os The OutputStream we will use for logging
|
||||
*/
|
||||
|
||||
public void setDebugLog(OutputStream os) {
|
||||
debugLog = new PrintStream(os, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the filename of the File we want to print to. Equivalent to
|
||||
* setDebugLog(new FileOutputStream(fileName, true))
|
||||
*
|
||||
* @param file The File we will use for logging
|
||||
* @see #setDebugLog(OutputStream)
|
||||
*/
|
||||
|
||||
public void setDebugLog(String fileName) throws IOException {
|
||||
setDebugLog(getStream(fileName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints debug info to the current debugLog
|
||||
*
|
||||
* @param message The message to log
|
||||
* @see #logDebug(String, Exception)
|
||||
*/
|
||||
|
||||
public void logDebug(String message) {
|
||||
logDebug(message, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints debug info to the current debugLog
|
||||
*
|
||||
* @param exception An Exception
|
||||
* @see #logDebug(String, Exception)
|
||||
*/
|
||||
|
||||
public void logDebug(Exception exception) {
|
||||
logDebug(null, exception);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Prints debug info to the current debugLog
|
||||
*
|
||||
* @param message The message to log
|
||||
* @param exception An Exception
|
||||
*/
|
||||
|
||||
public void logDebug(String message, Exception exception) {
|
||||
if (!(logDebug || globalLog.logDebug))
|
||||
return;
|
||||
|
||||
if (debugLog != null)
|
||||
log(debugLog, "DEBUG", owner, message, exception);
|
||||
else
|
||||
log(globalLog.debugLog, "DEBUG", owner, message, exception);
|
||||
}
|
||||
|
||||
// WARNING
|
||||
|
||||
/**
|
||||
* Checks if we log warning info
|
||||
*
|
||||
* @return True if logging
|
||||
*/
|
||||
|
||||
public boolean getLogWarning() {
|
||||
return logWarning;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets wheter we are to log warning info
|
||||
*
|
||||
* @param logWarning Boolean, true if we want to log warning info
|
||||
*/
|
||||
|
||||
public void setLogWarning(boolean logWarning) {
|
||||
this.logWarning = logWarning;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if we globally log warning info
|
||||
*
|
||||
* @return True if global logging
|
||||
*/
|
||||
/*
|
||||
public static boolean getGlobalWarning() {
|
||||
return globalWarning;
|
||||
}
|
||||
*/
|
||||
/**
|
||||
* Sets wheter we are to globally log warning info
|
||||
*
|
||||
* @param logWarning Boolean, true if we want to globally log warning info
|
||||
*/
|
||||
/*
|
||||
public static void setGlobalWarning(boolean globalWarning) {
|
||||
Log.globalWarning = globalWarning;
|
||||
}
|
||||
*/
|
||||
/**
|
||||
* Sets the OutputStream we want to print to
|
||||
*
|
||||
* @param os The OutputStream we will use for logging
|
||||
*/
|
||||
|
||||
public void setWarningLog(OutputStream os) {
|
||||
warningLog = new PrintStream(os, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the filename of the File we want to print to. Equivalent to
|
||||
* setWarningLog(new FileOutputStream(fileName, true))
|
||||
*
|
||||
* @param file The File we will use for logging
|
||||
* @see #setWarningLog(OutputStream)
|
||||
*/
|
||||
|
||||
public void setWarningLog(String fileName) throws IOException {
|
||||
setWarningLog(getStream(fileName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints warning info to the current warningLog
|
||||
*
|
||||
* @param message The message to log
|
||||
* @see #logWarning(String, Exception)
|
||||
*/
|
||||
|
||||
public void logWarning(String message) {
|
||||
logWarning(message, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints warning info to the current warningLog
|
||||
*
|
||||
* @param exception An Exception
|
||||
* @see #logWarning(String, Exception)
|
||||
*/
|
||||
|
||||
public void logWarning(Exception exception) {
|
||||
logWarning(null, exception);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Prints warning info to the current warningLog
|
||||
*
|
||||
* @param message The message to log
|
||||
* @param exception An Exception
|
||||
*/
|
||||
|
||||
public void logWarning(String message, Exception exception) {
|
||||
if (!(logWarning || globalLog.logWarning))
|
||||
return;
|
||||
|
||||
if (warningLog != null)
|
||||
log(warningLog, "WARNING", owner, message, exception);
|
||||
else
|
||||
log(globalLog.warningLog, "WARNING", owner, message, exception);
|
||||
}
|
||||
|
||||
// ERROR
|
||||
|
||||
/**
|
||||
* Checks if we log error info
|
||||
*
|
||||
* @return True if logging
|
||||
*/
|
||||
|
||||
public boolean getLogError() {
|
||||
return logError;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets wheter we are to log error info
|
||||
*
|
||||
* @param logError Boolean, true if we want to log error info
|
||||
*/
|
||||
|
||||
public void setLogError(boolean logError) {
|
||||
this.logError = logError;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if we globally log error info
|
||||
*
|
||||
* @return True if global logging
|
||||
*/
|
||||
/*
|
||||
public static boolean getGlobalError() {
|
||||
return globalError;
|
||||
}
|
||||
*/
|
||||
/**
|
||||
* Sets wheter we are to globally log error info
|
||||
*
|
||||
* @param logError Boolean, true if we want to globally log error info
|
||||
*/
|
||||
/*
|
||||
public static void setGlobalError(boolean globalError) {
|
||||
Log.globalError = globalError;
|
||||
}
|
||||
*/
|
||||
/**
|
||||
* Sets the OutputStream we want to print to
|
||||
*
|
||||
* @param os The OutputStream we will use for logging
|
||||
*/
|
||||
|
||||
public void setErrorLog(OutputStream os) {
|
||||
errorLog = new PrintStream(os, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the filename of the File we want to print to. Equivalent to
|
||||
* setErrorLog(new FileOutputStream(fileName, true))
|
||||
*
|
||||
* @param file The File we will use for logging
|
||||
* @see #setErrorLog(OutputStream)
|
||||
*/
|
||||
|
||||
public void setErrorLog(String fileName) throws IOException {
|
||||
setErrorLog(getStream(fileName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints error info to the current errorLog
|
||||
*
|
||||
* @param message The message to log
|
||||
* @see #logError(String, Exception)
|
||||
*/
|
||||
|
||||
public void logError(String message) {
|
||||
logError(message, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints error info to the current errorLog
|
||||
*
|
||||
* @param exception An Exception
|
||||
* @see #logError(String, Exception)
|
||||
*/
|
||||
|
||||
public void logError(Exception exception) {
|
||||
logError(null, exception);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints error info to the current errorLog
|
||||
*
|
||||
* @param message The message to log
|
||||
* @param exception An Exception
|
||||
*/
|
||||
|
||||
public void logError(String message, Exception exception) {
|
||||
if (!(logError || globalLog.logError))
|
||||
return;
|
||||
|
||||
if (errorLog != null)
|
||||
log(errorLog, "ERROR", owner, message, exception);
|
||||
else
|
||||
log(globalLog.errorLog, "ERROR", owner, message, exception);
|
||||
}
|
||||
|
||||
// INFO
|
||||
|
||||
/**
|
||||
* Checks if we log info info
|
||||
*
|
||||
* @return True if logging
|
||||
*/
|
||||
|
||||
public boolean getLogInfo() {
|
||||
return logInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets wheter we are to log info info
|
||||
*
|
||||
* @param logInfo Boolean, true if we want to log info info
|
||||
*/
|
||||
|
||||
public void setLogInfo(boolean logInfo) {
|
||||
this.logInfo = logInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if we globally log info info
|
||||
*
|
||||
* @return True if global logging
|
||||
*/
|
||||
/*
|
||||
public static boolean getGlobalInfo() {
|
||||
return globalInfo;
|
||||
}
|
||||
*/
|
||||
/**
|
||||
* Sets wheter we are to globally log info info
|
||||
*
|
||||
* @param logInfo Boolean, true if we want to globally log info info
|
||||
*/
|
||||
/*
|
||||
public static void setGlobalInfo(boolean globalInfo) {
|
||||
Log.globalInfo = globalInfo;
|
||||
}
|
||||
*/
|
||||
/**
|
||||
* Sets the OutputStream we want to print to
|
||||
*
|
||||
* @param os The OutputStream we will use for logging
|
||||
*/
|
||||
|
||||
public void setInfoLog(OutputStream os) {
|
||||
infoLog = new PrintStream(os, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the filename of the File we want to print to. Equivalent to
|
||||
* setInfoLog(new FileOutputStream(fileName, true))
|
||||
*
|
||||
* @param file The File we will use for logging
|
||||
* @see #setInfoLog(OutputStream)
|
||||
*/
|
||||
|
||||
public void setInfoLog(String fileName) throws IOException {
|
||||
setInfoLog(getStream(fileName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints info info to the current infoLog
|
||||
*
|
||||
* @param message The message to log
|
||||
* @see #logInfo(String, Exception)
|
||||
*/
|
||||
|
||||
public void logInfo(String message) {
|
||||
logInfo(message, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints info info to the current infoLog
|
||||
*
|
||||
* @param exception An Exception
|
||||
* @see #logInfo(String, Exception)
|
||||
*/
|
||||
|
||||
public void logInfo(Exception exception) {
|
||||
logInfo(null, exception);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints info info to the current infoLog
|
||||
*
|
||||
* @param message The message to log
|
||||
* @param exception An Exception
|
||||
*/
|
||||
|
||||
public void logInfo(String message, Exception exception) {
|
||||
if (!(logInfo || globalLog.logInfo))
|
||||
return;
|
||||
|
||||
if (infoLog != null)
|
||||
log(infoLog, "INFO", owner, message, exception);
|
||||
else
|
||||
log(globalLog.infoLog, "INFO", owner, message, exception);
|
||||
}
|
||||
|
||||
// LOG
|
||||
|
||||
/**
|
||||
* Internal method to get a named stream
|
||||
*/
|
||||
|
||||
private static OutputStream getStream(String name) throws IOException {
|
||||
OutputStream os = null;
|
||||
|
||||
synchronized (streamCache) {
|
||||
if ((os = (OutputStream) streamCache.get(name)) != null)
|
||||
return os;
|
||||
|
||||
os = new FileOutputStream(name, true);
|
||||
streamCache.put(name, os);
|
||||
}
|
||||
|
||||
return os;
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal log method
|
||||
*/
|
||||
|
||||
private static void log(PrintStream ps, String header,
|
||||
String owner, String message, Exception ex) {
|
||||
// Only allow one instance to print to the given stream.
|
||||
synchronized (ps) {
|
||||
// Create output stream for logging
|
||||
LogStream logStream = new LogStream(ps);
|
||||
|
||||
logStream.time = new Date(System.currentTimeMillis());
|
||||
logStream.header = header;
|
||||
logStream.owner = owner;
|
||||
|
||||
if (message != null)
|
||||
logStream.println(message);
|
||||
|
||||
if (ex != null) {
|
||||
logStream.println(ex.getMessage());
|
||||
ex.printStackTrace(logStream);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility class for logging.
|
||||
*
|
||||
* Minimal overloading of PrintStream
|
||||
*/
|
||||
|
||||
class LogStream extends PrintStream {
|
||||
Date time = null;
|
||||
String header = null;
|
||||
String owner = null;
|
||||
|
||||
public LogStream(OutputStream ps) {
|
||||
super(ps);
|
||||
}
|
||||
|
||||
public void println(Object o) {
|
||||
if (o == null)
|
||||
println("null");
|
||||
else
|
||||
println(o.toString());
|
||||
}
|
||||
|
||||
public void println(String str) {
|
||||
super.println("*** " + header + " (" + time + ", " + time.getTime()
|
||||
+ ") " + owner + ": " + str);
|
||||
}
|
||||
}
|
||||
+276
@@ -0,0 +1,276 @@
|
||||
/*
|
||||
* 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.sql;
|
||||
|
||||
|
||||
import java.lang.reflect.*;
|
||||
import java.util.*;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Connection;
|
||||
|
||||
/*
|
||||
Det vi trenger er en mapping mellom
|
||||
- abstrakt navn/klasse/type/identifikator (tilsv. repository)
|
||||
- java klasse
|
||||
- selve mappingen av db kolonne/java property
|
||||
|
||||
I tillegg en mapping mellom alle objektene som brukes i VM'en, og deres id'er
|
||||
|
||||
*/
|
||||
|
||||
/**
|
||||
* Under construction.
|
||||
*
|
||||
* @author Harald Kuhr (haraldk@iconmedialab.no),
|
||||
* @version 0.5
|
||||
*/
|
||||
public abstract class ObjectManager {
|
||||
private ObjectReader mObjectReader = null;
|
||||
|
||||
private WeakHashMap mLiveObjects = new WeakHashMap(); // object/id
|
||||
|
||||
private Hashtable mTypes = new Hashtable(); // type name/java class
|
||||
private Hashtable mMappings = new Hashtable(); // type name/mapping
|
||||
|
||||
/**
|
||||
* Creates an Object Manager with the default JDBC connection
|
||||
*/
|
||||
|
||||
public ObjectManager() {
|
||||
this(DatabaseConnection.getConnection());
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an Object Manager with the given JDBC connection
|
||||
*/
|
||||
|
||||
public ObjectManager(Connection pConnection) {
|
||||
mObjectReader = new ObjectReader(pConnection);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Gets the property/column mapping for a given type
|
||||
*/
|
||||
|
||||
protected Hashtable getMapping(String pType) {
|
||||
return (Hashtable) mMappings.get(pType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the class for a type
|
||||
*
|
||||
* @return The class for a type. If the type is not found, this method will
|
||||
* throw an excpetion, and will never return null.
|
||||
*/
|
||||
|
||||
protected Class getType(String pType) {
|
||||
Class cl = (Class) mTypes.get(pType);
|
||||
|
||||
if (cl == null) {
|
||||
// throw new NoSuchTypeException();
|
||||
}
|
||||
|
||||
return cl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a java object of the class for a given type.
|
||||
*/
|
||||
|
||||
protected Object getObject(String pType)
|
||||
/*throws XxxException*/ {
|
||||
// Get class
|
||||
Class cl = getType(pType);
|
||||
|
||||
// Return the new instance (requires empty public constructor)
|
||||
try {
|
||||
return cl.newInstance();
|
||||
}
|
||||
catch (Exception e) {
|
||||
// throw new XxxException(e);
|
||||
throw new RuntimeException(e.getMessage());
|
||||
}
|
||||
|
||||
// Can't happen
|
||||
//return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a DatabaseReadable object that can be used for looking up the
|
||||
* object properties from the database.
|
||||
*/
|
||||
|
||||
protected DatabaseReadable getDatabaseReadable(String pType) {
|
||||
|
||||
return new DatabaseObject(getObject(pType), getMapping(pType));
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the object of the given type and with the given id from the
|
||||
* database
|
||||
*/
|
||||
|
||||
// interface
|
||||
public Object getObject(String pType, Object pId)
|
||||
throws SQLException {
|
||||
|
||||
// Create DatabaseReadable and set id
|
||||
DatabaseObject dbObject = (DatabaseObject) getDatabaseReadable(pType);
|
||||
dbObject.setId(pId);
|
||||
|
||||
// Read it
|
||||
dbObject = (DatabaseObject) mObjectReader.readObject(dbObject);
|
||||
|
||||
// Return it
|
||||
return dbObject.getObject();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the objects of the given type and with the given ids from the
|
||||
* database
|
||||
*/
|
||||
|
||||
// interface
|
||||
public Object[] getObjects(String pType, Object[] pIds)
|
||||
throws SQLException {
|
||||
|
||||
// Create Vector to hold the result
|
||||
Vector result = new Vector(pIds.length);
|
||||
|
||||
// Loop through Id's and fetch one at a time (no good performance...)
|
||||
for (int i = 0; i < pIds.length; i++) {
|
||||
// Create DBObject, set id and read it
|
||||
DatabaseObject dbObject =
|
||||
(DatabaseObject) getDatabaseReadable(pType);
|
||||
|
||||
dbObject.setId(pIds[i]);
|
||||
dbObject = (DatabaseObject) mObjectReader.readObject(dbObject);
|
||||
|
||||
// Add to result if not null
|
||||
if (dbObject != null) {
|
||||
result.add(dbObject.getObject());
|
||||
}
|
||||
}
|
||||
|
||||
// Create array of correct type, length equal to Vector
|
||||
Class cl = getType(pType);
|
||||
Object[] arr = (Object[]) Array.newInstance(cl, result.size());
|
||||
|
||||
// Return the vector as an array
|
||||
return result.toArray(arr);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the objects of the given type and with the given properties from
|
||||
* the database
|
||||
*/
|
||||
|
||||
// interface
|
||||
public Object[] getObjects(String pType, Hashtable pWhere)
|
||||
throws SQLException {
|
||||
return mObjectReader.readObjects(getDatabaseReadable(pType), pWhere);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads all objects of the given type from the database
|
||||
*/
|
||||
|
||||
// interface
|
||||
public Object[] getObjects(String pType)
|
||||
throws SQLException {
|
||||
return mObjectReader.readObjects(getDatabaseReadable(pType));
|
||||
}
|
||||
|
||||
// interface
|
||||
public Object addObject(Object pObject) {
|
||||
// get id...
|
||||
|
||||
return pObject;
|
||||
}
|
||||
|
||||
// interface
|
||||
public Object updateObject(Object pObject) {
|
||||
// get id...
|
||||
|
||||
return pObject;
|
||||
}
|
||||
|
||||
// interface
|
||||
public abstract Object deleteObject(String pType, Object pId);
|
||||
|
||||
// interface
|
||||
public abstract Object deleteObject(Object pObject);
|
||||
|
||||
// interface
|
||||
public abstract Object createObject(String pType, Object pId);
|
||||
|
||||
// interface
|
||||
public abstract Object createObject(String pType);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility class for reading Objects from the database
|
||||
*/
|
||||
|
||||
class DatabaseObject implements DatabaseReadable {
|
||||
Hashtable mMapping = null;
|
||||
|
||||
Object mId = null;
|
||||
Object mObject = null;
|
||||
|
||||
public DatabaseObject(Object pObject, Hashtable pMapping) {
|
||||
setObject(pObject);
|
||||
setMapping(pMapping);
|
||||
}
|
||||
|
||||
public Object getId() {
|
||||
return mId;
|
||||
}
|
||||
|
||||
public void setId(Object pId) {
|
||||
mId = pId;
|
||||
}
|
||||
|
||||
public void setObject(Object pObject) {
|
||||
mObject = pObject;
|
||||
}
|
||||
public Object getObject() {
|
||||
return mObject;
|
||||
}
|
||||
|
||||
public void setMapping(Hashtable pMapping) {
|
||||
mMapping = pMapping;
|
||||
}
|
||||
|
||||
public Hashtable getMapping() {
|
||||
return mMapping;
|
||||
}
|
||||
}
|
||||
+663
@@ -0,0 +1,663 @@
|
||||
/*
|
||||
* 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.sql;
|
||||
|
||||
import com.twelvemonkeys.lang.*;
|
||||
|
||||
import java.lang.reflect.*;
|
||||
|
||||
// Single-type import, to avoid util.Date/sql.Date confusion
|
||||
import java.util.Hashtable;
|
||||
import java.util.Vector;
|
||||
import java.util.Enumeration;
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* A class for mapping JDBC ResultSet rows to Java objects.
|
||||
*
|
||||
* @see ObjectReader
|
||||
*
|
||||
* @author Harald Kuhr (haraldk@iconmedialab.no)
|
||||
* @author last modified by $Author: haku $
|
||||
*
|
||||
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-sandbox/src/main/java/com/twelvemonkeys/sql/ObjectMapper.java#1 $
|
||||
*
|
||||
* @todo Use JDK logging instead of proprietary logging.
|
||||
*/
|
||||
public class ObjectMapper {
|
||||
final static String DIRECTMAP = "direct";
|
||||
final static String OBJECTMAP = "object";
|
||||
final static String COLLECTIONMAP = "collection";
|
||||
final static String OBJCOLLMAP = "objectcollection";
|
||||
|
||||
Class mInstanceClass = null;
|
||||
|
||||
Hashtable mMethods = null;
|
||||
|
||||
Hashtable mColumnMap = null;
|
||||
Hashtable mPropertiesMap = null;
|
||||
|
||||
Hashtable mJoins = null;
|
||||
|
||||
private Hashtable mTables = null;
|
||||
private Vector mColumns = null;
|
||||
|
||||
Hashtable mForeignKeys = null;
|
||||
Hashtable mPrimaryKeys = null;
|
||||
Hashtable mMapTypes = null;
|
||||
Hashtable mClasses = null;
|
||||
|
||||
String mPrimaryKey = null;
|
||||
String mForeignKey = null;
|
||||
String mIdentityJoin = null;
|
||||
|
||||
Log mLog = null;
|
||||
|
||||
/**
|
||||
* Creates a new ObjectMapper for a DatabaseReadable
|
||||
*
|
||||
* @param obj An object of type DatabaseReadable
|
||||
*/
|
||||
|
||||
/*
|
||||
public ObjectMapper(DatabaseReadable obj) {
|
||||
this(obj.getClass(), obj.getMapping());
|
||||
}
|
||||
*/
|
||||
/**
|
||||
* Creates a new ObjectMapper for any object, given a mapping
|
||||
*
|
||||
* @param objClass The class of the object(s) created by this OM
|
||||
* @param mapping an Hashtable containing the mapping information
|
||||
* for this OM
|
||||
*/
|
||||
|
||||
public ObjectMapper(Class pObjClass, Hashtable pMapping) {
|
||||
mLog = new Log(this);
|
||||
|
||||
mInstanceClass = pObjClass;
|
||||
|
||||
mJoins = new Hashtable();
|
||||
mPropertiesMap = new Hashtable();
|
||||
mColumnMap = new Hashtable();
|
||||
|
||||
mClasses = new Hashtable();
|
||||
mMapTypes = new Hashtable();
|
||||
mForeignKeys = new Hashtable();
|
||||
mPrimaryKeys = new Hashtable();
|
||||
|
||||
// Unpack and store mapping information
|
||||
for (Enumeration keys = pMapping.keys(); keys.hasMoreElements();) {
|
||||
String key = (String) keys.nextElement();
|
||||
String value = (String) pMapping.get(key);
|
||||
|
||||
int dotIdx = key.indexOf(".");
|
||||
|
||||
if (dotIdx >= 0) {
|
||||
if (key.equals(".primaryKey")) {
|
||||
// Primary key
|
||||
mPrimaryKey = (String) pMapping.get(value);
|
||||
}
|
||||
else if (key.equals(".foreignKey")) {
|
||||
// Foreign key
|
||||
mForeignKey = (String) pMapping.get(value);
|
||||
}
|
||||
else if (key.equals(".join")) {
|
||||
// Identity join
|
||||
mIdentityJoin = (String) pMapping.get(key);
|
||||
}
|
||||
else if (key.endsWith(".primaryKey")) {
|
||||
// Primary key in joining table
|
||||
mPrimaryKeys.put(key.substring(0, dotIdx), value);
|
||||
}
|
||||
else if (key.endsWith(".foreignKey")) {
|
||||
// Foreign key
|
||||
mForeignKeys.put(key.substring(0, dotIdx), value);
|
||||
}
|
||||
else if (key.endsWith(".join")) {
|
||||
// Joins
|
||||
mJoins.put(key.substring(0, dotIdx), value);
|
||||
}
|
||||
else if (key.endsWith(".mapType")) {
|
||||
// Maptypes
|
||||
value = value.toLowerCase();
|
||||
|
||||
if (value.equals(DIRECTMAP) || value.equals(OBJECTMAP) ||
|
||||
value.equals(COLLECTIONMAP) ||
|
||||
value.equals(OBJCOLLMAP)) {
|
||||
mMapTypes.put(key.substring(0, dotIdx), value);
|
||||
}
|
||||
else {
|
||||
mLog.logError("Illegal mapType: \"" + value + "\"! "
|
||||
+ "Legal types are: direct, object, "
|
||||
+ "collection and objectCollection.");
|
||||
}
|
||||
}
|
||||
else if (key.endsWith(".class")) {
|
||||
// Classes
|
||||
try {
|
||||
mClasses.put(key.substring(0, dotIdx),
|
||||
Class.forName(value));
|
||||
}
|
||||
catch (ClassNotFoundException e) {
|
||||
mLog.logError(e);
|
||||
//e.printStackTrace();
|
||||
}
|
||||
}
|
||||
else if (key.endsWith(".collection")) {
|
||||
// TODO!!
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Property to column mappings
|
||||
mPropertiesMap.put(key, value);
|
||||
mColumnMap.put(value.substring(value.lastIndexOf(".") + 1),
|
||||
key);
|
||||
}
|
||||
}
|
||||
|
||||
mMethods = new Hashtable();
|
||||
Method[] methods = mInstanceClass.getMethods();
|
||||
for (int i = 0; i < methods.length; i++) {
|
||||
// Two methods CAN have same name...
|
||||
mMethods.put(methods[i].getName(), methods[i]);
|
||||
}
|
||||
}
|
||||
|
||||
public void setPrimaryKey(String pPrimaryKey) {
|
||||
mPrimaryKey = pPrimaryKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the name of the property, that acts as the unique identifier for
|
||||
* this ObjectMappers type.
|
||||
*
|
||||
* @return The name of the primary key property
|
||||
*/
|
||||
|
||||
public String getPrimaryKey() {
|
||||
return mPrimaryKey;
|
||||
}
|
||||
|
||||
public String getForeignKey() {
|
||||
return mForeignKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the join, that is needed to find this ObjectMappers type.
|
||||
*
|
||||
* @return The name of the primary key property
|
||||
*/
|
||||
|
||||
public String getIdentityJoin() {
|
||||
return mIdentityJoin;
|
||||
}
|
||||
|
||||
Hashtable getPropertyMapping(String pProperty) {
|
||||
Hashtable mapping = new Hashtable();
|
||||
|
||||
if (pProperty != null) {
|
||||
// Property
|
||||
if (mPropertiesMap.containsKey(pProperty))
|
||||
mapping.put("object", mPropertiesMap.get(pProperty));
|
||||
|
||||
// Primary key
|
||||
if (mPrimaryKeys.containsKey(pProperty)) {
|
||||
mapping.put(".primaryKey", "id");
|
||||
mapping.put("id", mPrimaryKeys.get(pProperty));
|
||||
}
|
||||
|
||||
//Foreign key
|
||||
if (mForeignKeys.containsKey(pProperty))
|
||||
mapping.put(".foreignKey", mPropertiesMap.get(mForeignKeys.get(pProperty)));
|
||||
|
||||
// Join
|
||||
if (mJoins.containsKey(pProperty))
|
||||
mapping.put(".join", mJoins.get(pProperty));
|
||||
|
||||
// mapType
|
||||
mapping.put(".mapType", "object");
|
||||
}
|
||||
|
||||
return mapping;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Gets the column for a given property.
|
||||
*
|
||||
* @param property The property
|
||||
* @return The name of the matching database column, on the form
|
||||
* table.column
|
||||
*/
|
||||
|
||||
public String getColumn(String pProperty) {
|
||||
if (mPropertiesMap == null || pProperty == null)
|
||||
return null;
|
||||
return (String) mPropertiesMap.get(pProperty);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the table name for a given property.
|
||||
*
|
||||
* @param property The property
|
||||
* @return The name of the matching database table.
|
||||
*/
|
||||
|
||||
public String getTable(String pProperty) {
|
||||
String table = getColumn(pProperty);
|
||||
|
||||
if (table != null) {
|
||||
int dotIdx = 0;
|
||||
if ((dotIdx = table.lastIndexOf(".")) >= 0)
|
||||
table = table.substring(0, dotIdx);
|
||||
else
|
||||
return null;
|
||||
}
|
||||
|
||||
return table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the property for a given database column. If the column incudes
|
||||
* table qualifier, the table qualifier is removed.
|
||||
*
|
||||
* @param column The name of the column
|
||||
* @return The name of the mathcing property
|
||||
*/
|
||||
|
||||
public String getProperty(String pColumn) {
|
||||
if (mColumnMap == null || pColumn == null)
|
||||
return null;
|
||||
|
||||
String property = (String) mColumnMap.get(pColumn);
|
||||
|
||||
int dotIdx = 0;
|
||||
if (property == null && (dotIdx = pColumn.lastIndexOf(".")) >= 0)
|
||||
property = (String) mColumnMap.get(pColumn.substring(dotIdx + 1));
|
||||
|
||||
return property;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Maps each row of the given result set to an object ot this OM's type.
|
||||
*
|
||||
* @param rs The ResultSet to process (map to objects)
|
||||
* @return An array of objects (of this OM's class). If there are no rows
|
||||
* in the ResultSet, an empty (zero-length) array will be returned.
|
||||
*/
|
||||
|
||||
public synchronized Object[] mapObjects(ResultSet pRSet) throws SQLException {
|
||||
Vector result = new Vector();
|
||||
|
||||
ResultSetMetaData meta = pRSet.getMetaData();
|
||||
int cols = meta.getColumnCount();
|
||||
|
||||
// Get colum names
|
||||
String[] colNames = new String[cols];
|
||||
for (int i = 0; i < cols; i++) {
|
||||
colNames[i] = meta.getColumnName(i + 1); // JDBC cols start at 1...
|
||||
|
||||
/*
|
||||
System.out.println(meta.getColumnLabel(i + 1));
|
||||
System.out.println(meta.getColumnName(i + 1));
|
||||
System.out.println(meta.getColumnType(i + 1));
|
||||
System.out.println(meta.getColumnTypeName(i + 1));
|
||||
// System.out.println(meta.getTableName(i + 1));
|
||||
// System.out.println(meta.getCatalogName(i + 1));
|
||||
// System.out.println(meta.getSchemaName(i + 1));
|
||||
// Last three NOT IMPLEMENTED!!
|
||||
*/
|
||||
}
|
||||
|
||||
// Loop through rows in resultset
|
||||
while (pRSet.next()) {
|
||||
Object obj = null;
|
||||
|
||||
try {
|
||||
obj = mInstanceClass.newInstance(); // Asserts empty constructor!
|
||||
}
|
||||
catch (IllegalAccessException iae) {
|
||||
mLog.logError(iae);
|
||||
// iae.printStackTrace();
|
||||
}
|
||||
catch (InstantiationException ie) {
|
||||
mLog.logError(ie);
|
||||
// ie.printStackTrace();
|
||||
}
|
||||
|
||||
// Read each colum from this row into object
|
||||
for (int i = 0; i < cols; i++) {
|
||||
|
||||
String property = (String) mColumnMap.get(colNames[i]);
|
||||
|
||||
if (property != null) {
|
||||
// This column is mapped to a property
|
||||
mapColumnProperty(pRSet, i + 1, property, obj);
|
||||
}
|
||||
}
|
||||
|
||||
// Add object to the result Vector
|
||||
result.addElement(obj);
|
||||
}
|
||||
|
||||
return result.toArray((Object[]) Array.newInstance(mInstanceClass,
|
||||
result.size()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a ResultSet column (from the current ResultSet row) to a named
|
||||
* property of an object, using reflection.
|
||||
*
|
||||
* @param rs The JDBC ResultSet
|
||||
* @param index The column index to get the value from
|
||||
* @param property The name of the property to set the value of
|
||||
* @param obj The object to set the property to
|
||||
*/
|
||||
|
||||
void mapColumnProperty(ResultSet pRSet, int pIndex, String pProperty,
|
||||
Object pObj) {
|
||||
if (pRSet == null || pProperty == null || pObj == null)
|
||||
throw new IllegalArgumentException("ResultSet, Property or Object"
|
||||
+ " arguments cannot be null!");
|
||||
if (pIndex <= 0)
|
||||
throw new IllegalArgumentException("Index parameter must be > 0!");
|
||||
|
||||
String methodName = "set" + StringUtil.capitalize(pProperty);
|
||||
Method setMethod = (Method) mMethods.get(methodName);
|
||||
|
||||
if (setMethod == null) {
|
||||
// No setMethod for this property
|
||||
mLog.logError("No set method for property \""
|
||||
+ pProperty + "\" in " + pObj.getClass() + "!");
|
||||
return;
|
||||
}
|
||||
|
||||
// System.err.println("DEBUG: setMethod=" + setMethod);
|
||||
|
||||
Method getMethod = null;
|
||||
|
||||
String type = "";
|
||||
try {
|
||||
Class[] cl = {Integer.TYPE};
|
||||
type = setMethod.getParameterTypes()[0].getName();
|
||||
|
||||
type = type.substring(type.lastIndexOf(".") + 1);
|
||||
|
||||
// There is no getInteger, use getInt instead
|
||||
if (type.equals("Integer")) {
|
||||
type = "int";
|
||||
}
|
||||
|
||||
// System.err.println("DEBUG: type=" + type);
|
||||
getMethod = pRSet.getClass().
|
||||
getMethod("get" + StringUtil.capitalize(type), cl);
|
||||
}
|
||||
catch (Exception e) {
|
||||
mLog.logError("Can't find method \"get"
|
||||
+ StringUtil.capitalize(type) + "(int)\" "
|
||||
+ "(for class " + StringUtil.capitalize(type)
|
||||
+ ") in ResultSet", e);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Get the data from the DB
|
||||
// System.err.println("DEBUG: " + getMethod.getName() + "(" + (i + 1) + ")");
|
||||
|
||||
Object[] colIdx = {new Integer(pIndex)};
|
||||
Object[] arg = {getMethod.invoke(pRSet, colIdx)};
|
||||
|
||||
// Set it to the object
|
||||
// System.err.println("DEBUG: " + setMethod.getName() + "(" + arg[0] + ")");
|
||||
setMethod.invoke(pObj, arg);
|
||||
}
|
||||
catch (InvocationTargetException ite) {
|
||||
mLog.logError(ite);
|
||||
// ite.printStackTrace();
|
||||
}
|
||||
catch (IllegalAccessException iae) {
|
||||
mLog.logError(iae);
|
||||
// iae.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a SQL query string to get the primary keys for this
|
||||
* ObjectMapper.
|
||||
*/
|
||||
|
||||
String buildIdentitySQL(String[] pKeys) {
|
||||
mTables = new Hashtable();
|
||||
mColumns = new Vector();
|
||||
|
||||
// Get columns to select
|
||||
mColumns.addElement(getPrimaryKey());
|
||||
|
||||
// Get tables to select (and join) from and their joins
|
||||
tableJoins(null, false);
|
||||
|
||||
for (int i = 0; i < pKeys.length; i++) {
|
||||
tableJoins(getColumn(pKeys[i]), true);
|
||||
}
|
||||
|
||||
// All data read, build SQL query string
|
||||
return "SELECT " + getPrimaryKey() + " " + buildFromClause()
|
||||
+ buildWhereClause();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a SQL query string to get objects for this ObjectMapper.
|
||||
*/
|
||||
|
||||
public String buildSQL() {
|
||||
mTables = new Hashtable();
|
||||
mColumns = new Vector();
|
||||
|
||||
String key = null;
|
||||
for (Enumeration keys = mPropertiesMap.keys(); keys.hasMoreElements();) {
|
||||
key = (String) keys.nextElement();
|
||||
|
||||
// Get columns to select
|
||||
String column = (String) mPropertiesMap.get(key);
|
||||
mColumns.addElement(column);
|
||||
|
||||
tableJoins(column, false);
|
||||
}
|
||||
|
||||
// All data read, build SQL query string
|
||||
return buildSelectClause() + buildFromClause()
|
||||
+ buildWhereClause();
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a SQL SELECT clause from the columns Vector
|
||||
*/
|
||||
|
||||
private String buildSelectClause() {
|
||||
StringBuilder sqlBuf = new StringBuilder();
|
||||
|
||||
sqlBuf.append("SELECT ");
|
||||
|
||||
String column = null;
|
||||
for (Enumeration select = mColumns.elements(); select.hasMoreElements();) {
|
||||
column = (String) select.nextElement();
|
||||
|
||||
/*
|
||||
String subColumn = column.substring(column.indexOf(".") + 1);
|
||||
// System.err.println("DEBUG: col=" + subColumn);
|
||||
String mapType = (String) mMapTypes.get(mColumnMap.get(subColumn));
|
||||
*/
|
||||
String mapType = (String) mMapTypes.get(getProperty(column));
|
||||
|
||||
if (mapType == null || mapType.equals(DIRECTMAP)) {
|
||||
sqlBuf.append(column);
|
||||
|
||||
sqlBuf.append(select.hasMoreElements() ? ", " : " ");
|
||||
}
|
||||
}
|
||||
|
||||
return sqlBuf.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a SQL FROM clause from the tables/joins Hashtable
|
||||
*/
|
||||
|
||||
private String buildFromClause() {
|
||||
StringBuilder sqlBuf = new StringBuilder();
|
||||
|
||||
sqlBuf.append("FROM ");
|
||||
|
||||
String table = null;
|
||||
String schema = null;
|
||||
for (Enumeration from = mTables.keys(); from.hasMoreElements();) {
|
||||
table = (String) from.nextElement();
|
||||
/*
|
||||
schema = (String) schemas.get(table);
|
||||
|
||||
if (schema != null)
|
||||
sqlBuf.append(schema + ".");
|
||||
*/
|
||||
|
||||
sqlBuf.append(table);
|
||||
sqlBuf.append(from.hasMoreElements() ? ", " : " ");
|
||||
}
|
||||
|
||||
return sqlBuf.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a SQL WHERE clause from the tables/joins Hashtable
|
||||
*
|
||||
* @return Currently, this metod will return "WHERE 1 = 1", if no other
|
||||
* WHERE conditions are specified. This can be considered a hack.
|
||||
*/
|
||||
|
||||
private String buildWhereClause() {
|
||||
|
||||
StringBuilder sqlBuf = new StringBuilder();
|
||||
|
||||
String join = null;
|
||||
boolean first = true;
|
||||
|
||||
for (Enumeration where = mTables.elements(); where.hasMoreElements();) {
|
||||
join = (String) where.nextElement();
|
||||
|
||||
if (join.length() > 0) {
|
||||
if (first) {
|
||||
// Skip " AND " in first iteration
|
||||
first = false;
|
||||
}
|
||||
else {
|
||||
sqlBuf.append(" AND ");
|
||||
}
|
||||
}
|
||||
|
||||
sqlBuf.append(join);
|
||||
}
|
||||
|
||||
if (sqlBuf.length() > 0)
|
||||
return "WHERE " + sqlBuf.toString();
|
||||
|
||||
return "WHERE 1 = 1"; // Hacky...
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds tables used in mappings and joins and adds them to the tables
|
||||
* Hashtable, with the table name as key, and the join as value.
|
||||
*/
|
||||
|
||||
private void tableJoins(String pColumn, boolean pWhereJoin) {
|
||||
String join = null;
|
||||
String table = null;
|
||||
|
||||
if (pColumn == null) {
|
||||
// Identity
|
||||
join = getIdentityJoin();
|
||||
table = getTable(getProperty(getPrimaryKey()));
|
||||
}
|
||||
else {
|
||||
// Normal
|
||||
int dotIndex = -1;
|
||||
if ((dotIndex = pColumn.lastIndexOf(".")) <= 0) {
|
||||
// No table qualifier
|
||||
return;
|
||||
}
|
||||
|
||||
// Get table qualifier.
|
||||
table = pColumn.substring(0, dotIndex);
|
||||
|
||||
// Don't care about the tables that are not supposed to be selected from
|
||||
String property = (String) getProperty(pColumn);
|
||||
|
||||
if (property != null) {
|
||||
String mapType = (String) mMapTypes.get(property);
|
||||
if (!pWhereJoin && mapType != null && !mapType.equals(DIRECTMAP)) {
|
||||
return;
|
||||
}
|
||||
|
||||
join = (String) mJoins.get(property);
|
||||
}
|
||||
}
|
||||
|
||||
// If table is not in the tables Hash, add it, and check for joins.
|
||||
if (mTables.get(table) == null) {
|
||||
if (join != null) {
|
||||
mTables.put(table, join);
|
||||
|
||||
StringTokenizer tok = new StringTokenizer(join, "= ");
|
||||
String next = null;
|
||||
|
||||
while(tok.hasMoreElements()) {
|
||||
next = tok.nextToken();
|
||||
// Don't care about SQL keywords
|
||||
if (next.equals("AND") || next.equals("OR")
|
||||
|| next.equals("NOT") || next.equals("IN")) {
|
||||
continue;
|
||||
}
|
||||
// Check for new tables and joins in this join clause.
|
||||
tableJoins(next, false);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// No joins for this table.
|
||||
join = "";
|
||||
mTables.put(table, join);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+879
@@ -0,0 +1,879 @@
|
||||
/*
|
||||
* 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.sql;
|
||||
|
||||
|
||||
import com.twelvemonkeys.lang.StringUtil;
|
||||
import com.twelvemonkeys.lang.SystemUtil;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Array;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Hashtable;
|
||||
import java.util.Properties;
|
||||
import java.util.Vector;
|
||||
|
||||
/**
|
||||
* Class used for reading table data from a database through JDBC, and map
|
||||
* the data to Java classes.
|
||||
*
|
||||
* @see ObjectMapper
|
||||
*
|
||||
* @author Harald Kuhr (haraldk@iconmedialab.no)
|
||||
* @author last modified by $Author: haku $
|
||||
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-sandbox/src/main/java/com/twelvemonkeys/sql/ObjectReader.java#1 $
|
||||
*
|
||||
* @todo Use JDK logging instead of proprietary logging.
|
||||
*
|
||||
*/
|
||||
public class ObjectReader {
|
||||
|
||||
/**
|
||||
* Main method, for testing purposes only.
|
||||
*/
|
||||
|
||||
public final static void main(String[] pArgs) throws SQLException {
|
||||
/*
|
||||
System.err.println("Testing only!");
|
||||
|
||||
// Get default connection
|
||||
ObjectReader obr = new ObjectReader(DatabaseConnection.getConnection());
|
||||
|
||||
com.twelvemonkeys.usedcars.DBCar car = new com.twelvemonkeys.usedcars.DBCar(new Integer(1));
|
||||
com.twelvemonkeys.usedcars.DBDealer dealer = new com.twelvemonkeys.usedcars.DBDealer("NO4537");
|
||||
|
||||
System.out.println(obr.readObject(dealer));
|
||||
com.twelvemonkeys.usedcars.Dealer[] dealers = (com.twelvemonkeys.usedcars.Dealer[]) obr.readObjects(dealer);
|
||||
|
||||
for (int i = 0; i < dealers.length; i++) {
|
||||
System.out.println(dealers[i]);
|
||||
}
|
||||
|
||||
System.out.println("------------------------------------------------------------------------------\n"
|
||||
+ "Total: " + dealers.length + " dealers in database\n");
|
||||
|
||||
Hashtable where = new Hashtable();
|
||||
|
||||
where.put("zipCode", "0655");
|
||||
dealers = (com.twelvemonkeys.usedcars.Dealer[]) obr.readObjects(dealer, where);
|
||||
|
||||
for (int i = 0; i < dealers.length; i++) {
|
||||
System.out.println(dealers[i]);
|
||||
}
|
||||
|
||||
System.out.println("------------------------------------------------------------------------------\n"
|
||||
+ "Total: " + dealers.length + " dealers matching query: "
|
||||
+ where + "\n");
|
||||
|
||||
|
||||
com.twelvemonkeys.usedcars.Car[] cars = null;
|
||||
cars = (com.twelvemonkeys.usedcars.Car[]) obr.readObjects(car);
|
||||
|
||||
for (int i = 0; i < cars.length; i++) {
|
||||
System.out.println(cars[i]);
|
||||
}
|
||||
|
||||
System.out.println("------------------------------------------------------------------------------\n"
|
||||
+ "Total: " + cars.length + " cars in database\n");
|
||||
|
||||
where = new Hashtable();
|
||||
where.put("year", new Integer(1995));
|
||||
cars = (com.twelvemonkeys.usedcars.Car[]) obr.readObjects(car, where);
|
||||
|
||||
for (int i = 0; i < cars.length; i++) {
|
||||
System.out.println(cars[i]);
|
||||
}
|
||||
|
||||
System.out.println("------------------------------------------------------------------------------\n"
|
||||
+ "Total: " + cars.length + " cars matching query: "
|
||||
+ where + " \n");
|
||||
|
||||
|
||||
where = new Hashtable();
|
||||
where.put("publishers", "Bilguiden");
|
||||
cars = (com.twelvemonkeys.usedcars.Car[]) obr.readObjects(car, where);
|
||||
|
||||
for (int i = 0; i < cars.length; i++) {
|
||||
System.out.println(cars[i]);
|
||||
}
|
||||
|
||||
System.out.println("------------------------------------------------------------------------------\n"
|
||||
+ "Total: " + cars.length + " cars matching query: "
|
||||
+ where + "\n");
|
||||
|
||||
System.out.println("==============================================================================\n"
|
||||
+ getStats());
|
||||
*/
|
||||
}
|
||||
|
||||
|
||||
protected Log mLog = null;
|
||||
protected Properties mConfig = null;
|
||||
|
||||
/**
|
||||
* The connection used for all database operations executed by this
|
||||
* ObjectReader.
|
||||
*/
|
||||
|
||||
Connection mConnection = null;
|
||||
|
||||
/**
|
||||
* The cache for this ObjectReader.
|
||||
* Probably a source for memory leaks, as it has no size limitations.
|
||||
*/
|
||||
|
||||
private Hashtable mCache = new Hashtable();
|
||||
|
||||
/**
|
||||
* Creates a new ObjectReader, using the given JDBC Connection. The
|
||||
* Connection will be used for all database reads by this ObjectReader.
|
||||
*
|
||||
* @param connection A JDBC Connection
|
||||
*/
|
||||
|
||||
public ObjectReader(Connection pConnection) {
|
||||
mConnection = pConnection;
|
||||
|
||||
try {
|
||||
mConfig = SystemUtil.loadProperties(getClass());
|
||||
}
|
||||
catch (FileNotFoundException fnf) {
|
||||
// Just go with defaults
|
||||
}
|
||||
catch (IOException ioe) {
|
||||
new Log(this).logError(ioe);
|
||||
}
|
||||
|
||||
mLog = new Log(this, mConfig);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a string containing the stats for this ObjectReader.
|
||||
*
|
||||
* @return A string to display the stats.
|
||||
*/
|
||||
|
||||
public static String getStats() {
|
||||
long total = sCacheHit + sCacheMiss + sCacheUn;
|
||||
double hit = ((double) sCacheHit / (double) total) * 100.0;
|
||||
double miss = ((double) sCacheMiss / (double) total) * 100.0;
|
||||
double un = ((double) sCacheUn / (double) total) * 100.0;
|
||||
|
||||
// Default locale
|
||||
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
|
||||
|
||||
return "Total: " + total + " reads. "
|
||||
+ "Cache hits: " + sCacheHit + " (" + nf.format(hit) + "%), "
|
||||
+ "Cache misses: " + sCacheMiss + " (" + nf.format(miss) + "%), "
|
||||
+ "Unattempted: " + sCacheUn + " (" + nf.format(un) + "%) ";
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an array containing Objects of type objClass, with the
|
||||
* identity values for the given class set.
|
||||
*/
|
||||
|
||||
private Object[] readIdentities(Class pObjClass, Hashtable pMapping,
|
||||
Hashtable pWhere, ObjectMapper pOM)
|
||||
throws SQLException {
|
||||
sCacheUn++;
|
||||
// Build SQL query string
|
||||
if (pWhere == null)
|
||||
pWhere = new Hashtable();
|
||||
|
||||
String[] keys = new String[pWhere.size()];
|
||||
int i = 0;
|
||||
for (Enumeration en = pWhere.keys(); en.hasMoreElements(); i++) {
|
||||
keys[i] = (String) en.nextElement();
|
||||
}
|
||||
|
||||
// Get SQL for reading identity column
|
||||
String sql = pOM.buildIdentitySQL(keys)
|
||||
+ buildWhereClause(keys, pMapping);
|
||||
|
||||
// Log?
|
||||
mLog.logDebug(sql + " (" + pWhere + ")");
|
||||
|
||||
// Prepare statement and set values
|
||||
PreparedStatement statement = mConnection.prepareStatement(sql);
|
||||
for (int j = 0; j < keys.length; j++) {
|
||||
Object key = pWhere.get(keys[j]);
|
||||
|
||||
if (key instanceof Integer)
|
||||
statement.setInt(j + 1, ((Integer) key).intValue());
|
||||
else if (key instanceof BigDecimal)
|
||||
statement.setBigDecimal(j + 1, (BigDecimal) key);
|
||||
else
|
||||
statement.setString(j + 1, key.toString());
|
||||
}
|
||||
|
||||
// Execute query
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
rs = statement.executeQuery();
|
||||
}
|
||||
catch (SQLException e) {
|
||||
mLog.logError(sql + " (" + pWhere + ")", e);
|
||||
throw e;
|
||||
}
|
||||
Vector result = new Vector();
|
||||
|
||||
// Map query to objects
|
||||
while (rs.next()) {
|
||||
Object obj = null;
|
||||
|
||||
try {
|
||||
obj = pObjClass.newInstance();
|
||||
}
|
||||
catch (IllegalAccessException iae) {
|
||||
iae.printStackTrace();
|
||||
}
|
||||
catch (InstantiationException ie) {
|
||||
ie.printStackTrace();
|
||||
}
|
||||
|
||||
// Map it
|
||||
pOM.mapColumnProperty(rs, 1,
|
||||
pOM.getProperty(pOM.getPrimaryKey()), obj);
|
||||
result.addElement(obj);
|
||||
}
|
||||
|
||||
// Return array of identifiers
|
||||
return result.toArray((Object[]) Array.newInstance(pObjClass,
|
||||
result.size()));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Reads one object implementing the DatabaseReadable interface from the
|
||||
* database.
|
||||
*
|
||||
* @param readable A DatabaseReadable object
|
||||
* @return The Object read, or null in no object is found
|
||||
*/
|
||||
|
||||
public Object readObject(DatabaseReadable pReadable) throws SQLException {
|
||||
return readObject(pReadable.getId(), pReadable.getClass(),
|
||||
pReadable.getMapping());
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the object with the given id from the database, using the given
|
||||
* mapping.
|
||||
*
|
||||
* @param id An object uniquely identifying the object to read
|
||||
* @param objClass The clas
|
||||
* @return The Object read, or null in no object is found
|
||||
*/
|
||||
|
||||
public Object readObject(Object pId, Class pObjClass, Hashtable pMapping)
|
||||
throws SQLException {
|
||||
return readObject(pId, pObjClass, pMapping, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads all the objects of the given type from the
|
||||
* database. The object must implement the DatabaseReadable interface.
|
||||
*
|
||||
* @return An array of Objects, or an zero-length array if none was found
|
||||
*/
|
||||
|
||||
public Object[] readObjects(DatabaseReadable pReadable)
|
||||
throws SQLException {
|
||||
return readObjects(pReadable.getClass(),
|
||||
pReadable.getMapping(), null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the property value to an object using reflection
|
||||
*
|
||||
* @param obj The object to get a property from
|
||||
* @param property The name of the property
|
||||
* @param value The property value
|
||||
*
|
||||
*/
|
||||
|
||||
private void setPropertyValue(Object pObj, String pProperty,
|
||||
Object pValue) {
|
||||
|
||||
Method m = null;
|
||||
Class[] cl = {pValue.getClass()};
|
||||
|
||||
try {
|
||||
//Util.setPropertyValue(pObj, pProperty, pValue);
|
||||
|
||||
// Find method
|
||||
m = pObj.getClass().
|
||||
getMethod("set" + StringUtil.capitalize(pProperty), cl);
|
||||
// Invoke it
|
||||
Object[] args = {pValue};
|
||||
m.invoke(pObj, args);
|
||||
|
||||
}
|
||||
catch (NoSuchMethodException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
catch (IllegalAccessException iae) {
|
||||
iae.printStackTrace();
|
||||
}
|
||||
catch (InvocationTargetException ite) {
|
||||
ite.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the property value from an object using reflection
|
||||
*
|
||||
* @param obj The object to get a property from
|
||||
* @param property The name of the property
|
||||
*
|
||||
* @return The property value as an Object
|
||||
*/
|
||||
|
||||
private Object getPropertyValue(Object pObj, String pProperty) {
|
||||
|
||||
Method m = null;
|
||||
Class[] cl = new Class[0];
|
||||
|
||||
try {
|
||||
//return Util.getPropertyValue(pObj, pProperty);
|
||||
|
||||
// Find method
|
||||
m = pObj.getClass().
|
||||
getMethod("get" + StringUtil.capitalize(pProperty),
|
||||
new Class[0]);
|
||||
// Invoke it
|
||||
Object result = m.invoke(pObj, new Object[0]);
|
||||
return result;
|
||||
|
||||
}
|
||||
catch (NoSuchMethodException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
catch (IllegalAccessException iae) {
|
||||
iae.printStackTrace();
|
||||
}
|
||||
catch (InvocationTargetException ite) {
|
||||
ite.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads and sets the child properties of the given parent object.
|
||||
*
|
||||
* @param parent The object to set the child obects to.
|
||||
* @param om The ObjectMapper of the parent object.
|
||||
*/
|
||||
|
||||
private void setChildObjects(Object pParent, ObjectMapper pOM)
|
||||
throws SQLException {
|
||||
if (pOM == null) {
|
||||
throw new NullPointerException("ObjectMapper in readChildObjects "
|
||||
+ "cannot be null!!");
|
||||
}
|
||||
|
||||
for (Enumeration keys = pOM.mMapTypes.keys(); keys.hasMoreElements();) {
|
||||
String property = (String) keys.nextElement();
|
||||
String mapType = (String) pOM.mMapTypes.get(property);
|
||||
|
||||
if (property.length() <= 0 || mapType == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get the id of the parent
|
||||
Object id = getPropertyValue(pParent,
|
||||
pOM.getProperty(pOM.getPrimaryKey()));
|
||||
|
||||
if (mapType.equals(ObjectMapper.OBJECTMAP)) {
|
||||
// OBJECT Mapping
|
||||
|
||||
// Get the class for this property
|
||||
Class objectClass = (Class) pOM.mClasses.get(property);
|
||||
|
||||
DatabaseReadable dbr = null;
|
||||
try {
|
||||
dbr = (DatabaseReadable) objectClass.newInstance();
|
||||
}
|
||||
catch (Exception e) {
|
||||
mLog.logError(e);
|
||||
}
|
||||
|
||||
/*
|
||||
Properties mapping = readMapping(objectClass);
|
||||
*/
|
||||
|
||||
// Get property mapping for child object
|
||||
if (pOM.mJoins.containsKey(property))
|
||||
// mapping.setProperty(".join", (String) pOM.joins.get(property));
|
||||
dbr.getMapping().put(".join", pOM.mJoins.get(property));
|
||||
|
||||
// Find id and put in where hash
|
||||
Hashtable where = new Hashtable();
|
||||
|
||||
// String foreignKey = mapping.getProperty(".foreignKey");
|
||||
String foreignKey = (String)
|
||||
dbr.getMapping().get(".foreignKey");
|
||||
|
||||
if (foreignKey != null) {
|
||||
where.put(".foreignKey", id);
|
||||
}
|
||||
|
||||
Object[] child = readObjects(dbr, where);
|
||||
// Object[] child = readObjects(objectClass, mapping, where);
|
||||
|
||||
if (child.length < 1)
|
||||
throw new SQLException("No child object with foreign key "
|
||||
+ foreignKey + "=" + id);
|
||||
else if (child.length != 1)
|
||||
throw new SQLException("More than one object with foreign "
|
||||
+ "key " + foreignKey + "=" + id);
|
||||
|
||||
// Set child object to the parent
|
||||
setPropertyValue(pParent, property, child[0]);
|
||||
}
|
||||
else if (mapType.equals(ObjectMapper.COLLECTIONMAP)) {
|
||||
// COLLECTION Mapping
|
||||
|
||||
// Get property mapping for child object
|
||||
Hashtable mapping = pOM.getPropertyMapping(property);
|
||||
|
||||
// Find id and put in where hash
|
||||
Hashtable where = new Hashtable();
|
||||
String foreignKey = (String) mapping.get(".foreignKey");
|
||||
if (foreignKey != null) {
|
||||
where.put(".foreignKey", id);
|
||||
}
|
||||
|
||||
DBObject dbr = new DBObject();
|
||||
dbr.mapping = mapping; // ugh...
|
||||
// Read the objects
|
||||
Object[] objs = readObjects(dbr, where);
|
||||
|
||||
// Put the objects in a hash
|
||||
Hashtable children = new Hashtable();
|
||||
for (int i = 0; i < objs.length; i++) {
|
||||
children.put(((DBObject) objs[i]).getId(),
|
||||
((DBObject) objs[i]).getObject());
|
||||
}
|
||||
|
||||
// Set child properties to parent object
|
||||
setPropertyValue(pParent, property, children);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads all objects from the database, using the given mapping.
|
||||
*
|
||||
* @param objClass The class of the objects to read
|
||||
* @param mapping The hashtable containing the object mapping
|
||||
*
|
||||
* @return An array of Objects, or an zero-length array if none was found
|
||||
*/
|
||||
|
||||
public Object[] readObjects(Class pObjClass, Hashtable pMapping)
|
||||
throws SQLException {
|
||||
return readObjects(pObjClass, pMapping, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds extra SQL WHERE clause
|
||||
*
|
||||
* @param keys An array of ID names
|
||||
* @param mapping The hashtable containing the object mapping
|
||||
*
|
||||
* @return A string containing valid SQL
|
||||
*/
|
||||
|
||||
private String buildWhereClause(String[] pKeys, Hashtable pMapping) {
|
||||
StringBuilder sqlBuf = new StringBuilder();
|
||||
|
||||
for (int i = 0; i < pKeys.length; i++) {
|
||||
String column = (String) pMapping.get(pKeys[i]);
|
||||
sqlBuf.append(" AND ");
|
||||
sqlBuf.append(column);
|
||||
sqlBuf.append(" = ?");
|
||||
}
|
||||
|
||||
return sqlBuf.toString();
|
||||
|
||||
}
|
||||
|
||||
private String buildIdInClause(Object[] pIds, Hashtable pMapping) {
|
||||
StringBuilder sqlBuf = new StringBuilder();
|
||||
|
||||
if (pIds != null && pIds.length > 0) {
|
||||
sqlBuf.append(" AND ");
|
||||
sqlBuf.append(pMapping.get(".primaryKey"));
|
||||
sqlBuf.append(" IN (");
|
||||
|
||||
for (int i = 0; i < pIds.length; i++) {
|
||||
sqlBuf.append(pIds[i]); // SETTE INN '?' ???
|
||||
sqlBuf.append(", ");
|
||||
}
|
||||
sqlBuf.append(")");
|
||||
}
|
||||
|
||||
return sqlBuf.toString();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads all objects from the database, using the given mapping.
|
||||
*
|
||||
* @param readable A DatabaseReadable object
|
||||
* @param mapping The hashtable containing the object mapping
|
||||
*
|
||||
* @return An array of Objects, or an zero-length array if none was found
|
||||
*/
|
||||
|
||||
public Object[] readObjects(DatabaseReadable pReadable, Hashtable pWhere)
|
||||
throws SQLException {
|
||||
return readObjects(pReadable.getClass(),
|
||||
pReadable.getMapping(), pWhere);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Reads the object with the given id from the database, using the given
|
||||
* mapping.
|
||||
* This is the most general form of readObject().
|
||||
*
|
||||
* @param id An object uniquely identifying the object to read
|
||||
* @param objClass The class of the object to read
|
||||
* @param mapping The hashtable containing the object mapping
|
||||
* @param where An hashtable containing extra criteria for the read
|
||||
*
|
||||
* @return An array of Objects, or an zero-length array if none was found
|
||||
*/
|
||||
|
||||
public Object readObject(Object pId, Class pObjClass,
|
||||
Hashtable pMapping, Hashtable pWhere)
|
||||
throws SQLException {
|
||||
ObjectMapper om = new ObjectMapper(pObjClass, pMapping);
|
||||
return readObject0(pId, pObjClass, om, pWhere);
|
||||
}
|
||||
|
||||
public Object readObjects(Object[] pIds, Class pObjClass,
|
||||
Hashtable pMapping, Hashtable pWhere)
|
||||
throws SQLException {
|
||||
ObjectMapper om = new ObjectMapper(pObjClass, pMapping);
|
||||
return readObjects0(pIds, pObjClass, om, pWhere);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads all objects from the database, using the given mapping.
|
||||
* This is the most general form of readObjects().
|
||||
*
|
||||
* @param objClass The class of the objects to read
|
||||
* @param mapping The hashtable containing the object mapping
|
||||
* @param where An hashtable containing extra criteria for the read
|
||||
*
|
||||
* @return An array of Objects, or an zero-length array if none was found
|
||||
*/
|
||||
|
||||
public Object[] readObjects(Class pObjClass, Hashtable pMapping,
|
||||
Hashtable pWhere) throws SQLException {
|
||||
return readObjects0(pObjClass, pMapping, pWhere);
|
||||
}
|
||||
|
||||
// readObjects implementation
|
||||
|
||||
private Object[] readObjects0(Class pObjClass, Hashtable pMapping,
|
||||
Hashtable pWhere) throws SQLException {
|
||||
ObjectMapper om = new ObjectMapper(pObjClass, pMapping);
|
||||
|
||||
Object[] ids = readIdentities(pObjClass, pMapping, pWhere, om);
|
||||
|
||||
Object[] result = readObjects0(ids, pObjClass, om, pWhere);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private Object[] readObjects0(Object[] pIds, Class pObjClass,
|
||||
ObjectMapper pOM, Hashtable pWhere)
|
||||
throws SQLException {
|
||||
Object[] result = new Object[pIds.length];
|
||||
|
||||
// Read each object from ID
|
||||
for (int i = 0; i < pIds.length; i++) {
|
||||
|
||||
// TODO: For better cahce efficiency/performance:
|
||||
// - Read as many objects from cache as possible
|
||||
// - Read all others in ONE query, and add to cache
|
||||
/*
|
||||
sCacheUn++;
|
||||
// Build SQL query string
|
||||
if (pWhere == null)
|
||||
pWhere = new Hashtable();
|
||||
|
||||
String[] keys = new String[pWhere.size()];
|
||||
int i = 0;
|
||||
for (Enumeration en = pWhere.keys(); en.hasMoreElements(); i++) {
|
||||
keys[i] = (String) en.nextElement();
|
||||
}
|
||||
|
||||
// Get SQL for reading identity column
|
||||
String sql = pOM.buildSelectClause() + pOM.buildFromClause() +
|
||||
+ buildWhereClause(keys, pMapping) + buildIdInClause(pIds, pMapping);
|
||||
|
||||
// Log?
|
||||
mLog.logDebug(sql + " (" + pWhere + ")");
|
||||
|
||||
|
||||
// Log?
|
||||
mLog.logDebug(sql + " (" + pWhere + ")");
|
||||
|
||||
PreparedStatement statement = null;
|
||||
|
||||
// Execute query, and map columns/properties
|
||||
try {
|
||||
statement = mConnection.prepareStatement(sql);
|
||||
|
||||
// Set keys
|
||||
for (int j = 0; j < keys.length; j++) {
|
||||
Object value = pWhere.get(keys[j]);
|
||||
|
||||
if (value instanceof Integer)
|
||||
statement.setInt(j + 1, ((Integer) value).intValue());
|
||||
else if (value instanceof BigDecimal)
|
||||
statement.setBigDecimal(j + 1, (BigDecimal) value);
|
||||
else
|
||||
statement.setString(j + 1, value.toString());
|
||||
}
|
||||
// Set ids
|
||||
for (int j = 0; j < pIds.length; j++) {
|
||||
Object id = pIds[i];
|
||||
|
||||
if (id instanceof Integer)
|
||||
statement.setInt(j + 1, ((Integer) id).intValue());
|
||||
else if (id instanceof BigDecimal)
|
||||
statement.setBigDecimal(j + 1, (BigDecimal) id);
|
||||
else
|
||||
statement.setString(j + 1, id.toString());
|
||||
}
|
||||
|
||||
ResultSet rs = statement.executeQuery();
|
||||
|
||||
Object[] result = pOM.mapObjects(rs);
|
||||
|
||||
// Set child objects and return
|
||||
for (int i = 0; i < result.length; i++) {
|
||||
// FOR THIS TO REALLY GET EFFECTIVE, WE NEED TO SET ALL
|
||||
// CHILDREN IN ONE GO!
|
||||
setChildObjects(result[i], pOM);
|
||||
mContent.put(pOM.getPrimaryKey() + "=" + pId, result[0]);
|
||||
|
||||
}
|
||||
// Return result
|
||||
return result[0];
|
||||
|
||||
}
|
||||
*/
|
||||
|
||||
Object id = getPropertyValue(result[i],
|
||||
pOM.getProperty(pOM.getPrimaryKey()));
|
||||
|
||||
result[i] = readObject0(id, pObjClass, pOM, null);
|
||||
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// readObject implementation, used for ALL database reads
|
||||
|
||||
static long sCacheHit;
|
||||
static long sCacheMiss;
|
||||
static long sCacheUn;
|
||||
|
||||
private Object readObject0(Object pId, Class pObjClass, ObjectMapper pOM,
|
||||
Hashtable pWhere) throws SQLException {
|
||||
if (pId == null && pWhere == null)
|
||||
throw new IllegalArgumentException("Either id or where argument"
|
||||
+ "must be non-null!");
|
||||
|
||||
// First check if object exists in cache
|
||||
if (pId != null) {
|
||||
Object o = mCache.get(pOM.getPrimaryKey() + "=" + pId);
|
||||
if (o != null) {
|
||||
sCacheHit++;
|
||||
return o;
|
||||
}
|
||||
sCacheMiss++;
|
||||
}
|
||||
else {
|
||||
sCacheUn++;
|
||||
}
|
||||
|
||||
// Create where hash
|
||||
if (pWhere == null)
|
||||
pWhere = new Hashtable();
|
||||
|
||||
// Make sure the ID is in the where hash
|
||||
if (pId != null)
|
||||
pWhere.put(pOM.getProperty(pOM.getPrimaryKey()), pId);
|
||||
|
||||
String[] keys = new String[pWhere.size()];
|
||||
Enumeration en = pWhere.keys();
|
||||
for (int i = 0; en.hasMoreElements(); i++) {
|
||||
keys[i] = (String) en.nextElement();
|
||||
}
|
||||
|
||||
// Get SQL query string
|
||||
String sql = pOM.buildSQL() + buildWhereClause(keys, pOM.mPropertiesMap);
|
||||
|
||||
// Log?
|
||||
mLog.logDebug(sql + " (" + pWhere + ")");
|
||||
|
||||
PreparedStatement statement = null;
|
||||
|
||||
// Execute query, and map columns/properties
|
||||
try {
|
||||
statement = mConnection.prepareStatement(sql);
|
||||
|
||||
for (int j = 0; j < keys.length; j++) {
|
||||
Object value = pWhere.get(keys[j]);
|
||||
|
||||
if (value instanceof Integer)
|
||||
statement.setInt(j + 1, ((Integer) value).intValue());
|
||||
else if (value instanceof BigDecimal)
|
||||
statement.setBigDecimal(j + 1, (BigDecimal) value);
|
||||
else
|
||||
statement.setString(j + 1, value.toString());
|
||||
}
|
||||
|
||||
ResultSet rs = statement.executeQuery();
|
||||
|
||||
Object[] result = pOM.mapObjects(rs);
|
||||
|
||||
// Set child objects and return
|
||||
if (result.length == 1) {
|
||||
setChildObjects(result[0], pOM);
|
||||
mCache.put(pOM.getPrimaryKey() + "=" + pId, result[0]);
|
||||
|
||||
// Return result
|
||||
return result[0];
|
||||
}
|
||||
// More than 1 is an error...
|
||||
else if (result.length > 1) {
|
||||
throw new SQLException("More than one object with primary key "
|
||||
+ pOM.getPrimaryKey() + "="
|
||||
+ pWhere.get(pOM.getProperty(pOM.getPrimaryKey())) + "!");
|
||||
}
|
||||
}
|
||||
catch (SQLException e) {
|
||||
mLog.logError(sql + " (" + pWhere + ")", e);
|
||||
throw e;
|
||||
}
|
||||
finally {
|
||||
try {
|
||||
statement.close();
|
||||
}
|
||||
catch (SQLException e) {
|
||||
mLog.logError(e);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method for reading a property mapping from a properties-file
|
||||
*
|
||||
*/
|
||||
|
||||
public static Properties loadMapping(Class pClass) {
|
||||
try {
|
||||
return SystemUtil.loadProperties(pClass);
|
||||
}
|
||||
catch (FileNotFoundException fnf) {
|
||||
// System.err... err...
|
||||
System.err.println("ERROR: " + fnf.getMessage());
|
||||
}
|
||||
catch (IOException ioe) {
|
||||
ioe.printStackTrace();
|
||||
}
|
||||
return new Properties();
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use loadMapping(Class) instead
|
||||
* @see #loadMapping(Class)
|
||||
*/
|
||||
|
||||
public static Properties readMapping(Class pClass) {
|
||||
return loadMapping(pClass);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility class
|
||||
*/
|
||||
|
||||
class DBObject implements DatabaseReadable {
|
||||
Object id;
|
||||
Object o;
|
||||
static Hashtable mapping; // WHOA, STATIC!?!?
|
||||
|
||||
public DBObject() {
|
||||
}
|
||||
|
||||
public void setId(Object id) {
|
||||
this.id = id;
|
||||
}
|
||||
public Object getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setObject(Object o) {
|
||||
this.o = o;
|
||||
}
|
||||
public Object getObject() {
|
||||
return o;
|
||||
}
|
||||
|
||||
public Hashtable getMapping() {
|
||||
return mapping;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,396 @@
|
||||
/*
|
||||
* 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.sql;
|
||||
|
||||
import com.twelvemonkeys.lang.StringUtil;
|
||||
|
||||
import java.sql.*;
|
||||
import java.io.*;
|
||||
import java.util.Properties;
|
||||
|
||||
|
||||
/**
|
||||
* A class used to test a JDBC database connection. It can also be used as a
|
||||
* really simple form of command line SQL interface, that passes all command
|
||||
* line parameters to the database as plain SQL, and returns all rows to
|
||||
* Sytem.out. <EM>Be aware that the wildcard character (*) is intercepted by
|
||||
* the console, so you have to quote your string, or escape the wildcard
|
||||
* character, otherwise you may get unpredictable results.</EM>
|
||||
* <P/>
|
||||
* <STRONG>Exmaple use</STRONG>
|
||||
* <BR/>
|
||||
* <PRE>
|
||||
* $ java -cp lib\jconn2.jar;build com.twelvemonkeys.sql.SQLUtil
|
||||
* -d com.sybase.jdbc2.jdbc.SybDriver -u "jdbc:sybase:Tds:10.248.136.42:6100"
|
||||
* -l scott -p tiger "SELECT * FROM emp"</PRE>
|
||||
* <EM>Make sure sure to include the path to your JDBC driver in the java class
|
||||
* path!</EM>
|
||||
*
|
||||
* @author Philippe Béal (phbe@iconmedialab.no)
|
||||
* @author Harald Kuhr (haraldk@iconmedialab.no)
|
||||
* @author last modified by $author: WMHAKUR $
|
||||
* @version $id: $
|
||||
* @see DatabaseConnection
|
||||
*/
|
||||
public class SQLUtil {
|
||||
/**
|
||||
* Method main
|
||||
*
|
||||
* @param pArgs
|
||||
* @throws SQLException
|
||||
*
|
||||
* @todo Refactor the long and ugly main method...
|
||||
* Consider: - extract method parserArgs(String[])::Properties (how do we
|
||||
* get the rest of the arguments? getProperty("_ARGV")?
|
||||
* Make the Properties/Map an argument and return int with last
|
||||
* option index?
|
||||
* - extract method getStatementReader(Properties)
|
||||
*/
|
||||
public static void main(String[] pArgs) throws SQLException, IOException {
|
||||
String user = null;
|
||||
String password = null;
|
||||
String url = null;
|
||||
String driver = null;
|
||||
String configFileName = null;
|
||||
String scriptFileName = null;
|
||||
String scriptSQLDelim = "go";
|
||||
int argIdx = 0;
|
||||
boolean errArgs = false;
|
||||
|
||||
while ((argIdx < pArgs.length) && (pArgs[argIdx].charAt(0) == '-') && (pArgs[argIdx].length() >= 2)) {
|
||||
if ((pArgs[argIdx].charAt(1) == 'l') || pArgs[argIdx].equals("--login")) {
|
||||
argIdx++;
|
||||
user = pArgs[argIdx++];
|
||||
}
|
||||
else if ((pArgs[argIdx].charAt(1) == 'p') || pArgs[argIdx].equals("--password")) {
|
||||
argIdx++;
|
||||
password = pArgs[argIdx++];
|
||||
}
|
||||
else if ((pArgs[argIdx].charAt(1) == 'u') || pArgs[argIdx].equals("--url")) {
|
||||
argIdx++;
|
||||
url = pArgs[argIdx++];
|
||||
}
|
||||
else if ((pArgs[argIdx].charAt(1) == 'd') || pArgs[argIdx].equals("--driver")) {
|
||||
argIdx++;
|
||||
driver = pArgs[argIdx++];
|
||||
}
|
||||
else if ((pArgs[argIdx].charAt(1) == 'c') || pArgs[argIdx].equals("--config")) {
|
||||
argIdx++;
|
||||
configFileName = pArgs[argIdx++];
|
||||
}
|
||||
else if ((pArgs[argIdx].charAt(1) == 's') || pArgs[argIdx].equals("--script")) {
|
||||
argIdx++;
|
||||
scriptFileName = pArgs[argIdx++];
|
||||
}
|
||||
else if ((pArgs[argIdx].charAt(1) == 'h') || pArgs[argIdx].equals("--help")) {
|
||||
argIdx++;
|
||||
errArgs = true;
|
||||
}
|
||||
else {
|
||||
System.err.println("Unknown option \"" + pArgs[argIdx++] + "\"");
|
||||
}
|
||||
}
|
||||
if (errArgs || (scriptFileName == null && (pArgs.length < (argIdx + 1)))) {
|
||||
System.err.println("Usage: SQLUtil [--help|-h] [--login|-l <login-name>] [--password|-p <password>] [--driver|-d <jdbc-driver-class>] [--url|-u <connect url>] [--config|-c <config-file>] [--script|-s <script-file>] <sql statement> ");
|
||||
System.exit(5);
|
||||
}
|
||||
|
||||
// If config file, read config and use as defaults
|
||||
// NOTE: Command line options override!
|
||||
if (!StringUtil.isEmpty(configFileName)) {
|
||||
Properties config = new Properties();
|
||||
File configFile = new File(configFileName);
|
||||
if (!configFile.exists()) {
|
||||
System.err.println("Config file " + configFile.getAbsolutePath() + " does not exist.");
|
||||
System.exit(10);
|
||||
}
|
||||
|
||||
InputStream in = new FileInputStream(configFile);
|
||||
try {
|
||||
config.load(in);
|
||||
}
|
||||
finally {
|
||||
in.close();
|
||||
}
|
||||
|
||||
if (driver == null) {
|
||||
driver = config.getProperty("driver");
|
||||
}
|
||||
if (url == null) {
|
||||
url = config.getProperty("url");
|
||||
}
|
||||
if (user == null) {
|
||||
user = config.getProperty("login");
|
||||
}
|
||||
if (password == null) {
|
||||
password = config.getProperty("password");
|
||||
}
|
||||
}
|
||||
|
||||
// Register JDBC driver
|
||||
if (driver != null) {
|
||||
registerDriver(driver);
|
||||
}
|
||||
Connection conn = null;
|
||||
|
||||
try {
|
||||
// Use default connection from DatabaseConnection.properties
|
||||
conn = DatabaseConnection.getConnection(user, password, url);
|
||||
if (conn == null) {
|
||||
System.err.println("No connection.");
|
||||
System.exit(10);
|
||||
}
|
||||
|
||||
BufferedReader reader;
|
||||
if (scriptFileName != null) {
|
||||
// Read SQL from file
|
||||
File file = new File(scriptFileName);
|
||||
if (!file.exists()) {
|
||||
System.err.println("Script file " + file.getAbsolutePath() + " does not exist.");
|
||||
System.exit(10);
|
||||
}
|
||||
|
||||
reader = new BufferedReader(new FileReader(file));
|
||||
}
|
||||
else {
|
||||
// Create SQL statement from command line params
|
||||
StringBuilder sql = new StringBuilder();
|
||||
for (int i = argIdx; i < pArgs.length; i++) {
|
||||
sql.append(pArgs[i]).append(" ");
|
||||
}
|
||||
|
||||
reader = new BufferedReader(new StringReader(sql.toString()));
|
||||
}
|
||||
|
||||
//reader.mark(10000000);
|
||||
//for (int i = 0; i < 5; i++) {
|
||||
StringBuilder sql = new StringBuilder();
|
||||
while (true) {
|
||||
// Read next line
|
||||
String line = reader.readLine();
|
||||
if (line == null) {
|
||||
// End of file, execute and quit
|
||||
String str = sql.toString();
|
||||
if (!StringUtil.isEmpty(str)) {
|
||||
executeSQL(str, conn);
|
||||
}
|
||||
break;
|
||||
}
|
||||
else if (line.trim().endsWith(scriptSQLDelim)) {
|
||||
// End of statement, execute and continue
|
||||
sql.append(line.substring(0, line.lastIndexOf(scriptSQLDelim)));
|
||||
executeSQL(sql.toString(), conn);
|
||||
sql.setLength(0);
|
||||
}
|
||||
else {
|
||||
sql.append(line).append(" ");
|
||||
}
|
||||
}
|
||||
//reader.reset();
|
||||
//}
|
||||
}
|
||||
finally {
|
||||
// Close the connection
|
||||
if (conn != null) {
|
||||
conn.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void executeSQL(String pSQL, Connection pConn) throws SQLException {
|
||||
System.out.println("Executing: " + pSQL);
|
||||
|
||||
Statement stmt = null;
|
||||
try {
|
||||
// NOTE: Experimental
|
||||
//stmt = pConn.prepareCall(pSQL);
|
||||
//boolean results = ((CallableStatement) stmt).execute();
|
||||
|
||||
// Create statement and execute
|
||||
stmt = pConn.createStatement();
|
||||
boolean results = stmt.execute(pSQL);
|
||||
|
||||
int updateCount = -1;
|
||||
|
||||
SQLWarning warning = stmt.getWarnings();
|
||||
while (warning != null) {
|
||||
System.out.println("Warning: " + warning.getMessage());
|
||||
warning = warning.getNextWarning();
|
||||
}
|
||||
|
||||
// More result sets to process?
|
||||
while (results || (updateCount = stmt.getUpdateCount()) != -1) {
|
||||
// INSERT, UPDATE or DELETE statement (no result set).
|
||||
if (!results && (updateCount >= 0)) {
|
||||
System.out.println("Operation successfull. " + updateCount + " row" + ((updateCount != 1) ? "s" : "") + " affected.");
|
||||
System.out.println();
|
||||
}
|
||||
// SELECT statement or stored procedure
|
||||
else {
|
||||
processResultSet(stmt.getResultSet());
|
||||
}
|
||||
|
||||
// More results?
|
||||
results = stmt.getMoreResults();
|
||||
}
|
||||
}
|
||||
catch (SQLException sqle) {
|
||||
System.err.println("Error: " + sqle.getMessage());
|
||||
while ((sqle = sqle.getNextException()) != null) {
|
||||
System.err.println(" " + sqle);
|
||||
}
|
||||
}
|
||||
finally {
|
||||
// Close the statement
|
||||
if (stmt != null) {
|
||||
stmt.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Create interface ResultSetProcessor
|
||||
// -- processWarnings(SQLWarning pWarnings);
|
||||
// -- processMetaData(ResultSetMetaData pMetas); ??
|
||||
// -- processResultSet(ResultSet pResult);
|
||||
// TODO: Add parameter pResultSetProcessor to method
|
||||
// TODO: Extract contents of this method to class Default/CLIRSP
|
||||
// TODO: Create new class JTableRSP that creates (?) and populates a JTable
|
||||
// or a TableModel (?)
|
||||
private static void processResultSet(ResultSet pResultSet) throws SQLException {
|
||||
try {
|
||||
// Get meta data
|
||||
ResultSetMetaData meta = pResultSet.getMetaData();
|
||||
|
||||
// Print any warnings that might have occured
|
||||
SQLWarning warning = pResultSet.getWarnings();
|
||||
while (warning != null) {
|
||||
System.out.println("Warning: " + warning.getMessage());
|
||||
warning = warning.getNextWarning();
|
||||
}
|
||||
|
||||
// Get the number of columns in the result set
|
||||
int numCols = meta.getColumnCount();
|
||||
|
||||
for (int i = 1; i <= numCols; i++) {
|
||||
boolean prepend = isNumeric(meta.getColumnType(i));
|
||||
|
||||
String label = maybePad(meta.getColumnLabel(i), meta.getColumnDisplaySize(i), " ", prepend);
|
||||
|
||||
System.out.print(label + "\t");
|
||||
}
|
||||
System.out.println();
|
||||
for (int i = 1; i <= numCols; i++) {
|
||||
boolean prepend = isNumeric(meta.getColumnType(i));
|
||||
String label = maybePad("(" + meta.getColumnTypeName(i) + "/" + meta.getColumnClassName(i) + ")", meta.getColumnDisplaySize(i), " ", prepend);
|
||||
System.out.print(label + "\t");
|
||||
}
|
||||
System.out.println();
|
||||
for (int i = 1; i <= numCols; i++) {
|
||||
String label = maybePad("", meta.getColumnDisplaySize(i), "-", false);
|
||||
System.out.print(label + "\t");
|
||||
}
|
||||
System.out.println();
|
||||
while (pResultSet.next()) {
|
||||
for (int i = 1; i <= numCols; i++) {
|
||||
boolean prepend = isNumeric(meta.getColumnType(i));
|
||||
String value = maybePad(String.valueOf(pResultSet.getString(i)), meta.getColumnDisplaySize(i), " ", prepend);
|
||||
System.out.print(value + "\t");
|
||||
//System.out.print(pResultSet.getString(i) + "\t");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
catch (SQLException sqle) {
|
||||
System.err.println("Error: " + sqle.getMessage());
|
||||
while ((sqle = sqle.getNextException()) != null) {
|
||||
System.err.println(" " + sqle);
|
||||
}
|
||||
throw sqle;
|
||||
}
|
||||
finally {
|
||||
if (pResultSet != null) {
|
||||
pResultSet.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String maybePad(String pString, int pColumnDisplaySize, String pPad, boolean pPrepend) {
|
||||
String padded;
|
||||
if (pColumnDisplaySize < 100) {
|
||||
padded = StringUtil.pad(pString, pColumnDisplaySize, pPad, pPrepend);
|
||||
}
|
||||
else {
|
||||
padded = StringUtil.pad(pString, 100, pPad, pPrepend);
|
||||
}
|
||||
return padded;
|
||||
}
|
||||
|
||||
private static boolean isNumeric(int pColumnType) {
|
||||
return (pColumnType == Types.INTEGER || pColumnType == Types.DECIMAL
|
||||
|| pColumnType == Types.TINYINT || pColumnType == Types.BIGINT
|
||||
|| pColumnType == Types.DOUBLE || pColumnType == Types.FLOAT
|
||||
|| pColumnType == Types.NUMERIC || pColumnType == Types.REAL
|
||||
|| pColumnType == Types.SMALLINT);
|
||||
}
|
||||
|
||||
public static boolean isDriverAvailable(String pDriver) {
|
||||
//ClassLoader loader = Thread.currentThread().getContextClassLoader();
|
||||
try {
|
||||
Class.forName(pDriver, false, null); // null means the caller's ClassLoader
|
||||
return true;
|
||||
}
|
||||
catch (ClassNotFoundException ignore) {
|
||||
// Ignore
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void registerDriver(String pDriver) {
|
||||
// Register JDBC driver
|
||||
try {
|
||||
Class.forName(pDriver).newInstance();
|
||||
}
|
||||
catch (ClassNotFoundException e) {
|
||||
throw new RuntimeException("Driver class not found: " + e.getMessage(), e);
|
||||
//System.err.println("Driver class not found: " + e.getMessage());
|
||||
//System.exit(5);
|
||||
}
|
||||
catch (InstantiationException e) {
|
||||
throw new RuntimeException("Driver class could not be instantiated: " + e.getMessage(), e);
|
||||
//System.err.println("Driver class could not be instantiated: " + e.getMessage());
|
||||
//System.exit(5);
|
||||
}
|
||||
catch (IllegalAccessException e) {
|
||||
throw new RuntimeException("Driver class could not be instantiated: " + e.getMessage(), e);
|
||||
//System.err.println("Driver class could not be instantiated: " + e.getMessage());
|
||||
//System.exit(5);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<HTML>
|
||||
|
||||
<BODY>
|
||||
Provides classes for database access through JDBC.
|
||||
The package contains warious mechanisms to et connections, read (currently) and write (future) objects from a database, etc.
|
||||
|
||||
@see java.sql
|
||||
@see com.twelvemonkeys.sql.ObjectReader
|
||||
@see com.twelvemonkeys.sql.DatabaseConnection
|
||||
|
||||
</BODY>
|
||||
</HTML>
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* AbstractResource class description.
|
||||
*
|
||||
* @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/util/AbstractResource.java#1 $
|
||||
*/
|
||||
abstract class AbstractResource implements Resource {
|
||||
protected final Object resourceId;
|
||||
protected final Object wrappedResource;
|
||||
|
||||
/**
|
||||
* Creates a {@code Resource}.
|
||||
*
|
||||
* @param pResourceId
|
||||
* @param pWrappedResource
|
||||
*/
|
||||
protected AbstractResource(Object pResourceId, Object pWrappedResource) {
|
||||
if (pResourceId == null) {
|
||||
throw new IllegalArgumentException("id == null");
|
||||
}
|
||||
if (pWrappedResource == null) {
|
||||
throw new IllegalArgumentException("resource == null");
|
||||
}
|
||||
|
||||
resourceId = pResourceId;
|
||||
wrappedResource = pWrappedResource;
|
||||
}
|
||||
|
||||
public final Object getId() {
|
||||
return resourceId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default implementation simply returns {@code asURL().toExternalForm()}.
|
||||
*
|
||||
* @return a string representation of this resource
|
||||
*/
|
||||
public String toString() {
|
||||
return asURL().toExternalForm();
|
||||
}
|
||||
|
||||
/**
|
||||
* Defautl implementation returns {@code mWrapped.hashCode()}.
|
||||
*
|
||||
* @return {@code mWrapped.hashCode()}
|
||||
*/
|
||||
public int hashCode() {
|
||||
return wrappedResource.hashCode();
|
||||
}
|
||||
|
||||
/**
|
||||
* Default implementation
|
||||
*
|
||||
* @param pObject
|
||||
* @return
|
||||
*/
|
||||
public boolean equals(Object pObject) {
|
||||
return pObject instanceof AbstractResource
|
||||
&& wrappedResource.equals(((AbstractResource) pObject).wrappedResource);
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* BooleanKey class description.
|
||||
*
|
||||
* @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/util/BooleanKey.java#1 $
|
||||
*/
|
||||
public class BooleanKey extends TypedMap.AbstractKey implements Serializable {
|
||||
public BooleanKey() {
|
||||
super();
|
||||
}
|
||||
|
||||
public BooleanKey(String pName) {
|
||||
super(pName);
|
||||
}
|
||||
|
||||
public boolean isCompatibleValue(Object pValue) {
|
||||
return pValue instanceof Boolean;
|
||||
}
|
||||
}
|
||||
+1757
File diff suppressed because it is too large
Load Diff
+78
@@ -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.util;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
* FileResource class description.
|
||||
*
|
||||
* @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/util/FileResource.java#1 $
|
||||
*/
|
||||
final class FileResource extends AbstractResource {
|
||||
|
||||
/**
|
||||
* Creates a {@code FileResource}.
|
||||
*
|
||||
* @param pResourceId the resource id
|
||||
* @param pFile the file resource
|
||||
*/
|
||||
public FileResource(Object pResourceId, File pFile) {
|
||||
super(pResourceId, pFile);
|
||||
}
|
||||
|
||||
private File getFile() {
|
||||
return (File) wrappedResource;
|
||||
}
|
||||
|
||||
public URL asURL() {
|
||||
try {
|
||||
return getFile().toURL();
|
||||
}
|
||||
catch (MalformedURLException e) {
|
||||
throw new IllegalStateException("The file \"" + getFile().getAbsolutePath()
|
||||
+ "\" is not parseable as an URL: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public InputStream asStream() throws IOException {
|
||||
return new FileInputStream(getFile());
|
||||
}
|
||||
|
||||
public long lastModified() {
|
||||
return getFile().lastModified();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* FloatKey class description.
|
||||
*
|
||||
* @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/util/FloatKey.java#1 $
|
||||
*/
|
||||
public class FloatKey extends TypedMap.AbstractKey implements Serializable {
|
||||
public FloatKey() {
|
||||
super();
|
||||
}
|
||||
|
||||
public FloatKey(String pName) {
|
||||
super(pName);
|
||||
}
|
||||
|
||||
public boolean isCompatibleValue(Object pValue) {
|
||||
return pValue instanceof Float;
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* IntegerKey class description.
|
||||
*
|
||||
* @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/util/IntegerKey.java#1 $
|
||||
*/
|
||||
public class IntegerKey extends TypedMap.AbstractKey implements Serializable {
|
||||
public IntegerKey(String pName) {
|
||||
super(pName);
|
||||
}
|
||||
|
||||
public IntegerKey() {
|
||||
}
|
||||
|
||||
public boolean isCompatibleValue(Object pValue) {
|
||||
return pValue instanceof Integer;
|
||||
}
|
||||
}
|
||||
+456
@@ -0,0 +1,456 @@
|
||||
/*
|
||||
* Copyright (c) 2009, 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;
|
||||
|
||||
import java.beans.BeanInfo;
|
||||
import java.beans.IntrospectionException;
|
||||
import java.beans.Introspector;
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.io.ObjectStreamException;
|
||||
import java.io.Serializable;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* MappedBeanFactory
|
||||
*
|
||||
* @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-sandbox/src/main/java/com/twelvemonkeys/sandbox/MappedBeanFactory.java#1 $
|
||||
*/
|
||||
public final class MappedBeanFactory {
|
||||
|
||||
// TODO: Map<String, ?> getMap(Object pProxy)
|
||||
|
||||
// TODO: Consider a @NotNull annotation that will allow for throwing IllegalArgumentExceptions
|
||||
// - Or a more general validator approach for custom fields...
|
||||
|
||||
// NOTE: Specifying default values does not make much sense, as it would be possible to just add values to the map
|
||||
// in the first place
|
||||
|
||||
// TODO: Replace Converter varargs with new class a PropertyConverterConfiguration
|
||||
// - setPropertyConverter(String propertyName, Converter from, Converter to)
|
||||
// - setDefaultConverter(Class from, Class to, Converter)
|
||||
// TODO: Validators? Allows for more than just NotNull checking
|
||||
// TODO: Mixin support for other methods, and we are on the way to full-blown AOP.. ;-)
|
||||
// TODO: Delegate for behaviour?
|
||||
|
||||
// TODO: Consider being fail-fast for primitives without default values?
|
||||
// Or have default values be the same as they would have been if class members (false/0/null)
|
||||
// NOTE: There's a difference between a map with a null value for a key, and no presence of that key at all
|
||||
|
||||
// TODO: ProperyChange support!
|
||||
|
||||
private MappedBeanFactory() {
|
||||
}
|
||||
|
||||
static <T> T as(final Class<T> pClass, final Converter... pConverters) {
|
||||
// TODO: Add neccessary default initializer stuff here.
|
||||
return as(pClass, new LinkedHashMap<String, Object>(), pConverters);
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked"})
|
||||
static <T> T as(final Class<T> pClass, final Map<String, ?> pMap, final Converter... pConverters) {
|
||||
return asImpl(pClass, (Map<String, Object>) pMap, pConverters);
|
||||
}
|
||||
|
||||
static <T> T asImpl(final Class<T> pClass, final Map<String, Object> pMap, final Converter[] pConverters) {
|
||||
// TODO: Report clashing? Named converters?
|
||||
final Map<ConverterKey, Converter> converters = new HashMap<ConverterKey, Converter>() {
|
||||
@Override
|
||||
public Converter get(Object key) {
|
||||
Converter converter = super.get(key);
|
||||
return converter != null ? converter : Converter.NULL;
|
||||
}
|
||||
};
|
||||
|
||||
for (Converter converter : pConverters) {
|
||||
converters.put(new ConverterKey(converter.getFromType(), converter.getToType()), converter);
|
||||
}
|
||||
|
||||
return pClass.cast(
|
||||
Proxy.newProxyInstance(
|
||||
pClass.getClassLoader(),
|
||||
new Class<?>[]{pClass, Serializable.class}, // TODO: Maybe Serializable should be specified by pClass?
|
||||
new MappedBeanInvocationHandler(pClass, pMap, converters)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private static class ConverterKey {
|
||||
private Class<?> to;
|
||||
private Class<?> from;
|
||||
|
||||
ConverterKey(Class<?> pFrom, Class<?> pTo) {
|
||||
to = pTo;
|
||||
from = pFrom;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object pOther) {
|
||||
if (this == pOther) {
|
||||
return true;
|
||||
}
|
||||
if (pOther == null || getClass() != pOther.getClass()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
ConverterKey that = (ConverterKey) pOther;
|
||||
|
||||
return from == that.from && to == that.to;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = to != null ? to.hashCode() : 0;
|
||||
result = 31 * result + (from != null ? from.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("%s->%s", from, to);
|
||||
}
|
||||
}
|
||||
|
||||
public static interface Converter<F, T> {
|
||||
|
||||
Converter NULL = new Converter() {
|
||||
public Class<?> getFromType() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Class<?> getToType() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Object convert(Object value, Object old) {
|
||||
if (value == null) {
|
||||
return value;
|
||||
}
|
||||
throw new ClassCastException(value.getClass().getName());
|
||||
}
|
||||
};
|
||||
|
||||
Class<F> getFromType();
|
||||
|
||||
Class<T> getToType();
|
||||
|
||||
T convert(F value, T old);
|
||||
}
|
||||
|
||||
// Add guards for null values by throwing IllegalArgumentExceptions for parameters
|
||||
// TODO: Throw IllegalArgumentException at CREATION time, if value in map is null for a method with @NotNull return type
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD})
|
||||
static @interface NotNull {
|
||||
}
|
||||
|
||||
// For setter methods to have automatic property change support
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
// TODO: Consider field as well?
|
||||
static @interface Observable {
|
||||
}
|
||||
|
||||
// TODO: Decide on default value annotation
|
||||
// Alternate default value annotation
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
static @interface DefaultValue {
|
||||
boolean booleanValue() default false;
|
||||
byte byteValue() default 0;
|
||||
char charValue() default 0;
|
||||
short shortValue() default 0;
|
||||
int intValue() default 0;
|
||||
float floatValue() default 0f;
|
||||
long longValue() default 0l;
|
||||
double doubleValue() default 0d;
|
||||
}
|
||||
|
||||
|
||||
// Default values for primitive types
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
static @interface DefaultBooleanValue {
|
||||
boolean value() default false;
|
||||
}
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
static @interface DefaultByteValue {
|
||||
byte value() default 0;
|
||||
}
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
static @interface DefaultCharValue {
|
||||
char value() default 0;
|
||||
}
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
static @interface DefaultShortValue {
|
||||
short value() default 0;
|
||||
}
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
static @interface DefaultIntValue {
|
||||
int value() default 0;
|
||||
}
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
static @interface DefaultFloatValue {
|
||||
float value() default 0;
|
||||
}
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
static @interface DefaultLongValue {
|
||||
long value() default 0;
|
||||
}
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
static @interface DefaultDouleValue {
|
||||
double value() default 0;
|
||||
}
|
||||
|
||||
// TODO: Does it make sense to NOT just put the value in the map?
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
private static @interface DefaultStringValue {
|
||||
String value(); // TODO: Do we want a default empty string?
|
||||
}
|
||||
|
||||
private static class MappedBeanInvocationHandler implements InvocationHandler, Serializable {
|
||||
|
||||
private static final Method OBJECT_TO_STRING = getObjectMethod("toString");
|
||||
private static final Method OBJECT_HASH_CODE = getObjectMethod("hashCode");
|
||||
private static final Method OBJECT_EQUALS = getObjectMethod("equals", Object.class);
|
||||
private static final Method OBJECT_CLONE = getObjectMethod("clone");
|
||||
|
||||
private final Class<?> mClass;
|
||||
private final Map<String, Object> mMap;
|
||||
private final Map<ConverterKey, Converter> mConverters;
|
||||
|
||||
private transient Map<Method, String> mReadMethods = new HashMap<Method, String>();
|
||||
private transient Map<Method, String> mWriteMethods = new HashMap<Method, String>();
|
||||
|
||||
private static Method getObjectMethod(final String pMethodName, final Class<?>... pParams) {
|
||||
try {
|
||||
return Object.class.getDeclaredMethod(pMethodName, pParams);
|
||||
}
|
||||
catch (NoSuchMethodException e) {
|
||||
throw new Error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private Object readResolve() throws ObjectStreamException {
|
||||
mReadMethods = new HashMap<Method, String>();
|
||||
mWriteMethods = new HashMap<Method, String>();
|
||||
|
||||
introspectBean(mClass, mReadMethods, mWriteMethods);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public MappedBeanInvocationHandler(Class<?> pClass, Map<String, Object> pMap, Map<ConverterKey, Converter> pConverters) {
|
||||
mClass = pClass;
|
||||
mMap = pMap;
|
||||
mConverters = pConverters;
|
||||
|
||||
introspectBean(mClass, mReadMethods, mWriteMethods);
|
||||
}
|
||||
|
||||
private void introspectBean(Class<?> pClass, Map<Method, String> pReadMethods, Map<Method, String> pWriteMethods) {
|
||||
try {
|
||||
BeanInfo info = Introspector.getBeanInfo(pClass);
|
||||
PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
|
||||
for (PropertyDescriptor descriptor : descriptors) {
|
||||
String name = descriptor.getName();
|
||||
|
||||
Method read = descriptor.getReadMethod();
|
||||
if (read != null) {
|
||||
pReadMethods.put(read, name);
|
||||
}
|
||||
|
||||
Method write = descriptor.getWriteMethod();
|
||||
if (write != null) {
|
||||
pWriteMethods.put(write, name);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (IntrospectionException e) {
|
||||
throw new IllegalArgumentException(String.format("Class %s not introspectable: %s", pClass, e.getMessage()) , e);
|
||||
}
|
||||
}
|
||||
|
||||
public Object invoke(final Object pProxy, final Method pMethod, final Object[] pArguments) throws Throwable {
|
||||
String property = mReadMethods.get(pMethod);
|
||||
if (property != null) {
|
||||
if (pArguments == null || pArguments.length == 0) {
|
||||
Object value = mMap.get(property);
|
||||
Class<?> type = pMethod.getReturnType();
|
||||
|
||||
if (!isCompatible(value, type)) {
|
||||
return mConverters.get(new ConverterKey(value != null ? value.getClass() : Void.class, unBoxType(type))).convert(value, null);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Unknown parameters for " + pMethod + ": " + Arrays.toString(pArguments));
|
||||
}
|
||||
}
|
||||
|
||||
property = mWriteMethods.get(pMethod);
|
||||
if (property != null) {
|
||||
if (pArguments.length == 1) {
|
||||
Object value = pArguments[0];
|
||||
|
||||
// Make sure we don't accidentally overwrite a value that looks like ours...
|
||||
Object oldValue = mMap.get(property);
|
||||
Class<?> type = pMethod.getParameterTypes()[0];
|
||||
if (oldValue != null && !isCompatible(oldValue, type)) {
|
||||
value = mConverters.get(new ConverterKey(type, oldValue.getClass())).convert(value, oldValue);
|
||||
}
|
||||
return mMap.put(property, value);
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Unknown parameters for " + pMethod + ": " + Arrays.toString(pArguments));
|
||||
}
|
||||
}
|
||||
|
||||
if (pMethod.equals(OBJECT_TO_STRING)) {
|
||||
return proxyToString();
|
||||
}
|
||||
if (pMethod.equals(OBJECT_EQUALS)) {
|
||||
return proxyEquals(pProxy, pArguments[0]);
|
||||
}
|
||||
if (pMethod.equals(OBJECT_HASH_CODE)) {
|
||||
return proxyHashCode();
|
||||
}
|
||||
if (pMethod.getName().equals(OBJECT_CLONE.getName())
|
||||
&& Arrays.equals(pMethod.getParameterTypes(), OBJECT_CLONE.getParameterTypes())
|
||||
&& OBJECT_CLONE.getReturnType().isAssignableFrom(pMethod.getReturnType())) {
|
||||
return proxyClone();
|
||||
}
|
||||
|
||||
// Other methods not handled (for now)
|
||||
throw new AbstractMethodError(pMethod.getName());
|
||||
}
|
||||
|
||||
private boolean isCompatible(final Object pValue, final Class<?> pType) {
|
||||
return pValue == null && !pType.isPrimitive() || unBoxType(pType).isInstance(pValue);
|
||||
}
|
||||
|
||||
private Class<?> unBoxType(final Class<?> pType) {
|
||||
if (pType.isPrimitive()) {
|
||||
if (pType == boolean.class) {
|
||||
return Boolean.class;
|
||||
}
|
||||
if (pType == byte.class) {
|
||||
return Byte.class;
|
||||
}
|
||||
if (pType == char.class) {
|
||||
return Character.class;
|
||||
}
|
||||
if (pType == short.class) {
|
||||
return Short.class;
|
||||
}
|
||||
if (pType == int.class) {
|
||||
return Integer.class;
|
||||
}
|
||||
if (pType == float.class) {
|
||||
return Float.class;
|
||||
}
|
||||
if (pType == long.class) {
|
||||
return Long.class;
|
||||
}
|
||||
if (pType == double.class) {
|
||||
return Double.class;
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("Unknown type: " + pType);
|
||||
}
|
||||
return pType;
|
||||
}
|
||||
|
||||
private int proxyHashCode() {
|
||||
// NOTE: Implies mMap instance must follow Map.equals contract
|
||||
return mMap.hashCode();
|
||||
}
|
||||
|
||||
private boolean proxyEquals(final Object pThisProxy, final Object pThat) {
|
||||
if (pThisProxy == pThat) {
|
||||
return true;
|
||||
}
|
||||
if (pThat == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// TODO: Document that subclasses are considered equal (if no extra properties)
|
||||
if (!mClass.isInstance(pThat)) {
|
||||
return false;
|
||||
}
|
||||
if (!Proxy.isProxyClass(pThat.getClass())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// NOTE: This implies that we should put default values in map at creation time
|
||||
// NOTE: Implies mMap instance must follow Map.equals contract
|
||||
InvocationHandler handler = Proxy.getInvocationHandler(pThat);
|
||||
return handler.getClass() == getClass() && mMap.equals(((MappedBeanInvocationHandler) handler).mMap);
|
||||
|
||||
}
|
||||
|
||||
private Object proxyClone() throws CloneNotSupportedException {
|
||||
return as(
|
||||
mClass,
|
||||
new LinkedHashMap<String, Object>(mMap),
|
||||
mConverters.values().toArray(new Converter[mConverters.values().size()])
|
||||
);
|
||||
}
|
||||
|
||||
private String proxyToString() {
|
||||
return String.format("%s$MapProxy@%s: %s", mClass.getName(), System.identityHashCode(this), mMap);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import java.awt.*;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* PaintKey class description.
|
||||
*
|
||||
* @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/util/PaintKey.java#1 $
|
||||
*/
|
||||
public class PaintKey extends TypedMap.AbstractKey implements Serializable {
|
||||
public PaintKey() {
|
||||
super();
|
||||
}
|
||||
|
||||
public PaintKey(String pName) {
|
||||
super(pName);
|
||||
}
|
||||
|
||||
public boolean isCompatibleValue(Object pValue) {
|
||||
return pValue instanceof Paint;
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* Copyright (c) 2009, 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;
|
||||
|
||||
/**
|
||||
* PersistentMap
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @author last modified by $Author: haraldk$
|
||||
* @version $Id: PersistentMap.java,v 1.0 May 13, 2009 2:31:29 PM haraldk Exp$
|
||||
*/
|
||||
public class PersistentMap {
|
||||
// TODO: Implement Map
|
||||
// TODO: Delta synchronization (db?)
|
||||
}
|
||||
|
||||
/*
|
||||
Persistent format
|
||||
|
||||
Header
|
||||
File ID 4-8 bytes
|
||||
Size
|
||||
|
||||
Entry pointer array block
|
||||
Size
|
||||
Next entry pointer block address
|
||||
Entry 1 address
|
||||
...
|
||||
Entry n address
|
||||
|
||||
Entry 1
|
||||
...
|
||||
Entry n
|
||||
|
||||
*/
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import java.awt.geom.Rectangle2D;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* Rectangle2DKey class description.
|
||||
*
|
||||
* @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/util/Rectangle2DKey.java#1 $
|
||||
*/
|
||||
public class Rectangle2DKey extends TypedMap.AbstractKey implements Serializable {
|
||||
public Rectangle2DKey() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Rectangle2DKey(String pName) {
|
||||
super(pName);
|
||||
}
|
||||
|
||||
public boolean isCompatibleValue(Object pValue) {
|
||||
return pValue instanceof Rectangle2D;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
* Resource class description.
|
||||
*
|
||||
* @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/util/Resource.java#1 $
|
||||
*/
|
||||
public interface Resource {
|
||||
/**
|
||||
* Returns the id of this resource.
|
||||
*
|
||||
* The id might be a {@code URL}, a {@code File} or a string
|
||||
* representation of some system resource.
|
||||
* It will always be equal to the {@code resourceId} parameter
|
||||
* sent to the {@link ResourceMonitor#addResourceChangeListener} method
|
||||
* for a given resource.
|
||||
*
|
||||
* @return the id of this resource
|
||||
*/
|
||||
public Object getId();
|
||||
|
||||
/**
|
||||
* Returns the {@code URL} for the resource.
|
||||
*
|
||||
* @return the URL for the resource
|
||||
*/
|
||||
public URL asURL();
|
||||
|
||||
/**
|
||||
* Opens an input stream, that reads from this resource.
|
||||
*
|
||||
* @return an input stream, that reads from this resource.
|
||||
*
|
||||
* @throws IOException if an I/O exception occurs
|
||||
*/
|
||||
public InputStream asStream() throws IOException;
|
||||
|
||||
/**
|
||||
* Returns the last modified time.
|
||||
* Should only be used for comparison.
|
||||
*
|
||||
* @return the time of the last modification of this resource, or
|
||||
* {@code -1} if the last modification time cannot be determined.
|
||||
*/
|
||||
public long lastModified();
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import java.util.EventListener;
|
||||
|
||||
/**
|
||||
* An {@code EventListener} that listens for updates in file or system
|
||||
* resources.
|
||||
*
|
||||
* @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/util/ResourceChangeListener.java#1 $
|
||||
*/
|
||||
public interface ResourceChangeListener extends EventListener {
|
||||
/**
|
||||
* Invoked when a resource is changed.
|
||||
* Implementations that listens for multiple events, should check that
|
||||
* {@code Resource.getId()} is equal to the {@code resourceId} parameter
|
||||
* sent to the {@link ResourceMonitor#addResourceChangeListener} method.
|
||||
*
|
||||
* @param pResource changed file/url/etc.
|
||||
*/
|
||||
void resourceChanged(Resource pResource);
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
|
||||
// TODO: Could this be used for change-aware classloader? Woo..
|
||||
/**
|
||||
* Monitors changes is files and system resources.
|
||||
*
|
||||
* Based on example code and ideas from
|
||||
* <A href="http://www.javaworld.com/javaworld/javatips/jw-javatip125.html">Java
|
||||
* Tip 125: Set your timer for dynamic properties</A>.
|
||||
*
|
||||
* @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/util/ResourceMonitor.java#1 $
|
||||
*/
|
||||
public abstract class ResourceMonitor {
|
||||
|
||||
private static final ResourceMonitor INSTANCE = new ResourceMonitor() {};
|
||||
|
||||
private Timer timer;
|
||||
|
||||
private final Map<Object, ResourceMonitorTask> timerEntries;
|
||||
|
||||
public static ResourceMonitor getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a {@code ResourceMonitor}.
|
||||
*/
|
||||
protected ResourceMonitor() {
|
||||
// Create timer, run timer thread as daemon...
|
||||
timer = new Timer(true);
|
||||
timerEntries = new HashMap<Object, ResourceMonitorTask>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a monitored {@code Resource} with a {@code ResourceChangeListener}.
|
||||
*
|
||||
* The {@code reourceId} might be a {@code File} a {@code URL} or a
|
||||
* {@code String} containing a file path, or a path to a resource in the
|
||||
* class path. Note that class path resources are resolved using the
|
||||
* given {@code ResourceChangeListener}'s {@code ClassLoader}, then
|
||||
* the current {@code Thread}'s context class loader, if not found.
|
||||
*
|
||||
* @param pListener pListener to notify when the file changed.
|
||||
* @param pResourceId id of the resource to monitor (a {@code File}
|
||||
* a {@code URL} or a {@code String} containing a file path).
|
||||
* @param pPeriod polling pPeriod in milliseconds.
|
||||
*
|
||||
* @see ClassLoader#getResource(String)
|
||||
*/
|
||||
public void addResourceChangeListener(ResourceChangeListener pListener,
|
||||
Object pResourceId, long pPeriod) throws IOException {
|
||||
// Create the task
|
||||
ResourceMonitorTask task = new ResourceMonitorTask(pListener, pResourceId);
|
||||
|
||||
// Get unique Id
|
||||
Object resourceId = getResourceId(pResourceId, pListener);
|
||||
|
||||
// Remove the old task for this Id, if any, and register the new one
|
||||
synchronized (timerEntries) {
|
||||
removeListenerInternal(resourceId);
|
||||
timerEntries.put(resourceId, task);
|
||||
}
|
||||
|
||||
timer.schedule(task, pPeriod, pPeriod);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the {@code ResourceChangeListener} from the notification list.
|
||||
*
|
||||
* @param pListener the pListener to be removed.
|
||||
* @param pResourceId name of the resource to monitor.
|
||||
*/
|
||||
public void removeResourceChangeListener(ResourceChangeListener pListener, Object pResourceId) {
|
||||
synchronized (timerEntries) {
|
||||
removeListenerInternal(getResourceId(pResourceId, pListener));
|
||||
}
|
||||
}
|
||||
|
||||
private void removeListenerInternal(Object pResourceId) {
|
||||
ResourceMonitorTask task = timerEntries.remove(pResourceId);
|
||||
|
||||
if (task != null) {
|
||||
task.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
private Object getResourceId(Object pResourceName, ResourceChangeListener pListener) {
|
||||
return pResourceName.toString() + System.identityHashCode(pListener);
|
||||
}
|
||||
|
||||
private void fireResourceChangeEvent(ResourceChangeListener pListener, Resource pResource) {
|
||||
pListener.resourceChanged(pResource);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private class ResourceMonitorTask extends TimerTask {
|
||||
ResourceChangeListener listener;
|
||||
Resource monitoredResource;
|
||||
long lastModified;
|
||||
|
||||
public ResourceMonitorTask(ResourceChangeListener pListener, Object pResourceId) throws IOException {
|
||||
listener = pListener;
|
||||
lastModified = 0;
|
||||
|
||||
String resourceId = null;
|
||||
File file = null;
|
||||
URL url = null;
|
||||
if (pResourceId instanceof File) {
|
||||
file = (File) pResourceId;
|
||||
resourceId = file.getAbsolutePath(); // For use by exception only
|
||||
}
|
||||
else if (pResourceId instanceof URL) {
|
||||
url = (URL) pResourceId;
|
||||
if ("file".equals(url.getProtocol())) {
|
||||
file = new File(url.getFile());
|
||||
}
|
||||
resourceId = url.toExternalForm(); // For use by exception only
|
||||
}
|
||||
else if (pResourceId instanceof String) {
|
||||
resourceId = (String) pResourceId; // This one might be looked up
|
||||
file = new File(resourceId);
|
||||
}
|
||||
|
||||
if (file != null && file.exists()) {
|
||||
// Easy, this is a file
|
||||
monitoredResource = new FileResource(pResourceId, file);
|
||||
//System.out.println("File: " + monitoredResource);
|
||||
}
|
||||
else {
|
||||
// No file there, but is it on CLASSPATH?
|
||||
if (url == null) {
|
||||
url = pListener.getClass().getClassLoader().getResource(resourceId);
|
||||
}
|
||||
if (url == null) {
|
||||
url = Thread.currentThread().getContextClassLoader().getResource(resourceId);
|
||||
}
|
||||
|
||||
if (url != null && "file".equals(url.getProtocol())
|
||||
&& (file = new File(url.getFile())).exists()) {
|
||||
// It's a file in classpath, so try this as an optimization
|
||||
monitoredResource = new FileResource(pResourceId, file);
|
||||
//System.out.println("File: " + monitoredResource);
|
||||
}
|
||||
else if (url != null) {
|
||||
// No, not a file, might even be an external resource
|
||||
monitoredResource = new URLResource(pResourceId, url);
|
||||
//System.out.println("URL: " + monitoredResource);
|
||||
}
|
||||
else {
|
||||
throw new FileNotFoundException(resourceId);
|
||||
}
|
||||
}
|
||||
|
||||
lastModified = monitoredResource.lastModified();
|
||||
}
|
||||
|
||||
public void run() {
|
||||
long lastModified = monitoredResource.lastModified();
|
||||
|
||||
if (lastModified != this.lastModified) {
|
||||
this.lastModified = lastModified;
|
||||
fireResourceChangeEvent(listener, monitoredResource);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* StringKey class description.
|
||||
*
|
||||
* @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/util/StringKey.java#1 $
|
||||
*/
|
||||
public class StringKey extends TypedMap.AbstractKey implements Serializable {
|
||||
public StringKey() {
|
||||
super();
|
||||
}
|
||||
|
||||
public StringKey(String pName) {
|
||||
super(pName);
|
||||
}
|
||||
|
||||
public boolean isCompatibleValue(Object pValue) {
|
||||
return pValue instanceof String;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.util.Collection;
|
||||
import java.util.Set;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* This {@code Map} implementation guarantees that the values have a type that
|
||||
* are compatible with it's key. Different keys may have different types.
|
||||
*
|
||||
* @see TypedMap.Key
|
||||
*
|
||||
* @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/util/TypedMap.java#1 $
|
||||
*/
|
||||
public class TypedMap<K extends TypedMap.Key, V> implements Map<K, V>, Serializable {
|
||||
|
||||
/**
|
||||
* The wrapped map
|
||||
*/
|
||||
protected Map<K, V> entries;
|
||||
|
||||
/**
|
||||
* Creates a {@code TypedMap}.
|
||||
* This {@code TypedMap} will be backed by a new {@code HashMap} instance.
|
||||
*/
|
||||
public TypedMap() {
|
||||
entries = new HashMap<K, V>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a {@code TypedMap} containing the same elements as the given
|
||||
* map.
|
||||
* This {@code TypedMap} will be backed by a new {@code HashMap} instance,
|
||||
* and <em>not</em> the map passed in as a paramter.
|
||||
* <p/>
|
||||
* <small>This is constructor is here to comply with the reccomendations for
|
||||
* "standard" constructors in the {@code Map} interface.</small>
|
||||
*
|
||||
* @param pMap the map used to populate this map
|
||||
* @throws ClassCastException if all keys in the map are not instances of
|
||||
* {@code TypedMap.Key}.
|
||||
* @see java.util.Map
|
||||
* @see #TypedMap(java.util.Map, boolean)
|
||||
*/
|
||||
public TypedMap(Map<? extends K, ? extends V> pMap) {
|
||||
this();
|
||||
|
||||
if (pMap != null) {
|
||||
putAll(pMap);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a {@code TypedMap}.
|
||||
* This {@code TypedMap} will be backed by the given {@code Map}.
|
||||
* <P/>
|
||||
* Note that structurally modifying the backing map directly (not through
|
||||
* this map or its collection views), is not allowed, and will produce
|
||||
* undeterministic exceptions.
|
||||
*
|
||||
* @param pBacking the map that will be used as backing.
|
||||
* @param pUseElements if {@code true}, the elements in the map are
|
||||
* retained. Otherwise, the map is cleared. For an empty {@code Map} the
|
||||
* parameter has no effect.
|
||||
* @throws ClassCastException if {@code pUseElements} is {@code true}
|
||||
* all keys in the map are not instances of {@code TypedMap.Key}.
|
||||
*/
|
||||
public TypedMap(Map<? extends K, ? extends V> pBacking, boolean pUseElements) {
|
||||
if (pBacking == null) {
|
||||
throw new IllegalArgumentException("backing == null");
|
||||
}
|
||||
|
||||
// This is safe, as we re-insert all values later
|
||||
//noinspection unchecked
|
||||
entries = (Map<K, V>) pBacking;
|
||||
|
||||
// Re-insert all elements to avoid undeterministic ClassCastExceptions
|
||||
if (pUseElements) {
|
||||
putAll(pBacking);
|
||||
}
|
||||
else if (entries.size() > 0) {
|
||||
entries.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of key-value mappings in this map. If the
|
||||
* map contains more than {@code Integer.MAX_VALUE} elements, returns
|
||||
* {@code Integer.MAX_VALUE}.
|
||||
*
|
||||
* @return the number of key-value mappings in this map.
|
||||
*/
|
||||
public int size() {
|
||||
return entries.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns {@code true} if this map contains no key-value mappings.
|
||||
*
|
||||
* @return {@code true} if this map contains no key-value mappings.
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return entries.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns {@code true} if this map contains a mapping for the specified
|
||||
* key.
|
||||
*
|
||||
* @param pKey key whose presence in this map is to be tested.
|
||||
* @return {@code true} if this map contains a mapping for the specified
|
||||
* key.
|
||||
*/
|
||||
public boolean containsKey(Object pKey) {
|
||||
return entries.containsKey(pKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns {@code true} if this map maps one or more keys to the
|
||||
* specified value. More formally, returns {@code true} if and only if
|
||||
* this map contains at least one mapping to a value {@code v} such that
|
||||
* {@code (pValue==null ? v==null : pValue.equals(v))}. This operation
|
||||
* will probably require time linear in the map size for most
|
||||
* implementations of the {@code Map} interface.
|
||||
*
|
||||
* @param pValue value whose presence in this map is to be tested.
|
||||
* @return {@code true} if this map maps one or more keys to the
|
||||
* specified value.
|
||||
*/
|
||||
public boolean containsValue(Object pValue) {
|
||||
return entries.containsValue(pValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value to which this map maps the specified key. Returns
|
||||
* {@code null} if the map contains no mapping for this key. A return
|
||||
* value of {@code null} does not <i>necessarily</i> indicate that the
|
||||
* map contains no mapping for the key; it's also possible that the map
|
||||
* explicitly maps the key to {@code null}. The {@code containsKey}
|
||||
* operation may be used to distinguish these two cases.
|
||||
*
|
||||
* @param pKey key whose associated value is to be returned.
|
||||
* @return the value to which this map maps the specified key, or
|
||||
* {@code null} if the map contains no mapping for this key.
|
||||
* @see #containsKey(java.lang.Object)
|
||||
*/
|
||||
public V get(Object pKey) {
|
||||
return entries.get(pKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Associates the specified value with the specified key in this map.
|
||||
* If the map previously contained a mapping for
|
||||
* the key, the old value is replaced.
|
||||
*
|
||||
* @param pKey key with which the specified value is to be associated.
|
||||
* @param pValue value to be associated with the specified key.
|
||||
*
|
||||
* @return previous value associated with specified key, or {@code null}
|
||||
* if there was no mapping for key. A {@code null} return can
|
||||
* also indicate that the map previously associated {@code null}
|
||||
* with the specified pKey, if the implementation supports
|
||||
* {@code null} values.
|
||||
*
|
||||
* @throws IllegalArgumentException if the value is not compatible with the
|
||||
* key.
|
||||
*
|
||||
* @see TypedMap.Key
|
||||
*/
|
||||
public V put(K pKey, V pValue) {
|
||||
if (!pKey.isCompatibleValue(pValue)) {
|
||||
throw new IllegalArgumentException("incompatible value for key");
|
||||
}
|
||||
return entries.put(pKey, pValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the mapping for this key from this map if present (optional
|
||||
* operation).
|
||||
*
|
||||
* @param pKey key whose mapping is to be removed from the map.
|
||||
* @return previous value associated with specified key, or {@code null}
|
||||
* if there was no mapping for key. A {@code null} return can
|
||||
* also indicate that the map previously associated {@code null}
|
||||
* with the specified key, if the implementation supports
|
||||
* {@code null} values.
|
||||
*/
|
||||
public V remove(Object pKey) {
|
||||
return entries.remove(pKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies all of the mappings from the specified map to this map
|
||||
* (optional operation). These mappings will replace any mappings that
|
||||
* this map had for any of the keys currently in the specified map.
|
||||
* <P/>
|
||||
* Note: If you override this method, make sure you add each element through
|
||||
* the put method, to avoid resource leaks and undeterministic class casts.
|
||||
*
|
||||
* @param pMap Mappings to be stored in this map.
|
||||
*/
|
||||
public void putAll(Map<? extends K, ? extends V> pMap) {
|
||||
for (final Entry<? extends K, ? extends V> e : pMap.entrySet()) {
|
||||
put(e.getKey(), e.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all mappings from this map (optional operation).
|
||||
*/
|
||||
public void clear() {
|
||||
entries.clear();
|
||||
}
|
||||
|
||||
public Collection<V> values() {
|
||||
return entries.values();
|
||||
}
|
||||
|
||||
public Set<Entry<K, V>> entrySet() {
|
||||
return entries.entrySet();
|
||||
}
|
||||
|
||||
public Set<K> keySet() {
|
||||
return entries.keySet();
|
||||
}
|
||||
|
||||
/**
|
||||
* Keys for use with {@code TypedMap} must implement this interface.
|
||||
*
|
||||
* @see #isCompatibleValue(Object)
|
||||
*/
|
||||
public static interface Key {
|
||||
|
||||
/**
|
||||
* Tests if the given value is compatible with this {@code Key}.
|
||||
* Only compatible values may be passed to the
|
||||
* {@code TypedMap.put} method.
|
||||
*
|
||||
* @param pValue the value to test for compatibility
|
||||
* @return {@code true} if compatible, otherwise {@code false}
|
||||
*/
|
||||
boolean isCompatibleValue(Object pValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* An abstract {@code Key} implementation that allows keys to have
|
||||
* meaningful names.
|
||||
*/
|
||||
public static abstract class AbstractKey implements Key, Serializable {
|
||||
private final String mStringRep;
|
||||
|
||||
/**
|
||||
* Creates a {@code Key} with the given name.
|
||||
*
|
||||
* @param pName name of this key
|
||||
*/
|
||||
public AbstractKey(String pName) {
|
||||
if (pName == null) {
|
||||
throw new IllegalArgumentException("name == null");
|
||||
}
|
||||
mStringRep = getClass().getName() + '[' + pName + ']';
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a {@code Key} with no name.
|
||||
*/
|
||||
public AbstractKey() {
|
||||
this("null");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return mStringRep;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return obj == this ||
|
||||
(obj != null && obj.getClass() == getClass() &&
|
||||
mStringRep.equals(((AbstractKey) obj).mStringRep));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return mStringRep.hashCode();
|
||||
}
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
||||
/**
|
||||
* URLResource class description.
|
||||
*
|
||||
* @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/util/URLResource.java#1 $
|
||||
*/
|
||||
final class URLResource extends AbstractResource {
|
||||
|
||||
// NOTE: For the time being, we rely on the URL class (and helpers) to do
|
||||
// some smart caching and reuse of connections...
|
||||
// TODO: Change the implementation if this is a problem
|
||||
private long lastModified = -1;
|
||||
|
||||
/**
|
||||
* Creates a {@code URLResource}.
|
||||
*
|
||||
* @param pResourceId the resource id
|
||||
* @param pURL the URL resource
|
||||
*/
|
||||
public URLResource(Object pResourceId, URL pURL) {
|
||||
super(pResourceId, pURL);
|
||||
}
|
||||
|
||||
private URL getURL() {
|
||||
return (URL) wrappedResource;
|
||||
}
|
||||
|
||||
public URL asURL() {
|
||||
return getURL();
|
||||
}
|
||||
|
||||
public InputStream asStream() throws IOException {
|
||||
URLConnection connection = getURL().openConnection();
|
||||
connection.setAllowUserInteraction(false);
|
||||
connection.setUseCaches(true);
|
||||
return connection.getInputStream();
|
||||
}
|
||||
|
||||
public long lastModified() {
|
||||
try {
|
||||
URLConnection connection = getURL().openConnection();
|
||||
connection.setAllowUserInteraction(false);
|
||||
connection.setUseCaches(true);
|
||||
connection.setIfModifiedSince(lastModified);
|
||||
|
||||
lastModified = connection.getLastModified();
|
||||
}
|
||||
catch (IOException ignore) {
|
||||
}
|
||||
|
||||
return lastModified;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
/*
|
||||
* Copyright (c) 2012, 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;
|
||||
|
||||
import com.twelvemonkeys.lang.StringUtil;
|
||||
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.SocketException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* A factory for creating {@code UUID}s not directly supported by {@link java.util.UUID java.util.UUID}.
|
||||
* <p>
|
||||
* This class can create version 1 time based {@code UUID}s, using either IEEE 802 (mac) address or random "node" value
|
||||
* as well as version 5 SHA1 hash based {@code UUID}s.
|
||||
* </p>
|
||||
* <p>
|
||||
* The timestamp value for version 1 {@code UUID}s will use a high precision clock, when available to the Java VM.
|
||||
* If the Java system clock does not offer the needed precision, the timestamps will fall back to 100-nanosecond
|
||||
* increments, to avoid duplicates.
|
||||
* </p>
|
||||
* <p>
|
||||
* <a name="mac-node"></a>
|
||||
* The node value for version 1 {@code UUID}s will, by default, reflect the IEEE 802 (mac) address of one of
|
||||
* the network interfaces of the local computer. This node value can be manually overridden by setting
|
||||
* the system property {@code "com.twelvemonkeys.util.UUID.node"} to a valid IEEE 802 address, on the form
|
||||
* {@code "12:34:56:78:9a:bc"} or {@code "12-34-45-78-9a-bc"}.
|
||||
* </p>
|
||||
* <p>
|
||||
* <a name="random-node"></a>
|
||||
* The node value for the random "node" based version 1 {@code UUID}s will be stable for the lifetime of the VM.
|
||||
* </p>
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @author last modified by $Author: haraldk$
|
||||
* @version $Id: UUIDFactory.java,v 1.0 27.02.12 09:45 haraldk Exp$
|
||||
*
|
||||
* @see <a href="http://tools.ietf.org/html/rfc4122">RFC 4122</a>
|
||||
* @see <a href="http://en.wikipedia.org/wiki/Universally_unique_identifier">Wikipedia</a>
|
||||
* @see java.util.UUID
|
||||
*/
|
||||
public final class UUIDFactory {
|
||||
private static final String NODE_PROPERTY = "com.twelvemonkeys.util.UUID.node";
|
||||
|
||||
/**
|
||||
* The Nil UUID: {@code "00000000-0000-0000-0000-000000000000"}.
|
||||
*
|
||||
* The nil UUID is special form of UUID that is specified to have all
|
||||
* 128 bits set to zero. Not particularly useful, unless as a placeholder or template.
|
||||
*
|
||||
* @see <a href="http://tools.ietf.org/html/rfc4122#section-4.1.7">RFC 4122 4.1.7. Nil UUID</a>
|
||||
*/
|
||||
public static final UUID NIL = new UUID(0l, 0l);
|
||||
|
||||
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
||||
|
||||
private static final Comparator<UUID> COMPARATOR = new UUIDComparator();
|
||||
|
||||
// Assumes MAC address is constant, which it may not be if a network card is replaced
|
||||
static final long MAC_ADDRESS_NODE = getMacAddressNode();
|
||||
|
||||
static final long SECURE_RANDOM_NODE = getSecureRandomNode();
|
||||
|
||||
private static long getSecureRandomNode() {
|
||||
// Creates a completely random "node" value, with the unicast bit set to 1, as outlined in RFC 4122.
|
||||
return 1l << 40 | SECURE_RANDOM.nextLong() & 0xffffffffffffl;
|
||||
}
|
||||
|
||||
private static long getMacAddressNode() {
|
||||
long[] addressNodes;
|
||||
|
||||
String nodeProperty = System.getProperty(NODE_PROPERTY);
|
||||
|
||||
// Read mac address/node from system property, to allow user-specified node addresses.
|
||||
if (!StringUtil.isEmpty(nodeProperty)) {
|
||||
addressNodes = parseMacAddressNodes(nodeProperty);
|
||||
}
|
||||
else {
|
||||
addressNodes = MacAddressFinder.getMacAddressNodes();
|
||||
}
|
||||
|
||||
// TODO: The UUID spec allows us to use multiple nodes, when available, to create more UUIDs per time unit...
|
||||
// For example in a round robin fashion?
|
||||
return addressNodes != null && addressNodes.length > 0 ? addressNodes[0] : -1;
|
||||
}
|
||||
|
||||
static long[] parseMacAddressNodes(final String nodeProperty) {
|
||||
// Parse comma-separated list mac addresses on format 00:11:22:33:44:55 / 00-11-22-33-44-55
|
||||
String[] nodesStrings = nodeProperty.trim().split(",\\W*");
|
||||
long[] addressNodes = new long[nodesStrings.length];
|
||||
|
||||
for (int i = 0, nodesStringsLength = nodesStrings.length; i < nodesStringsLength; i++) {
|
||||
String nodesString = nodesStrings[i];
|
||||
|
||||
try {
|
||||
String[] nodes = nodesString.split("(?<=(^|\\W)[0-9a-fA-F]{2})\\W(?=[0-9a-fA-F]{2}(\\W|$))", 6);
|
||||
|
||||
long nodeAddress = 0;
|
||||
|
||||
// Network byte order
|
||||
nodeAddress |= (long) (Integer.parseInt(nodes[0], 16) & 0xff) << 40;
|
||||
nodeAddress |= (long) (Integer.parseInt(nodes[1], 16) & 0xff) << 32;
|
||||
nodeAddress |= (long) (Integer.parseInt(nodes[2], 16) & 0xff) << 24;
|
||||
nodeAddress |= (long) (Integer.parseInt(nodes[3], 16) & 0xff) << 16;
|
||||
nodeAddress |= (long) (Integer.parseInt(nodes[4], 16) & 0xff) << 8;
|
||||
nodeAddress |= (long) (Integer.parseInt(nodes[5], 16) & 0xff);
|
||||
|
||||
addressNodes[i] = nodeAddress;
|
||||
}
|
||||
catch (RuntimeException e) {
|
||||
// May be NumberformatException from parseInt or ArrayIndexOutOfBounds from nodes array
|
||||
NumberFormatException formatException = new NumberFormatException(String.format("Bad IEEE 802 node address: '%s' (from system property %s)", nodesString, NODE_PROPERTY));
|
||||
formatException.initCause(e);
|
||||
throw formatException;
|
||||
}
|
||||
}
|
||||
|
||||
return addressNodes;
|
||||
}
|
||||
|
||||
private UUIDFactory() {}
|
||||
|
||||
/**
|
||||
* Creates a type 5 (name based) {@code UUID} based on the specified byte array.
|
||||
* This method is effectively identical to {@link UUID#nameUUIDFromBytes}, except that this method
|
||||
* uses a SHA1 hash instead of the MD5 hash used in the type 3 {@code UUID}s.
|
||||
* RFC 4122 states that "SHA-1 is preferred" over MD5, without giving a reason for why.
|
||||
*
|
||||
* @param name a byte array to be used to construct a {@code UUID}
|
||||
* @return a {@code UUID} generated from the specified array.
|
||||
*
|
||||
* @see <a href="http://tools.ietf.org/html/rfc4122#section-4.3">RFC 4122 4.3. Algorithm for Creating a Name-Based UUID</a>
|
||||
* @see <a href="http://tools.ietf.org/html/rfc4122#appendix-A">RFC 4122 appendix A</a>
|
||||
* @see UUID#nameUUIDFromBytes(byte[])
|
||||
*/
|
||||
public static UUID nameUUIDv5FromBytes(byte[] name) {
|
||||
// Based on code from OpenJDK UUID#nameUUIDFromBytes + private byte[] constructor
|
||||
MessageDigest md;
|
||||
|
||||
try {
|
||||
md = MessageDigest.getInstance("SHA1");
|
||||
}
|
||||
catch (NoSuchAlgorithmException nsae) {
|
||||
throw new InternalError("SHA1 not supported");
|
||||
}
|
||||
|
||||
byte[] sha1Bytes = md.digest(name);
|
||||
sha1Bytes[6] &= 0x0f; /* clear version */
|
||||
sha1Bytes[6] |= 0x50; /* set to version 5 */
|
||||
sha1Bytes[8] &= 0x3f; /* clear variant */
|
||||
sha1Bytes[8] |= 0x80; /* set to IETF variant */
|
||||
|
||||
long msb = 0;
|
||||
long lsb = 0;
|
||||
|
||||
// NOTE: According to RFC 4122, only first 16 bytes are used, meaning
|
||||
// bytes 17-20 in the 160 bit SHA1 hash are simply discarded in this case...
|
||||
for (int i=0; i<8; i++) {
|
||||
msb = (msb << 8) | (sha1Bytes[i] & 0xff);
|
||||
}
|
||||
for (int i=8; i<16; i++) {
|
||||
lsb = (lsb << 8) | (sha1Bytes[i] & 0xff);
|
||||
}
|
||||
|
||||
return new UUID(msb, lsb);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a version 1 time (and node) based {@code UUID}.
|
||||
* The node part is by default the IEE 802 (mac) address of one of the network cards of the current machine.
|
||||
*
|
||||
* @return a {@code UUID} based on the current time and the node address of this computer.
|
||||
* @see <a href="http://tools.ietf.org/html/rfc4122#section-4.2">RFC 4122 4.2. Algorithms for Creating a Time-Based UUID</a>
|
||||
* @see <a href="http://en.wikipedia.org/wiki/MAC_address">IEEE 802 (mac) address</a>
|
||||
* @see <a href="#mac-node">Overriding the node address</a>
|
||||
*
|
||||
* @throws IllegalStateException if the IEEE 802 (mac) address of the computer (node) cannot be found.
|
||||
*/
|
||||
public static UUID timeNodeBasedUUID() {
|
||||
if (MAC_ADDRESS_NODE == -1) {
|
||||
throw new IllegalStateException("Could not determine IEEE 802 (mac) address for node");
|
||||
}
|
||||
|
||||
return createTimeBasedUUIDforNode(MAC_ADDRESS_NODE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a version 1 time based {@code UUID} with the node part replaced by a random based value.
|
||||
* The node part is computed using a 47 bit secure random number + lsb of first octet (unicast/multicast bit) set to 1.
|
||||
* These {@code UUID}s can never clash with "real" node based version 1 {@code UUID}s due to the difference in
|
||||
* the unicast/multicast bit, however, no uniqueness between multiple machines/vms/nodes can be guaranteed.
|
||||
*
|
||||
* @return a {@code UUID} based on the current time and a random generated "node" value.
|
||||
* @see <a href="http://tools.ietf.org/html/rfc4122#section-4.5">RFC 4122 4.5. Node IDs that Do Not Identify the Host</a>
|
||||
* @see <a href="http://tools.ietf.org/html/rfc4122#appendix-A">RFC 4122 Appendix A</a>
|
||||
* @see <a href="#random-node">Lifetime of random node value</a>
|
||||
*
|
||||
* @throws IllegalStateException if the IEEE 802 (mac) address of the computer (node) cannot be found.
|
||||
*/
|
||||
public static UUID timeRandomBasedUUID() {
|
||||
return createTimeBasedUUIDforNode(SECURE_RANDOM_NODE);
|
||||
}
|
||||
|
||||
private static UUID createTimeBasedUUIDforNode(final long node) {
|
||||
return new UUID(createTimeAndVersion(), createClockSeqAndNode(node));
|
||||
}
|
||||
|
||||
// TODO: Version 2 UUID?
|
||||
/*
|
||||
Version 2 UUIDs are similar to Version 1 UUIDs, with the upper byte of the clock sequence replaced by the
|
||||
identifier for a "local domain" (typically either the "POSIX UID domain" or the "POSIX GID domain")
|
||||
and the first 4 bytes of the timestamp replaced by the user's POSIX UID or GID (with the "local domain"
|
||||
identifier indicating which it is).[2][3]
|
||||
*/
|
||||
|
||||
private static long createClockSeqAndNode(final long node) {
|
||||
// Variant (2) + Clock seq high and low + node
|
||||
return 0x8000000000000000l | (Clock.getClockSequence() << 48) | node & 0xffffffffffffl;
|
||||
}
|
||||
|
||||
private static long createTimeAndVersion() {
|
||||
long clockTime = Clock.currentTimeHundredNanos();
|
||||
|
||||
long time = clockTime << 32; // Time low
|
||||
time |= (clockTime & 0xFFFF00000000L) >> 16; // Time mid
|
||||
time |= ((clockTime >> 48) & 0x0FFF); // Time high
|
||||
time |= 0x1000; // Version (1)
|
||||
|
||||
return time;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a comparator that compares UUIDs as 128 bit unsigned entities, as mentioned in RFC 4122.
|
||||
* This is different than {@link UUID#compareTo(Object)} that compares the UUIDs as signed entities.
|
||||
*
|
||||
* @return a comparator that compares UUIDs as 128 bit unsigned entities.
|
||||
*
|
||||
* @see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7025832">java.lang.UUID compareTo() does not do an unsigned compare</a>
|
||||
* @see <a href="http://tools.ietf.org/html/rfc4122#appendix-A">RFC 4122 Appendix A</a>
|
||||
*/
|
||||
public static Comparator<UUID> comparator() {
|
||||
return COMPARATOR;
|
||||
}
|
||||
|
||||
static final class UUIDComparator implements Comparator<UUID> {
|
||||
public int compare(UUID left, UUID right) {
|
||||
// The ordering is intentionally set up so that the UUIDs
|
||||
// can simply be numerically compared as two *UNSIGNED* numbers
|
||||
if (left.getMostSignificantBits() >>> 32 < right.getMostSignificantBits() >>> 32) {
|
||||
return -1;
|
||||
}
|
||||
else if (left.getMostSignificantBits() >>> 32 > right.getMostSignificantBits() >>> 32) {
|
||||
return 1;
|
||||
}
|
||||
else if ((left.getMostSignificantBits() & 0xffffffffl) < (right.getMostSignificantBits() & 0xffffffffl)) {
|
||||
return -1;
|
||||
}
|
||||
else if ((left.getMostSignificantBits() & 0xffffffffl) > (right.getMostSignificantBits() & 0xffffffffl)) {
|
||||
return 1;
|
||||
}
|
||||
else if (left.getLeastSignificantBits() >>> 32 < right.getLeastSignificantBits() >>> 32) {
|
||||
return -1;
|
||||
}
|
||||
else if (left.getLeastSignificantBits() >>> 32 > right.getLeastSignificantBits() >>> 32) {
|
||||
return 1;
|
||||
}
|
||||
else if ((left.getLeastSignificantBits() & 0xffffffffl) < (right.getLeastSignificantBits() & 0xffffffffl)) {
|
||||
return -1;
|
||||
}
|
||||
else if ((left.getLeastSignificantBits() & 0xffffffffl) > (right.getLeastSignificantBits() & 0xffffffffl)) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A high-resolution timer for use in creating version 1 {@code UUID}s.
|
||||
*/
|
||||
static final class Clock {
|
||||
// Java: 0:00, Jan. 1st, 1970 vs UUID: 0:00, Oct 15th, 1582
|
||||
private static final long JAVA_EPOCH_OFFSET_HUNDRED_NANOS = 122192928000000000L;
|
||||
|
||||
private static int clockSeq = SECURE_RANDOM.nextInt();
|
||||
|
||||
private static long initialNanos;
|
||||
private static long initialTime;
|
||||
|
||||
private static long lastMeasuredTime;
|
||||
private static long lastTime;
|
||||
|
||||
static {
|
||||
initClock();
|
||||
}
|
||||
|
||||
private static void initClock() {
|
||||
long millis = System.currentTimeMillis();
|
||||
long nanos = System.nanoTime();
|
||||
|
||||
initialTime = JAVA_EPOCH_OFFSET_HUNDRED_NANOS + millis * 10000 + (nanos / 100) % 10000;
|
||||
initialNanos = nanos;
|
||||
}
|
||||
|
||||
public static synchronized long currentTimeHundredNanos() {
|
||||
// Measure delta since init and compute accurate time
|
||||
long time;
|
||||
|
||||
while ((time = initialTime + (System.nanoTime() - initialNanos) / 100) < lastMeasuredTime) {
|
||||
// Reset clock seq (should happen VERY rarely)
|
||||
initClock();
|
||||
clockSeq++;
|
||||
}
|
||||
|
||||
lastMeasuredTime = time;
|
||||
|
||||
if (time <= lastTime) {
|
||||
// This typically means the clock isn't accurate enough, use auto-incremented time.
|
||||
// It is possible that more timestamps than available are requested for
|
||||
// each time unit in the system clock, but that is extremely unlikely.
|
||||
// TODO: RFC 4122 says we should wait in the case of too many requests...
|
||||
time = ++lastTime;
|
||||
}
|
||||
else {
|
||||
lastTime = time;
|
||||
}
|
||||
|
||||
return time;
|
||||
}
|
||||
|
||||
public static synchronized long getClockSequence() {
|
||||
return clockSeq & 0x3fff;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Static inner class for 1.5 compatibility.
|
||||
*/
|
||||
static final class MacAddressFinder {
|
||||
public static long[] getMacAddressNodes() {
|
||||
List<Long> nodeAddresses = new ArrayList<Long>();
|
||||
try {
|
||||
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
|
||||
|
||||
if (interfaces != null) {
|
||||
while (interfaces.hasMoreElements()) {
|
||||
NetworkInterface nic = interfaces.nextElement();
|
||||
|
||||
if (!nic.isVirtual()) {
|
||||
long nodeAddress = 0;
|
||||
|
||||
byte[] hardware = nic.getHardwareAddress(); // 1.6 method
|
||||
|
||||
if (hardware != null && hardware.length == 6 && hardware[1] != (byte) 0xff) {
|
||||
// Network byte order
|
||||
nodeAddress |= (long) (hardware[0] & 0xff) << 40;
|
||||
nodeAddress |= (long) (hardware[1] & 0xff) << 32;
|
||||
nodeAddress |= (long) (hardware[2] & 0xff) << 24;
|
||||
nodeAddress |= (long) (hardware[3] & 0xff) << 16;
|
||||
nodeAddress |= (long) (hardware[4] & 0xff) << 8;
|
||||
nodeAddress |= (long) (hardware[5] & 0xff);
|
||||
|
||||
nodeAddresses.add(nodeAddress);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (SocketException ex) {
|
||||
return null;
|
||||
}
|
||||
|
||||
long[] unwrapped = new long[nodeAddresses.size()];
|
||||
for (int i = 0, nodeAddressesSize = nodeAddresses.size(); i < nodeAddressesSize; i++) {
|
||||
unwrapped[i] = nodeAddresses.get(i);
|
||||
}
|
||||
|
||||
return unwrapped;
|
||||
}
|
||||
}
|
||||
}
|
||||
+1287
File diff suppressed because it is too large
Load Diff
Executable
+398
@@ -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>
|
||||
* <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', '\u00e6',
|
||||
'\u00f8', '\u00e5', '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', '\u00c6', '\u00d8', '\u00c5', '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-�A-�0-9]|.|_|-)*)");
|
||||
}
|
||||
|
||||
// Free-pass character '?'
|
||||
else if (isFreePassCharacter(stringMaskChar)) {
|
||||
regexpBuffer.append("([a-�A_�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 ------*/
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
+18
@@ -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();
|
||||
}
|
||||
}
|
||||
+18
@@ -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();
|
||||
}
|
||||
}
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
package com.twelvemonkeys.lang;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import junit.framework.AssertionFailedError;
|
||||
|
||||
/**
|
||||
* “If it walks like a duck, looks like a duck, quacks like a duck, it must be…”
|
||||
* <p/>
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-sandbox/src/test/java/com/twelvemonkeys/lang/DuckTypeTestCase.java#1 $
|
||||
*/
|
||||
public class DuckTypeTestCase extends TestCase {
|
||||
|
||||
static public interface Eatable {
|
||||
}
|
||||
|
||||
static public interface Vegetable extends Eatable {
|
||||
}
|
||||
|
||||
static public interface Meat extends Eatable {
|
||||
}
|
||||
|
||||
static public interface Animal {
|
||||
void walk();
|
||||
boolean canEat(Eatable pFood);
|
||||
void eat(Eatable pFood);
|
||||
}
|
||||
|
||||
static public interface Bird extends Animal {
|
||||
void fly();
|
||||
}
|
||||
|
||||
static public interface Duck extends Bird {
|
||||
void quack();
|
||||
}
|
||||
|
||||
static public class DuckLookALike {
|
||||
private boolean mWalking;
|
||||
private boolean mFlying;
|
||||
private boolean mQuacking;
|
||||
|
||||
public void walk() {
|
||||
mWalking = true;
|
||||
}
|
||||
|
||||
public void fly() {
|
||||
mFlying = true;
|
||||
}
|
||||
|
||||
public void quack() {
|
||||
mQuacking = true;
|
||||
}
|
||||
|
||||
void reset() {
|
||||
mWalking = mFlying = mQuacking = false;
|
||||
}
|
||||
|
||||
boolean verify() {
|
||||
return mWalking && mFlying && mQuacking;
|
||||
}
|
||||
}
|
||||
|
||||
static public class Swan extends DuckLookALike {
|
||||
}
|
||||
|
||||
static public class VeggieEater {
|
||||
private boolean mHappy;
|
||||
|
||||
public boolean canEat(Eatable pFood) {
|
||||
return pFood instanceof Vegetable;
|
||||
}
|
||||
|
||||
public void eat(Eatable pFood) {
|
||||
if (pFood == this) {
|
||||
throw new IllegalArgumentException("CantEatMyselfException: duh");
|
||||
}
|
||||
if (!canEat(pFood)) {
|
||||
throw new NotVegetableException("yuck");
|
||||
}
|
||||
|
||||
mHappy = true;
|
||||
}
|
||||
|
||||
void reset() {
|
||||
mHappy = false;
|
||||
}
|
||||
|
||||
boolean verify() {
|
||||
return mHappy;
|
||||
}
|
||||
}
|
||||
|
||||
static class NotVegetableException extends RuntimeException {
|
||||
public NotVegetableException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
public static void testTooManyThingsAtOnce() {
|
||||
DuckLookALike lookALike = new DuckLookALike();
|
||||
VeggieEater veggieEater = new VeggieEater();
|
||||
|
||||
Object obj = DuckType.implement(new Class[]{Duck.class, Meat.class},
|
||||
new Object[]{lookALike, veggieEater});
|
||||
assertTrue(obj instanceof Duck);
|
||||
assertTrue(obj instanceof Meat);
|
||||
Duck duck = (Duck) obj;
|
||||
|
||||
Bird another = (Bird) DuckType.implement(new Class[]{Duck.class, Meat.class},
|
||||
new Object[]{lookALike, veggieEater});
|
||||
|
||||
Duck uglyDuckling = (Duck) DuckType.implement(new Class[] {Duck.class, Meat.class},
|
||||
new Object[] {new Swan(), new VeggieEater()});
|
||||
|
||||
assertNotNull(duck.toString());
|
||||
|
||||
assertTrue("Duck is supposed to equal itself (identity crisis)", duck.equals(duck));
|
||||
|
||||
assertEquals("Duck is supposed to equal other duck with same stuffing", duck, another);
|
||||
|
||||
assertFalse("Some ducks are more equal than others", duck.equals(uglyDuckling));
|
||||
|
||||
duck.walk();
|
||||
duck.quack();
|
||||
duck.quack();
|
||||
duck.fly();
|
||||
|
||||
assertTrue("Duck is supposed to quack", lookALike.verify());
|
||||
|
||||
Vegetable cabbage = new Vegetable() {};
|
||||
assertTrue("Duck is supposed to like cabbage", duck.canEat(cabbage));
|
||||
duck.eat(cabbage);
|
||||
assertTrue("Duck is supposed to eat vegetables", veggieEater.verify());
|
||||
|
||||
veggieEater.reset();
|
||||
|
||||
Throwable exception = null;
|
||||
try {
|
||||
duck.eat((Meat) uglyDuckling);
|
||||
fail("Duck ate distant cousin");
|
||||
}
|
||||
catch (AssertionFailedError e) {
|
||||
throw e;
|
||||
}
|
||||
catch (Throwable t) {
|
||||
exception = t;
|
||||
}
|
||||
assertTrue("Incorrect quack: " + exception, exception instanceof NotVegetableException);
|
||||
|
||||
|
||||
// TODO: There's a flaw in the design here..
|
||||
// The "this" keyword don't work well with proxies..
|
||||
|
||||
// Something that could possibly work, is:
|
||||
// All proxy-aware delegates need a method getThis() / getSelf()...
|
||||
// (using a field won't work for delegates that are part of multiple
|
||||
// proxies).
|
||||
// The default implementation should only return "this"..
|
||||
// TBD: How do we know which proxy the current delegate is part of?
|
||||
|
||||
exception = null;
|
||||
try {
|
||||
duck.eat((Meat) duck);
|
||||
fail("Duck ate itself");
|
||||
}
|
||||
catch (AssertionFailedError e) {
|
||||
throw e;
|
||||
}
|
||||
catch (Throwable t) {
|
||||
exception = t;
|
||||
}
|
||||
assertTrue("Duck tried to eat itself: " + exception, exception instanceof IllegalArgumentException);
|
||||
}
|
||||
|
||||
public void testExpandedArgs() {
|
||||
Object walker = new Object() {
|
||||
public void walk() {
|
||||
}
|
||||
};
|
||||
Object eater = new Object() {
|
||||
// Assignable, but not direct match
|
||||
public boolean canEat(Object pFood) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Assignable, but not direct match
|
||||
public void eat(Object pFood) {
|
||||
}
|
||||
};
|
||||
|
||||
Animal rat = (Animal) DuckType.implement(new Class[]{Animal.class, Meat.class},
|
||||
new Object[]{walker, eater});
|
||||
|
||||
assertNotNull(rat);
|
||||
assertTrue(rat instanceof Meat);
|
||||
|
||||
// Rats eat everything
|
||||
Eatable smellyFood = new Eatable() {boolean tastesVeryBad = true;};
|
||||
assertTrue("Rat did not eat smelly food", rat.canEat(smellyFood));
|
||||
}
|
||||
|
||||
public void testExpandedArgsFail() {
|
||||
try {
|
||||
Object walker = new Object() {
|
||||
public void walk() {
|
||||
}
|
||||
};
|
||||
Object eater = new Object() {
|
||||
// Not assignable return type
|
||||
public int canEat(Eatable pFood) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Assignable, but not direct match
|
||||
public void eat(Object pFood) {
|
||||
}
|
||||
};
|
||||
DuckType.implement(new Class[]{Animal.class},
|
||||
new Object[]{walker, eater});
|
||||
|
||||
fail("This kind of animal won't live long");
|
||||
}
|
||||
catch (DuckType.NoMatchingMethodException e) {
|
||||
}
|
||||
}
|
||||
|
||||
public void testStubAbstract() {
|
||||
Object obj = DuckType.implement(new Class[]{Animal.class},
|
||||
new Object[]{new Object()}, true);
|
||||
assertTrue(obj instanceof Animal);
|
||||
Animal unicorn = (Animal) obj;
|
||||
assertNotNull(unicorn);
|
||||
|
||||
// Should create a meaningful string representation
|
||||
assertNotNull(unicorn.toString());
|
||||
|
||||
// Unicorns don't fly, as they are only an abstract idea..
|
||||
try {
|
||||
unicorn.walk();
|
||||
fail("Unicorns should not fly, as they are only an abstract idea");
|
||||
}
|
||||
catch (AbstractMethodError e) {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
* Copyright (c) 2012, 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 org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* ExceptionUtilTest
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @author last modified by $Author: haraldk$
|
||||
* @version $Id: ExceptionUtilTest.java,v 1.0 11.04.12 16:07 haraldk Exp$
|
||||
*/
|
||||
@Ignore("Under development")
|
||||
public class ExceptionUtilTest {
|
||||
@Test(expected = BadException.class)
|
||||
@SuppressWarnings({"InfiniteLoopStatement"})
|
||||
public void test() {
|
||||
while (true) {
|
||||
foo();
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "varargs"})
|
||||
private static void foo() {
|
||||
try {
|
||||
bar();
|
||||
}
|
||||
catch (Throwable t) {
|
||||
ExceptionUtil.handle(t,
|
||||
new ExceptionUtil.ThrowableHandler<IOException>(IOException.class) {
|
||||
public void handle(final IOException pThrowable) {
|
||||
System.out.println("IOException: " + pThrowable + " handled");
|
||||
}
|
||||
},
|
||||
new ExceptionUtil.ThrowableHandler<Exception>(SQLException.class, NumberFormatException.class) {
|
||||
public void handle(final Exception pThrowable) {
|
||||
System.out.println("Exception: " + pThrowable + " handled");
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private static void bar() {
|
||||
baz();
|
||||
}
|
||||
|
||||
@SuppressWarnings({"ThrowableInstanceNeverThrown"})
|
||||
private static void baz() {
|
||||
double random = Math.random();
|
||||
if (random < (2.0 / 3.0)) {
|
||||
ExceptionUtil.throwUnchecked(new FileNotFoundException("FNF Boo"));
|
||||
}
|
||||
if (random < (5.0 / 6.0)) {
|
||||
ExceptionUtil.throwUnchecked(new SQLException("SQL Boo"));
|
||||
}
|
||||
else {
|
||||
ExceptionUtil.throwUnchecked(new BadException("Some Boo"));
|
||||
}
|
||||
}
|
||||
|
||||
static final class BadException extends Exception {
|
||||
public BadException(String s) {
|
||||
super(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+578
@@ -0,0 +1,578 @@
|
||||
/*
|
||||
* Copyright (c) 2009, 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;
|
||||
|
||||
import com.twelvemonkeys.util.MappedBeanFactory;
|
||||
import junit.framework.AssertionFailedError;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.event.ActionListener;
|
||||
import java.beans.IntrospectionException;
|
||||
import java.beans.PropertyChangeListener;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.io.*;
|
||||
|
||||
/**
|
||||
* MappedBeanFactoryTestCase
|
||||
*
|
||||
* @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-sandbox/src/test/java/com/twelvemonkeys/sandbox/MappedBeanFactoryTestCase.java#1 $
|
||||
*/
|
||||
public class MappedBeanFactoryTestCase {
|
||||
|
||||
public static interface Foo {
|
||||
boolean isFoo();
|
||||
|
||||
int getBar();
|
||||
void setBar(int bar);
|
||||
|
||||
Rectangle getBounds();
|
||||
void setBounds(Rectangle bounds);
|
||||
}
|
||||
|
||||
public static interface DefaultFoo extends Foo {
|
||||
// @MappedBeanFactory.DefaultBooleanValue
|
||||
@MappedBeanFactory.DefaultValue(booleanValue = false)
|
||||
boolean isFoo();
|
||||
|
||||
@MappedBeanFactory.DefaultIntValue
|
||||
int getBar();
|
||||
void setBar(int bar);
|
||||
|
||||
Rectangle getBounds();
|
||||
void setBounds(Rectangle bounds);
|
||||
|
||||
@SuppressWarnings({"CloneDoesntDeclareCloneNotSupportedException"})
|
||||
DefaultFoo clone();
|
||||
}
|
||||
|
||||
static interface ObservableFoo extends DefaultFoo {
|
||||
@MappedBeanFactory.DefaultBooleanValue(true)
|
||||
boolean isFoo();
|
||||
|
||||
@MappedBeanFactory.DefaultIntValue(1)
|
||||
int getBar();
|
||||
|
||||
@MappedBeanFactory.NotNull
|
||||
Rectangle getBounds();
|
||||
|
||||
@MappedBeanFactory.Observable
|
||||
void setBounds(@MappedBeanFactory.NotNull Rectangle bounds);
|
||||
|
||||
// TODO: This method should be implicitly supported, and throw IllegalArgument, if NoSuchProperty
|
||||
// TODO: An observable interface to extend?
|
||||
void addPropertyChangeListener(String property, PropertyChangeListener listener);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToString() {
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class);
|
||||
assertNotNull(foo);
|
||||
assertNotNull(foo.toString());
|
||||
assertTrue(foo.toString().contains(DefaultFoo.class.getName()));
|
||||
|
||||
// TODO: Consider this:
|
||||
// assertTrue(foo.toString().contains("foo=false"));
|
||||
// assertTrue(foo.toString().contains("bar=0"));
|
||||
// assertTrue(foo.toString().contains("bounds=null"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClone() {
|
||||
DefaultFoo foo = MappedBeanFactory.as(DefaultFoo.class, Collections.singletonMap("foo", true));
|
||||
DefaultFoo clone = foo.clone();
|
||||
assertNotSame(foo, clone);
|
||||
assertEquals(foo, clone);
|
||||
assertEquals(foo.hashCode(), clone.hashCode());
|
||||
assertEquals(foo.isFoo(), clone.isFoo());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSerializable() throws IOException, ClassNotFoundException {
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class, Collections.singletonMap("foo", true));
|
||||
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
ObjectOutputStream outputStream = new ObjectOutputStream(bytes);
|
||||
outputStream.writeObject(foo);
|
||||
|
||||
ObjectInputStream inputStream = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()));
|
||||
Foo bar = (Foo) inputStream.readObject();
|
||||
|
||||
assertNotSame(foo, bar);
|
||||
assertEquals(foo, bar);
|
||||
assertEquals(foo.hashCode(), bar.hashCode());
|
||||
assertEquals(foo.isFoo(), bar.isFoo());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotEqualsNull() {
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class);
|
||||
|
||||
@SuppressWarnings({"ObjectEqualsNull"})
|
||||
boolean equalsNull = foo.equals(null);
|
||||
|
||||
assertFalse(equalsNull);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEqualsSelf() {
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class, new HashMap<String, Object>() {
|
||||
@SuppressWarnings({"EqualsWhichDoesntCheckParameterClass"})
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
throw new AssertionFailedError("Don't need to test map for equals if same object");
|
||||
}
|
||||
});
|
||||
|
||||
assertTrue(foo.equals(foo));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEqualsOther() {
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class);
|
||||
Foo other = MappedBeanFactory.as(DefaultFoo.class);
|
||||
|
||||
assertEquals(foo, other);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEqualsOtherModifiedSameValue() {
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class, new HashMap<String, Object>());
|
||||
Foo other = MappedBeanFactory.as(DefaultFoo.class, new HashMap<String, Object>(Collections.singletonMap("bar", 0)));
|
||||
|
||||
assertEquals(foo, other);
|
||||
|
||||
// No real change
|
||||
other.setBar(foo.getBar());
|
||||
assertTrue(foo.equals(other));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotEqualsOtherModified() {
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class);
|
||||
Foo other = MappedBeanFactory.as(DefaultFoo.class);
|
||||
|
||||
assertEquals(foo, other);
|
||||
|
||||
// Real change
|
||||
other.setBar(42);
|
||||
assertFalse(foo.equals(other));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEqualsSubclass() {
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class);
|
||||
|
||||
Foo sub = MappedBeanFactory.as(ObservableFoo.class);
|
||||
assertEquals(foo, sub);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotEqualsDifferentValues() {
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class);
|
||||
Foo bar = MappedBeanFactory.as(DefaultFoo.class, Collections.singletonMap("bar", true));
|
||||
assertFalse(foo.equals(bar));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotEqualsDifferentClass() {
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class);
|
||||
ActionListener actionListener = MappedBeanFactory.as(ActionListener.class);
|
||||
assertFalse(foo.equals(actionListener));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBooleanReadOnly() {
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class, Collections.singletonMap("foo", true));
|
||||
|
||||
assertNotNull(foo);
|
||||
assertEquals(true, foo.isFoo());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBooleanEmpty() {
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class, new HashMap<String, Object>());
|
||||
|
||||
assertNotNull(foo);
|
||||
|
||||
try {
|
||||
foo.isFoo();
|
||||
fail("Expected NullPointerException");
|
||||
}
|
||||
catch (NullPointerException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBooleanEmptyWithConverter() {
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class, new HashMap<String, Object>(), new NullBooleanConverter(true));
|
||||
|
||||
assertNotNull(foo);
|
||||
|
||||
assertEquals(true, foo.isFoo());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIntReadOnly() {
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class, Collections.singletonMap("bar", 1));
|
||||
|
||||
assertNotNull(foo);
|
||||
assertEquals(1, foo.getBar());
|
||||
|
||||
try {
|
||||
foo.setBar(42);
|
||||
fail("Expected UnsupportedOperationException");
|
||||
}
|
||||
catch (UnsupportedOperationException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIntReadWrite() {
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class, new HashMap<String, Object>(Collections.singletonMap("bar", 1)));
|
||||
|
||||
assertNotNull(foo);
|
||||
assertEquals(1, foo.getBar());
|
||||
|
||||
foo.setBar(42);
|
||||
assertEquals(42, foo.getBar());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIntNull() {
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class, new HashMap<String, Object>(Collections.singletonMap("bar", null)));
|
||||
|
||||
assertNotNull(foo);
|
||||
|
||||
// TODO: Handle null-values smarter, maybe throw a better exception?
|
||||
// TODO: Consider allowing custom initializers?
|
||||
try {
|
||||
foo.getBar();
|
||||
fail("Expected NullPointerException");
|
||||
}
|
||||
catch (NullPointerException expected) {
|
||||
}
|
||||
|
||||
foo.setBar(42);
|
||||
assertEquals(42, foo.getBar());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIntNullWithConverter() {
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class, new HashMap<String, Object>(Collections.singletonMap("bar", null)), new NullIntConverter(1));
|
||||
|
||||
assertNotNull(foo);
|
||||
|
||||
assertEquals(1, foo.getBar());
|
||||
|
||||
foo.setBar(42);
|
||||
assertEquals(42, foo.getBar());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIntWrongType() {
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class, new HashMap<String, Object>(Collections.singletonMap("bar", "1")));
|
||||
|
||||
assertNotNull(foo);
|
||||
|
||||
// TODO: Handle conversion smarter, maybe throw a better exception?
|
||||
try {
|
||||
foo.getBar();
|
||||
fail("Expected ClassCastException");
|
||||
}
|
||||
catch (ClassCastException expected) {
|
||||
}
|
||||
|
||||
// TODO: Should we allow changing type?
|
||||
try {
|
||||
foo.setBar(42);
|
||||
fail("Expected ClassCastException");
|
||||
}
|
||||
catch (ClassCastException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBounds() {
|
||||
Rectangle rectangle = new Rectangle(2, 2, 4, 4);
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class, new HashMap<String, Object>(Collections.singletonMap("bounds", rectangle)));
|
||||
|
||||
assertNotNull(foo);
|
||||
assertEquals(rectangle, foo.getBounds());
|
||||
|
||||
foo.setBounds(new Rectangle());
|
||||
assertEquals(new Rectangle(), foo.getBounds());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBoundsNull() {
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class, new HashMap<String, Object>(Collections.singletonMap("bounds", null)));
|
||||
|
||||
assertNotNull(foo);
|
||||
assertNull(foo.getBounds());
|
||||
|
||||
Rectangle rectangle = new Rectangle(2, 2, 4, 4);
|
||||
foo.setBounds(rectangle);
|
||||
assertEquals(rectangle, foo.getBounds());
|
||||
|
||||
foo.setBounds(null);
|
||||
assertEquals(null, foo.getBounds());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBoundsNullWithConverter() {
|
||||
// TODO: Allow @NotNull annotations, to say that null is not a valid return value/paramter?
|
||||
Foo foo = MappedBeanFactory.as(ObservableFoo.class, new HashMap<String, Object>(Collections.singletonMap("bounds", null)), new MappedBeanFactory.Converter<Void, Rectangle>() {
|
||||
public Class<Void> getFromType() {
|
||||
return Void.class;
|
||||
}
|
||||
|
||||
public Class<Rectangle> getToType() {
|
||||
return Rectangle.class;
|
||||
}
|
||||
|
||||
public Rectangle convert(Void value, Rectangle old) {
|
||||
return new Rectangle(10, 10, 10, 10);
|
||||
}
|
||||
});
|
||||
|
||||
assertNotNull(foo);
|
||||
// TODO: The current problem is that null is okay as return value, even if not specified for interface...
|
||||
assertEquals(new Rectangle(10, 10, 10, 10), foo.getBounds());
|
||||
|
||||
Rectangle rectangle = new Rectangle(2, 2, 4, 4);
|
||||
foo.setBounds(rectangle);
|
||||
assertEquals(rectangle, foo.getBounds());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBoundsAsMapWithConverter() throws IntrospectionException {
|
||||
Rectangle rectangle = new Rectangle(2, 2, 4, 4);
|
||||
Map<String, Object> recAsMap = new HashMap<String, Object>();
|
||||
recAsMap.put("x", 2);
|
||||
recAsMap.put("y", 2);
|
||||
recAsMap.put("width", 4);
|
||||
recAsMap.put("height", 4);
|
||||
|
||||
HashMap<String, Object> map = new HashMap<String, Object>(Collections.singletonMap("bounds", recAsMap));
|
||||
|
||||
// TODO: Allow for registering superclasses/interfaces like Map...
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class, map, new MapRectangleConverter(), new RectangleMapConverter());
|
||||
|
||||
assertNotNull(foo);
|
||||
|
||||
assertEquals(rectangle, foo.getBounds());
|
||||
|
||||
foo.setBounds(new Rectangle());
|
||||
assertEquals(new Rectangle(), foo.getBounds());
|
||||
assertEquals(recAsMap, map.get("bounds"));
|
||||
assertSame(recAsMap, map.get("bounds"));
|
||||
|
||||
// TODO: The converter should maybe not have to handle this
|
||||
foo.setBounds(null);
|
||||
assertNull(foo.getBounds());
|
||||
assertEquals(recAsMap, map.get("bounds"));
|
||||
assertSame(recAsMap, map.get("bounds"));
|
||||
|
||||
Rectangle bounds = new Rectangle(1, 1, 1, 1);
|
||||
foo.setBounds(bounds);
|
||||
assertEquals(bounds, foo.getBounds());
|
||||
assertEquals(1, foo.getBounds().x);
|
||||
assertEquals(1, foo.getBounds().y);
|
||||
assertEquals(1, foo.getBounds().width);
|
||||
assertEquals(1, foo.getBounds().height);
|
||||
assertEquals(recAsMap, map.get("bounds"));
|
||||
assertSame(recAsMap, map.get("bounds"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSpeed() {
|
||||
// How many times faster may the direct access be, before we declare failure?
|
||||
final int threshold = 50;
|
||||
|
||||
Foo foo = MappedBeanFactory.as(DefaultFoo.class, new HashMap<String, Object>(Collections.singletonMap("foo", false)));
|
||||
|
||||
Foo bar = new Foo() {
|
||||
public boolean isFoo() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public int getBar() {
|
||||
throw new UnsupportedOperationException("Method getBar not implemented");
|
||||
}
|
||||
|
||||
public void setBar(int bar) {
|
||||
throw new UnsupportedOperationException("Method setBar not implemented");
|
||||
}
|
||||
|
||||
public Rectangle getBounds() {
|
||||
throw new UnsupportedOperationException("Method getBounds not implemented"); // TODO: Implement
|
||||
}
|
||||
|
||||
public void setBounds(Rectangle bounds) {
|
||||
throw new UnsupportedOperationException("Method setBounds not implemented"); // TODO: Implement
|
||||
}
|
||||
};
|
||||
|
||||
final int warmup = 50005;
|
||||
final int iter = 2000000;
|
||||
for (int i = 0; i < warmup; i++) {
|
||||
if (foo.isFoo()) {
|
||||
fail();
|
||||
}
|
||||
if (bar.isFoo()) {
|
||||
fail();
|
||||
}
|
||||
}
|
||||
|
||||
long startProxy = System.nanoTime();
|
||||
for (int i = 0; i < iter; i++) {
|
||||
if (foo.isFoo()) {
|
||||
fail();
|
||||
}
|
||||
}
|
||||
long proxyTime = System.nanoTime() - startProxy;
|
||||
|
||||
long startJava = System.nanoTime();
|
||||
for (int i = 0; i < iter; i++) {
|
||||
if (bar.isFoo()) {
|
||||
fail();
|
||||
}
|
||||
}
|
||||
long javaTime = System.nanoTime() - startJava;
|
||||
|
||||
assertTrue(
|
||||
String.format(
|
||||
"Proxy time (%1$,d ms) greater than %3$d times direct invocation (%2$,d ms)",
|
||||
proxyTime / 1000, javaTime / 1000, threshold
|
||||
),
|
||||
proxyTime < threshold * javaTime);
|
||||
}
|
||||
|
||||
private static class MapRectangleConverter implements MappedBeanFactory.Converter<HashMap, Rectangle> {
|
||||
public Class<HashMap> getFromType() {
|
||||
return HashMap.class;
|
||||
}
|
||||
|
||||
public Class<Rectangle> getToType() {
|
||||
return Rectangle.class;
|
||||
}
|
||||
|
||||
public Rectangle convert(final HashMap pMap, Rectangle pOldValue) {
|
||||
if (pMap == null || pMap.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Rectangle rectangle = pOldValue != null ? pOldValue : new Rectangle();
|
||||
|
||||
rectangle.x = (Integer) pMap.get("x");
|
||||
rectangle.y = (Integer) pMap.get("y");
|
||||
rectangle.width = (Integer) pMap.get("width");
|
||||
rectangle.height = (Integer) pMap.get("height");
|
||||
|
||||
return rectangle;
|
||||
}
|
||||
}
|
||||
|
||||
private static class RectangleMapConverter implements MappedBeanFactory.Converter<Rectangle, HashMap> {
|
||||
public Class<HashMap> getToType() {
|
||||
return HashMap.class;
|
||||
}
|
||||
|
||||
public Class<Rectangle> getFromType() {
|
||||
return Rectangle.class;
|
||||
}
|
||||
|
||||
public HashMap convert(final Rectangle pRectangle, HashMap pOldValue) {
|
||||
@SuppressWarnings("unchecked")
|
||||
HashMap<String, Integer> map = pOldValue != null ? pOldValue : new HashMap<String, Integer>();
|
||||
|
||||
if (pRectangle != null) {
|
||||
map.put("x", pRectangle.x);
|
||||
map.put("y", pRectangle.y);
|
||||
map.put("width", pRectangle.width);
|
||||
map.put("height", pRectangle.height);
|
||||
}
|
||||
else {
|
||||
map.remove("x");
|
||||
map.remove("y");
|
||||
map.remove("width");
|
||||
map.remove("height");
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
}
|
||||
|
||||
private static class NullIntConverter implements MappedBeanFactory.Converter<Void, Integer> {
|
||||
private Integer mInitialValue;
|
||||
|
||||
public NullIntConverter(int pValue) {
|
||||
mInitialValue = pValue;
|
||||
}
|
||||
|
||||
public Class<Void> getFromType() {
|
||||
return Void.class;
|
||||
}
|
||||
|
||||
public Class<Integer> getToType() {
|
||||
return Integer.class;
|
||||
}
|
||||
|
||||
public Integer convert(Void value, Integer old) {
|
||||
return mInitialValue;
|
||||
}
|
||||
}
|
||||
|
||||
private static class NullBooleanConverter implements MappedBeanFactory.Converter<Void, Boolean> {
|
||||
private Boolean mInitialValue;
|
||||
|
||||
public NullBooleanConverter(boolean pValue) {
|
||||
mInitialValue = pValue;
|
||||
}
|
||||
|
||||
public Class<Void> getFromType() {
|
||||
return Void.class;
|
||||
}
|
||||
|
||||
public Class<Boolean> getToType() {
|
||||
return Boolean.class;
|
||||
}
|
||||
|
||||
public Boolean convert(Void value, Boolean old) {
|
||||
return mInitialValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
package com.twelvemonkeys.util;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class UUIDFactoryTest {
|
||||
private static final String EXAMPLE_COM_UUID = "http://www.example.com/uuid/";
|
||||
|
||||
// Nil UUID
|
||||
|
||||
@Test
|
||||
public void testNilUUIDVariant() {
|
||||
assertEquals(0, UUIDFactory.NIL.variant());
|
||||
}
|
||||
@Test
|
||||
public void testNilUUIDVersion() {
|
||||
assertEquals(0, UUIDFactory.NIL.version());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNilUUIDFromStringRep() {
|
||||
assertEquals(UUID.fromString("00000000-0000-0000-0000-000000000000"), UUIDFactory.NIL);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNilUUIDFromLong() {
|
||||
assertEquals(new UUID(0l, 0l), UUIDFactory.NIL);
|
||||
}
|
||||
|
||||
// Version 3 UUIDs (for comparison with v5)
|
||||
|
||||
@Test
|
||||
public void testVersion3NameBasedMD5Variant() throws UnsupportedEncodingException {
|
||||
assertEquals(2, UUID.nameUUIDFromBytes(EXAMPLE_COM_UUID.getBytes("UTF-8")).variant());
|
||||
}
|
||||
@Test
|
||||
public void testVersion3NameBasedMD5Version() throws UnsupportedEncodingException {
|
||||
assertEquals(3, UUID.nameUUIDFromBytes(EXAMPLE_COM_UUID.getBytes("UTF-8")).version());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion3NameBasedMD5Equals() throws UnsupportedEncodingException {
|
||||
UUID a = UUID.nameUUIDFromBytes(EXAMPLE_COM_UUID.getBytes("UTF-8"));
|
||||
UUID b = UUID.nameUUIDFromBytes(EXAMPLE_COM_UUID.getBytes("UTF-8"));
|
||||
assertEquals(a, b);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion3NameBasedMD5NotEqualSHA1() throws UnsupportedEncodingException {
|
||||
UUID a = UUID.nameUUIDFromBytes(EXAMPLE_COM_UUID.getBytes("UTF-8"));
|
||||
UUID b = UUIDFactory.nameUUIDv5FromBytes(EXAMPLE_COM_UUID.getBytes("UTF-8"));
|
||||
assertFalse(a.equals(b));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion3NameBasedMD5FromStringRep() throws UnsupportedEncodingException {
|
||||
UUID a = UUID.nameUUIDFromBytes(EXAMPLE_COM_UUID.getBytes("UTF-8"));
|
||||
assertEquals(a, UUID.fromString(a.toString()));
|
||||
}
|
||||
|
||||
// Version 5 UUIDs
|
||||
|
||||
@Test
|
||||
public void testVersion5NameBasedSHA1Variant() throws UnsupportedEncodingException {
|
||||
UUID a = UUIDFactory.nameUUIDv5FromBytes(EXAMPLE_COM_UUID.getBytes("UTF-8"));
|
||||
assertEquals(2, a.variant());
|
||||
}
|
||||
@Test
|
||||
public void testVersion5NameBasedSHA1Version() throws UnsupportedEncodingException {
|
||||
UUID a = UUIDFactory.nameUUIDv5FromBytes(EXAMPLE_COM_UUID.getBytes("UTF-8"));
|
||||
assertEquals(5, a.version());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion5NameBasedSHA1Equals() throws UnsupportedEncodingException {
|
||||
UUID a = UUIDFactory.nameUUIDv5FromBytes(EXAMPLE_COM_UUID.getBytes("UTF-8"));
|
||||
UUID b = UUIDFactory.nameUUIDv5FromBytes(EXAMPLE_COM_UUID.getBytes("UTF-8"));
|
||||
assertEquals(a, b);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion5NameBasedSHA1Different() throws UnsupportedEncodingException {
|
||||
Random random = new Random();
|
||||
byte[] data = new byte[128];
|
||||
random.nextBytes(data);
|
||||
|
||||
UUID a = UUIDFactory.nameUUIDv5FromBytes(data);
|
||||
|
||||
// Swap a random byte with its "opposite"
|
||||
int i;
|
||||
while (data[i = random.nextInt(data.length)] == data[data.length - 1 - i]) {}
|
||||
data[i] = data[data.length - 1 - i];
|
||||
|
||||
UUID b = UUIDFactory.nameUUIDv5FromBytes(data);
|
||||
|
||||
assertFalse(a.equals(b));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion5NameBasedSHA1NotEqualMD5() throws UnsupportedEncodingException {
|
||||
UUID a = UUIDFactory.nameUUIDv5FromBytes(EXAMPLE_COM_UUID.getBytes("UTF-8"));
|
||||
UUID b = UUID.nameUUIDFromBytes(EXAMPLE_COM_UUID.getBytes("UTF-8"));
|
||||
assertFalse(a.equals(b));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion5NameBasedSHA1FromStringRep() throws UnsupportedEncodingException {
|
||||
UUID a = UUIDFactory.nameUUIDv5FromBytes(EXAMPLE_COM_UUID.getBytes("UTF-8"));
|
||||
assertEquals(a, UUID.fromString(a.toString()));
|
||||
}
|
||||
|
||||
// Version 1 UUIDs
|
||||
|
||||
@Test
|
||||
public void testVersion1NodeBasedVariant() {
|
||||
assertEquals(2, UUIDFactory.timeNodeBasedUUID().variant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion1NodeBasedVersion() {
|
||||
assertEquals(1, UUIDFactory.timeNodeBasedUUID().version());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion1NodeBasedFromStringRep() {
|
||||
UUID uuid = UUIDFactory.timeNodeBasedUUID();
|
||||
assertEquals(uuid, UUID.fromString(uuid.toString()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion1NodeBasedMacAddress() {
|
||||
UUID uuid = UUIDFactory.timeNodeBasedUUID();
|
||||
assertEquals(UUIDFactory.MAC_ADDRESS_NODE, uuid.node());
|
||||
// TODO: Test that this is actually a Mac address from the local computer, or specified through system property?
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion1NodeBasedClockSeq() {
|
||||
UUID uuid = UUIDFactory.timeNodeBasedUUID();
|
||||
assertEquals(UUIDFactory.Clock.getClockSequence(), uuid.clockSequence());
|
||||
|
||||
// Test time fields (within reasonable limits +/- 100 ms or so?)
|
||||
assertEquals(UUIDFactory.Clock.currentTimeHundredNanos(), uuid.timestamp(), 1e6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion1NodeBasedTimestamp() {
|
||||
UUID uuid = UUIDFactory.timeNodeBasedUUID();
|
||||
// Test time fields (within reasonable limits +/- 100 ms or so?)
|
||||
assertEquals(UUIDFactory.Clock.currentTimeHundredNanos(), uuid.timestamp(), 1e6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion1NodeBasedUniMulticastBitUnset() {
|
||||
// Do it a couple of times, to avoid accidentally have correct bit
|
||||
for (int i = 0; i < 100; i++) {
|
||||
UUID uuid = UUIDFactory.timeNodeBasedUUID();
|
||||
assertEquals(0, (uuid.node() >> 40) & 1);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion1NodeBasedUnique() {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
UUID a = UUIDFactory.timeNodeBasedUUID();
|
||||
UUID b = UUIDFactory.timeNodeBasedUUID();
|
||||
assertFalse(a.equals(b));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion1SecureRandomVariant() {
|
||||
assertEquals(2, UUIDFactory.timeRandomBasedUUID().variant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion1SecureRandomVersion() {
|
||||
assertEquals(1, UUIDFactory.timeRandomBasedUUID().version());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion1SecureRandomFromStringRep() {
|
||||
UUID uuid = UUIDFactory.timeRandomBasedUUID();
|
||||
assertEquals(uuid, UUID.fromString(uuid.toString()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion1SecureRandomNode() {
|
||||
UUID uuid = UUIDFactory.timeRandomBasedUUID();
|
||||
assertEquals(UUIDFactory.SECURE_RANDOM_NODE, uuid.node());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion1SecureRandomClockSeq() {
|
||||
UUID uuid = UUIDFactory.timeRandomBasedUUID();
|
||||
assertEquals(UUIDFactory.Clock.getClockSequence(), uuid.clockSequence());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion1SecureRandomTimestamp() {
|
||||
UUID uuid = UUIDFactory.timeRandomBasedUUID();
|
||||
|
||||
// Test time fields (within reasonable limits +/- 100 ms or so?)
|
||||
assertEquals(UUIDFactory.Clock.currentTimeHundredNanos(), uuid.timestamp(), 1e6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion1SecureRandomUniMulticastBit() {
|
||||
// Do it a couple of times, to avoid accidentally have correct bit
|
||||
for (int i = 0; i < 100; i++) {
|
||||
UUID uuid = UUIDFactory.timeRandomBasedUUID();
|
||||
assertEquals(1, (uuid.node() >> 40) & 1);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVersion1SecureRandomUnique() {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
UUID a = UUIDFactory.timeRandomBasedUUID();
|
||||
UUID b = UUIDFactory.timeRandomBasedUUID();
|
||||
assertFalse(a.equals(b));
|
||||
}
|
||||
}
|
||||
|
||||
// Clock tests
|
||||
|
||||
@Test(timeout = 10000l)
|
||||
public void testClock() throws InterruptedException {
|
||||
final long[] times = new long[100000];
|
||||
|
||||
ExecutorService service = Executors.newFixedThreadPool(20);
|
||||
for (int i = 0; i < times.length; i++) {
|
||||
final int index = i;
|
||||
|
||||
service.submit(new Runnable() {
|
||||
public void run() {
|
||||
times[index] = UUIDFactory.Clock.currentTimeHundredNanos();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
service.shutdown();
|
||||
assertTrue("Execution timed out", service.awaitTermination(10, TimeUnit.SECONDS));
|
||||
|
||||
Arrays.sort(times); // This is what really takes time...
|
||||
|
||||
for (int i = 0, timesLength = times.length; i < timesLength; i++) {
|
||||
if (i == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
assertFalse(String.format("times[%d] == times[%d]: 0x%016x", i - 1, i, times[i]), times[i - 1] == times[i]);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(timeout = 10000l)
|
||||
public void testClockSkew() throws InterruptedException {
|
||||
long clockSequence = UUIDFactory.Clock.getClockSequence();
|
||||
|
||||
ExecutorService service = Executors.newFixedThreadPool(10);
|
||||
for (int i = 0; i < 100000; i++) {
|
||||
service.submit(new Runnable() {
|
||||
public void run() {
|
||||
UUIDFactory.Clock.currentTimeHundredNanos();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
service.shutdown();
|
||||
assertTrue("Execution timed out", service.awaitTermination(10, TimeUnit.SECONDS));
|
||||
|
||||
assertEquals(clockSequence, UUIDFactory.Clock.getClockSequence(), 1); // Verify that clock skew doesn't happen "often"
|
||||
}
|
||||
|
||||
// Tests for node address system property
|
||||
|
||||
@Test
|
||||
public void testParseNodeAddressesSingle() {
|
||||
long[] nodes = UUIDFactory.parseMacAddressNodes("00:11:22:33:44:55");
|
||||
|
||||
assertEquals(1, nodes.length);
|
||||
assertEquals(0x001122334455l, nodes[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParseNodeAddressesSingleWhitespace() {
|
||||
long[] nodes = UUIDFactory.parseMacAddressNodes(" 00:11:22:33:44:55\r\n");
|
||||
|
||||
assertEquals(1, nodes.length);
|
||||
assertEquals(0x001122334455l, nodes[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParseNodeAddressesMulti() {
|
||||
long[] nodes = UUIDFactory.parseMacAddressNodes("00:11:22:33:44:55, aa:bb:cc:dd:ee:ff, \n\t 0a-1b-2c-3d-4e-5f,");
|
||||
|
||||
assertEquals(3, nodes.length);
|
||||
assertEquals(0x001122334455l, nodes[0]);
|
||||
assertEquals(0xaabbccddeeffl, nodes[1]);
|
||||
assertEquals(0x0a1b2c3d4e5fl, nodes[2]);
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void testParseNodeAddressesNull() {
|
||||
UUIDFactory.parseMacAddressNodes(null);
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void testParseNodeAddressesEmpty() {
|
||||
UUIDFactory.parseMacAddressNodes("");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void testParseNodeAddressesNonAddress() {
|
||||
UUIDFactory.parseMacAddressNodes("127.0.0.1");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void testParseNodeAddressesBadAddress() {
|
||||
UUIDFactory.parseMacAddressNodes("00a:11:22:33:44:55");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void testParseNodeAddressesBadAddress4() {
|
||||
UUIDFactory.parseMacAddressNodes("00:11:22:33:44:550");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void testParseNodeAddressesBadAddress2() {
|
||||
UUIDFactory.parseMacAddressNodes("0x:11:22:33:44:55");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void testParseNodeAddressesBadAddress3() {
|
||||
UUIDFactory.parseMacAddressNodes("00:11:22:33:44:55:99");
|
||||
}
|
||||
|
||||
// Comparator test
|
||||
|
||||
@Test
|
||||
public void testComparator() {
|
||||
UUID min = new UUID(0, 0);
|
||||
// Long.MAX_VALUE and MIN_VALUE are really adjacent values when comparing unsigned...
|
||||
UUID midLow = new UUID(Long.MAX_VALUE, Long.MAX_VALUE);
|
||||
UUID midHigh = new UUID(Long.MIN_VALUE, Long.MIN_VALUE);
|
||||
UUID max = new UUID(-1l, -1l);
|
||||
|
||||
Comparator<UUID> comparator = UUIDFactory.comparator();
|
||||
|
||||
assertEquals(0, comparator.compare(min, min));
|
||||
assertEquals(-1, comparator.compare(min, midLow));
|
||||
assertEquals(-1, comparator.compare(min, midHigh));
|
||||
assertEquals(-1, comparator.compare(min, max));
|
||||
|
||||
assertEquals(1, comparator.compare(midLow, min));
|
||||
assertEquals(0, comparator.compare(midLow, midLow));
|
||||
assertEquals(-1, comparator.compare(midLow, midHigh));
|
||||
assertEquals(-1, comparator.compare(midLow, max));
|
||||
|
||||
assertEquals(1, comparator.compare(midHigh, min));
|
||||
assertEquals(1, comparator.compare(midHigh, midLow));
|
||||
assertEquals(0, comparator.compare(midHigh, midHigh));
|
||||
assertEquals(-1, comparator.compare(midHigh, max));
|
||||
|
||||
assertEquals(1, comparator.compare(max, min));
|
||||
assertEquals(1, comparator.compare(max, midLow));
|
||||
assertEquals(1, comparator.compare(max, midHigh));
|
||||
assertEquals(0, comparator.compare(max, max));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testComparatorRandom() {
|
||||
final Comparator<UUID> comparator = UUIDFactory.comparator();
|
||||
|
||||
for (int i = 0; i < 10000; i++) {
|
||||
UUID one = UUID.randomUUID();
|
||||
UUID two = UUID.randomUUID();
|
||||
|
||||
if (one.getMostSignificantBits() < 0 && two.getMostSignificantBits() >= 0
|
||||
|| one.getMostSignificantBits() >= 0 && two.getMostSignificantBits() < 0
|
||||
|| one.getLeastSignificantBits() < 0 && two.getLeastSignificantBits() >= 0
|
||||
|| one.getLeastSignificantBits() >= 0 && two.getLeastSignificantBits() < 0) {
|
||||
// These will differ due to the differing signs
|
||||
assertEquals(-one.compareTo(two), comparator.compare(one, two));
|
||||
}
|
||||
else {
|
||||
assertEquals(one.compareTo(two), comparator.compare(one, two));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Various testing
|
||||
|
||||
@Ignore("Development testing only")
|
||||
@Test
|
||||
public void testOracleSYS_GUID() {
|
||||
// TODO: Consider including this as a "fromCompactString" or similar...
|
||||
String str = "AEB87F28E222D08AE043803BD559D08A";
|
||||
BigInteger bigInteger = new BigInteger(str, 16); // ALT: Create byte array of every 2 chars.
|
||||
long msb = bigInteger.shiftRight(64).longValue();
|
||||
long lsb = bigInteger.longValue();
|
||||
UUID uuid = new UUID(msb, lsb);
|
||||
System.err.println("uuid: " + uuid);
|
||||
System.err.println("uuid.variant(): " + uuid.variant());
|
||||
System.err.println("uuid.version(): " + uuid.version());
|
||||
}
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
/*
|
||||
* Copyright (c) 2012, 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.twlevemonkeys.image;
|
||||
|
||||
import com.twelvemonkeys.image.MappedFileBuffer;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.awt.image.DataBuffer;
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
/**
|
||||
* MappedFileBufferTest
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @author last modified by $Author: haraldk$
|
||||
* @version $Id: MappedFileBufferTest.java,v 1.0 01.06.12 14:23 haraldk Exp$
|
||||
*/
|
||||
public class MappedFileBufferTest {
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testCreateInvalidType() throws IOException {
|
||||
MappedFileBuffer.create(-1, 1, 1);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testCreateInvalidSize() throws IOException {
|
||||
MappedFileBuffer.create(DataBuffer.TYPE_USHORT, -1, 1);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testCreateInvalidBands() throws IOException {
|
||||
MappedFileBuffer.create(DataBuffer.TYPE_BYTE, 1, -1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateByte() throws IOException {
|
||||
DataBuffer buffer = MappedFileBuffer.create(DataBuffer.TYPE_BYTE, 256, 3);
|
||||
assertNotNull(buffer);
|
||||
|
||||
assertEquals(DataBuffer.TYPE_BYTE, buffer.getDataType());
|
||||
assertEquals(256, buffer.getSize());
|
||||
assertEquals(3, buffer.getNumBanks());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetGetElemByte() throws IOException {
|
||||
final int size = 256;
|
||||
DataBuffer buffer = MappedFileBuffer.create(DataBuffer.TYPE_BYTE, size, 3);
|
||||
assertNotNull(buffer);
|
||||
|
||||
for (int b = 0; b < 3; b++) {
|
||||
for (int i = 0; i < size; i++) {
|
||||
buffer.setElem(b, i, i);
|
||||
|
||||
assertEquals(i, buffer.getElem(b, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateUShort() throws IOException {
|
||||
DataBuffer buffer = MappedFileBuffer.create(DataBuffer.TYPE_USHORT, 256, 3);
|
||||
assertNotNull(buffer);
|
||||
|
||||
assertEquals(DataBuffer.TYPE_USHORT, buffer.getDataType());
|
||||
assertEquals(256, buffer.getSize());
|
||||
assertEquals(3, buffer.getNumBanks());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetGetElemUShort() throws IOException {
|
||||
final int size = (Short.MAX_VALUE + 1) * 2;
|
||||
DataBuffer buffer = MappedFileBuffer.create(DataBuffer.TYPE_USHORT, size, 3);
|
||||
assertNotNull(buffer);
|
||||
|
||||
for (int b = 0; b < 3; b++) {
|
||||
for (int i = 0; i < size; i++) {
|
||||
buffer.setElem(b, i, i);
|
||||
|
||||
assertEquals(i, buffer.getElem(b, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateInt() throws IOException {
|
||||
DataBuffer buffer = MappedFileBuffer.create(DataBuffer.TYPE_INT, 256, 3);
|
||||
assertNotNull(buffer);
|
||||
|
||||
assertEquals(DataBuffer.TYPE_INT, buffer.getDataType());
|
||||
assertEquals(256, buffer.getSize());
|
||||
assertEquals(3, buffer.getNumBanks());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetGetElemInt() throws IOException {
|
||||
final int size = (Short.MAX_VALUE + 1) * 2;
|
||||
DataBuffer buffer = MappedFileBuffer.create(DataBuffer.TYPE_INT, size, 3);
|
||||
assertNotNull(buffer);
|
||||
|
||||
for (int b = 0; b < 3; b++) {
|
||||
for (int i = 0; i < size; i++) {
|
||||
buffer.setElem(b, i, i * i);
|
||||
|
||||
assertEquals(i * i, buffer.getElem(b, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user