From 1cd594d11300e2eff0e5addfe6e118b1605afa3d Mon Sep 17 00:00:00 2001
From: Harald Kuhr
Date: Mon, 24 Jan 2022 09:01:53 +0100
Subject: [PATCH] RIP: Sandbox
---
pom.xml | 1 -
sandbox/pom.xml | 156 --
sandbox/sandbox-common/pom.xml | 58 -
.../twelvemonkeys/image/AbstractFilter.java | 143 --
.../twelvemonkeys/image/ConvolveTester.java | 128 --
.../com/twelvemonkeys/image/EasyImage.java | 78 -
.../image/ExtendedImageConsumer.java | 61 -
.../image/GenericWritableRaster.java | 61 -
.../twelvemonkeys/image/InstaCRTFilter.java | 182 --
.../twelvemonkeys/image/InstaLomoFilter.java | 201 --
.../twelvemonkeys/image/InstaSepiaFilter.java | 150 --
.../image/MappedBufferImage.java | 1019 ----------
.../twelvemonkeys/image/MappedFileBuffer.java | 174 --
.../image/MappedImageFactory.java | 325 ---
.../com/twelvemonkeys/image/NoiseFilter.java | 228 ---
.../twelvemonkeys/image/SubsampleTester.java | 163 --
.../java/com/twelvemonkeys/image/inv_cmap.c | 524 -----
.../com/twelvemonkeys/io/FileLockingTest.java | 64 -
.../com/twelvemonkeys/io/FileMonitor.java | 57 -
.../twelvemonkeys/io/StringInputStream.java | 87 -
.../twelvemonkeys/io/enc/DeflateEncoder.java | 90 -
.../twelvemonkeys/io/enc/InflateDecoder.java | 110 --
.../java/com/twelvemonkeys/lang/DuckType.java | 468 -----
.../com/twelvemonkeys/lang/ExceptionUtil.java | 89 -
.../java/com/twelvemonkeys/lang/MathUtil.java | 138 --
.../lang/MostUnfortunateException.java | 55 -
.../com/twelvemonkeys/lang/NativeLoader.java | 401 ----
.../twelvemonkeys/lang/NativeResourceSPI.java | 99 -
.../net/AuthenticatorFilter.java | 45 -
.../java/com/twelvemonkeys/net/BASE64.java | 143 --
.../twelvemonkeys/net/HttpURLConnection.java | 1101 -----------
.../java/com/twelvemonkeys/net/NetUtil.java | 1258 ------------
.../net/PasswordAuthenticator.java | 45 -
.../net/SimpleAuthenticator.java | 270 ---
.../twelvemonkeys/sql/DatabaseConnection.java | 247 ---
.../twelvemonkeys/sql/DatabaseProduct.java | 126 --
.../twelvemonkeys/sql/DatabaseReadable.java | 70 -
.../com/twelvemonkeys/sql/JDBCHelper.java | 173 --
.../main/java/com/twelvemonkeys/sql/Log.java | 673 -------
.../com/twelvemonkeys/sql/ObjectManager.java | 276 ---
.../com/twelvemonkeys/sql/ObjectMapper.java | 663 -------
.../com/twelvemonkeys/sql/ObjectReader.java | 879 ---------
.../java/com/twelvemonkeys/sql/SQLUtil.java | 396 ----
.../java/com/twelvemonkeys/sql/package.html | 12 -
.../twelvemonkeys/util/AbstractResource.java | 92 -
.../com/twelvemonkeys/util/BooleanKey.java | 52 -
.../com/twelvemonkeys/util/DebugUtil.java | 1757 -----------------
.../com/twelvemonkeys/util/FileResource.java | 78 -
.../java/com/twelvemonkeys/util/FloatKey.java | 52 -
.../com/twelvemonkeys/util/IntegerKey.java | 51 -
.../twelvemonkeys/util/MappedBeanFactory.java | 456 -----
.../java/com/twelvemonkeys/util/PaintKey.java | 53 -
.../com/twelvemonkeys/util/PersistentMap.java | 334 ----
.../twelvemonkeys/util/Rectangle2DKey.java | 53 -
.../java/com/twelvemonkeys/util/Resource.java | 80 -
.../util/ResourceChangeListener.java | 51 -
.../twelvemonkeys/util/ResourceMonitor.java | 207 --
.../com/twelvemonkeys/util/StringKey.java | 52 -
.../java/com/twelvemonkeys/util/TypedMap.java | 320 ---
.../com/twelvemonkeys/util/URLResource.java | 89 -
.../com/twelvemonkeys/util/UUIDFactory.java | 410 ----
.../com/twelvemonkeys/util/XMLProperties.java | 1287 ------------
.../util/regex/REWildcardStringParser.java | 398 ----
.../java/com/twelvemonkeys/xml/XMLReader.java | 55 -
.../image/MappedImageFactoryTest.java | 26 -
.../io/StringInputStreamTest.java | 126 --
.../io/enc/DeflateEncoderTestCase.java | 18 -
.../io/enc/InflateDecoderTestCase.java | 18 -
.../twelvemonkeys/lang/DuckTypeTestCase.java | 246 ---
.../twelvemonkeys/lang/ExceptionUtilTest.java | 99 -
.../util/MappedBeanFactoryTestCase.java | 578 ------
.../twelvemonkeys/util/UUIDFactoryTest.java | 419 ----
.../image/MappedFileBufferTest.java | 137 --
sandbox/sandbox-imageio/pom.xml | 86 -
.../Base64DataURLImageInputStreamSpi.java | 65 -
.../Base64DataURLImageInputStreamTest.java | 44 -
sandbox/sandbox-servlet/pom.xml | 84 -
.../servlet/image/TextRenderer.java | 336 ----
.../servlet/jsp/droplet/Droplet.java | 76 -
.../servlet/jsp/droplet/JspFragment.java | 42 -
.../servlet/jsp/droplet/Oparam.java | 26 -
.../servlet/jsp/droplet/Param.java | 41 -
.../servlet/jsp/droplet/package-info.java | 9 -
.../jsp/droplet/taglib/IncludeTag.java | 214 --
.../jsp/droplet/taglib/NestingHandler.java | 183 --
.../jsp/droplet/taglib/NestingValidator.java | 102 -
.../servlet/jsp/droplet/taglib/OparamTag.java | 220 ---
.../servlet/jsp/droplet/taglib/ParamTag.java | 129 --
.../jsp/droplet/taglib/ValueOfTEI.java | 47 -
.../jsp/droplet/taglib/ValueOfTag.java | 148 --
.../jsp/droplet/taglib/package-info.java | 38 -
.../servlet/jsp/package-info.java | 4 -
.../servlet/jsp/taglib/BodyReaderTag.java | 39 -
.../servlet/jsp/taglib/CSVToTableTag.java | 235 ---
.../servlet/jsp/taglib/ExBodyTagSupport.java | 290 ---
.../servlet/jsp/taglib/ExTag.java | 163 --
.../servlet/jsp/taglib/ExTagSupport.java | 293 ---
.../servlet/jsp/taglib/LastModifiedTEI.java | 20 -
.../servlet/jsp/taglib/LastModifiedTag.java | 49 -
.../servlet/jsp/taglib/TrimWhiteSpaceTag.java | 87 -
.../servlet/jsp/taglib/XMLTransformTag.java | 158 --
.../jsp/taglib/logic/ConditionalTagBase.java | 138 --
.../servlet/jsp/taglib/logic/EqualTag.java | 168 --
.../jsp/taglib/logic/IteratorProviderTEI.java | 40 -
.../jsp/taglib/logic/IteratorProviderTag.java | 86 -
.../servlet/jsp/taglib/logic/NotEqualTag.java | 168 --
.../servlet/jsp/taglib/package-info.java | 4 -
sandbox/sandbox-swing/pom.xml | 153 --
.../swing/filechooser/FileSystemViews.java | 207 --
109 files changed, 23473 deletions(-)
delete mode 100644 sandbox/pom.xml
delete mode 100644 sandbox/sandbox-common/pom.xml
delete mode 100644 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/AbstractFilter.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/ConvolveTester.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/EasyImage.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/ExtendedImageConsumer.java
delete mode 100644 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/GenericWritableRaster.java
delete mode 100644 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/InstaCRTFilter.java
delete mode 100644 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/InstaLomoFilter.java
delete mode 100644 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/InstaSepiaFilter.java
delete mode 100644 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/MappedBufferImage.java
delete mode 100644 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/MappedFileBuffer.java
delete mode 100644 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/MappedImageFactory.java
delete mode 100644 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/NoiseFilter.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/SubsampleTester.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/inv_cmap.c
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/FileLockingTest.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/FileMonitor.java
delete mode 100644 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/StringInputStream.java
delete mode 100644 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/enc/DeflateEncoder.java
delete mode 100644 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/enc/InflateDecoder.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/DuckType.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/ExceptionUtil.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/MathUtil.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/MostUnfortunateException.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/NativeLoader.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/NativeResourceSPI.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/AuthenticatorFilter.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/BASE64.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/NetUtil.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/PasswordAuthenticator.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/SimpleAuthenticator.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/DatabaseConnection.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/DatabaseProduct.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/DatabaseReadable.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/JDBCHelper.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/Log.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectManager.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectMapper.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/SQLUtil.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/package.html
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/AbstractResource.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/BooleanKey.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/FileResource.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/FloatKey.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/IntegerKey.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/MappedBeanFactory.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/PaintKey.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/PersistentMap.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/Rectangle2DKey.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/Resource.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/ResourceChangeListener.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/ResourceMonitor.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/StringKey.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/TypedMap.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/URLResource.java
delete mode 100644 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/UUIDFactory.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/XMLProperties.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/regex/REWildcardStringParser.java
delete mode 100755 sandbox/sandbox-common/src/main/java/com/twelvemonkeys/xml/XMLReader.java
delete mode 100644 sandbox/sandbox-common/src/test/java/com/twelvemonkeys/image/MappedImageFactoryTest.java
delete mode 100644 sandbox/sandbox-common/src/test/java/com/twelvemonkeys/io/StringInputStreamTest.java
delete mode 100644 sandbox/sandbox-common/src/test/java/com/twelvemonkeys/io/enc/DeflateEncoderTestCase.java
delete mode 100644 sandbox/sandbox-common/src/test/java/com/twelvemonkeys/io/enc/InflateDecoderTestCase.java
delete mode 100755 sandbox/sandbox-common/src/test/java/com/twelvemonkeys/lang/DuckTypeTestCase.java
delete mode 100644 sandbox/sandbox-common/src/test/java/com/twelvemonkeys/lang/ExceptionUtilTest.java
delete mode 100755 sandbox/sandbox-common/src/test/java/com/twelvemonkeys/util/MappedBeanFactoryTestCase.java
delete mode 100644 sandbox/sandbox-common/src/test/java/com/twelvemonkeys/util/UUIDFactoryTest.java
delete mode 100644 sandbox/sandbox-common/src/test/java/com/twlevemonkeys/image/MappedFileBufferTest.java
delete mode 100644 sandbox/sandbox-imageio/pom.xml
delete mode 100644 sandbox/sandbox-imageio/src/main/java/com/twelvemonkeys/imageio/stream/Base64DataURLImageInputStreamSpi.java
delete mode 100644 sandbox/sandbox-imageio/src/test/java/com/twelvemonkeys/imageio/stream/Base64DataURLImageInputStreamTest.java
delete mode 100644 sandbox/sandbox-servlet/pom.xml
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/image/TextRenderer.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/droplet/Droplet.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/droplet/JspFragment.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/droplet/Oparam.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/droplet/Param.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/droplet/package-info.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/droplet/taglib/IncludeTag.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/droplet/taglib/NestingHandler.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/droplet/taglib/NestingValidator.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/droplet/taglib/OparamTag.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/droplet/taglib/ParamTag.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/droplet/taglib/ValueOfTEI.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/droplet/taglib/ValueOfTag.java
delete mode 100644 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/droplet/taglib/package-info.java
delete mode 100644 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/package-info.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/BodyReaderTag.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/CSVToTableTag.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/ExBodyTagSupport.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/ExTag.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/ExTagSupport.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/LastModifiedTEI.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/LastModifiedTag.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/TrimWhiteSpaceTag.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/XMLTransformTag.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/logic/ConditionalTagBase.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/logic/EqualTag.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/logic/IteratorProviderTEI.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/logic/IteratorProviderTag.java
delete mode 100755 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/logic/NotEqualTag.java
delete mode 100644 sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/package-info.java
delete mode 100644 sandbox/sandbox-swing/pom.xml
delete mode 100644 sandbox/sandbox-swing/src/main/java/com/twelvemonkeys/swing/filechooser/FileSystemViews.java
diff --git a/pom.xml b/pom.xml
index 67011ce9..4499cbb9 100755
--- a/pom.xml
+++ b/pom.xml
@@ -24,7 +24,6 @@
servletimageio
-
contribbom
diff --git a/sandbox/pom.xml b/sandbox/pom.xml
deleted file mode 100644
index 5c73b336..00000000
--- a/sandbox/pom.xml
+++ /dev/null
@@ -1,156 +0,0 @@
-
-
- 4.0.0
- com.twelvemonkeys.sandbox
- sandbox
- 3.1-SNAPSHOT
- TwelveMonkeys :: Sandbox
- pom
-
-
- The TwelveMonkeys Sandbox. Experimental stuff, in progress, not for production use.
-
-
-
- com.twelvemonkeys
- twelvemonkeys
- 3.1-SNAPSHOT
-
-
-
- sandbox-common
- sandbox-imageio
- sandbox-servlet
- sandbox-swing
-
-
-
-
- junit
- junit
- test
-
-
-
-
-
-
-
- com.twelvemonkeys.common
- common-lang
- ${project.version}
- compile
-
-
- com.twelvemonkeys.common
- common-io
- ${project.version}
- compile
-
-
- com.twelvemonkeys.common
- common-image
- ${project.version}
- compile
-
-
- com.twelvemonkeys.servlet
- servlet
- ${project.version}
- compile
-
-
- com.twelvemonkeys.swing
- swing-core
- ${project.version}
- compile
-
-
- com.twelvemonkeys.swing
- swing-application
- ${project.version}
- compile
-
-
- com.twelvemonkeys.imageio
- imageio-core
- ${project.version}
- provided
-
-
- com.twelvemonkeys.sandbox
- sandbox-common
- ${project.version}
- compile
-
-
-
- com.twelvemonkeys.common
- common-io
- ${project.version}
- test
- test-jar
-
-
- com.twelvemonkeys.common
- common-lang
- ${project.version}
- test
- test-jar
-
-
-
- junit
- junit
- 4.13.1
- test
-
-
-
-
-
-
-
- maven-source-plugin
-
-
-
- maven-resources-plugin
-
- UTF-8
-
-
-
-
- org.apache.maven.plugins
- maven-jar-plugin
- 2.4
-
-
-
- ${project.name}
- TwelveMonkeys
- ${project.version}
- http://github.com/haraldk/TwelveMonkeys
-
-
-
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- true
-
- true
-
-
-
-
-
-
diff --git a/sandbox/sandbox-common/pom.xml b/sandbox/sandbox-common/pom.xml
deleted file mode 100644
index 31f6b315..00000000
--- a/sandbox/sandbox-common/pom.xml
+++ /dev/null
@@ -1,58 +0,0 @@
-
-
- 4.0.0
-
- com.twelvemonkeys.sandbox
- sandbox
- 3.1-SNAPSHOT
-
- sandbox-common
- jar
- TwelveMonkeys :: Sandbox :: Common
-
- The TwelveMonkeys Common Sandbox. Experimental stuff.
-
-
-
-
- com.twelvemonkeys.common
- common-lang
- compile
-
-
-
- com.twelvemonkeys.common
- common-io
- compile
-
-
-
- com.twelvemonkeys.common
- common-image
- compile
-
-
-
- com.twelvemonkeys.imageio
- imageio-core
- compile
-
-
-
- com.twelvemonkeys.common
- common-io
- test
- test-jar
-
-
-
- com.twelvemonkeys.common
- common-lang
- test
- test-jar
-
-
-
-
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/AbstractFilter.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/AbstractFilter.java
deleted file mode 100644
index 064fae79..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/AbstractFilter.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * 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.image;
-
-import javax.imageio.ImageIO;
-import javax.swing.*;
-import java.awt.*;
-import java.awt.event.ActionEvent;
-import java.awt.event.KeyEvent;
-import java.awt.event.WindowAdapter;
-import java.awt.event.WindowEvent;
-import java.awt.geom.Point2D;
-import java.awt.geom.Rectangle2D;
-import java.awt.image.BufferedImage;
-import java.awt.image.BufferedImageOp;
-import java.awt.image.ColorModel;
-import java.io.File;
-import java.io.IOException;
-
-/**
- * AbstractFilter
- *
- * @author Harald Kuhr
- * @author last modified by $Author: haraldk$
- * @version $Id: AbstractFilter.java,v 1.0 18.06.12 16:55 haraldk Exp$
- */
-public abstract class AbstractFilter implements BufferedImageOp {
- public abstract BufferedImage filter(BufferedImage src, BufferedImage dest);
-
- public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM) {
- throw new UnsupportedOperationException("Method createCompatibleDestImage not implemented"); // TODO: Implement
- }
-
- public Rectangle2D getBounds2D(BufferedImage src) {
- return new Rectangle2D.Double(0, 0, src.getWidth(), src.getHeight());
- }
-
- public Point2D getPoint2D(Point2D srcPt, Point2D dstPt) {
- if (dstPt == null) {
- dstPt = new Point2D.Double();
- }
-
- dstPt.setLocation(srcPt);
-
- return dstPt;
- }
-
- public RenderingHints getRenderingHints() {
- return null;
- }
-
- protected static void exercise(final String[] args, final BufferedImageOp filter, final Color background) throws IOException {
- boolean original = false;
-
- for (String arg : args) {
- if (arg.startsWith("-")) {
- if (arg.equals("-o") || arg.equals("--original")) {
- original = true;
- }
-
- continue;
- }
-
- final File file = new File(arg);
- BufferedImage image = ImageIO.read(file);
-
- if (image.getWidth() > 640) {
- image = new ResampleOp(640, Math.round(image.getHeight() * (640f / image.getWidth())), null).filter(image, null);
- }
-
- if (!original) {
- filter.filter(image, image);
- }
-
- final Color bg = original ? Color.BLACK : background;
- final BufferedImage img = image;
-
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- JFrame frame = new JFrame(filter.getClass().getSimpleName().replace("Filter", "") + "Test: " + file.getName());
- frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
- frame.addWindowListener(new WindowAdapter() {
- @Override
- public void windowClosed(final WindowEvent e) {
- Window[] windows = Window.getWindows();
- if (windows == null || windows.length == 0) {
- System.exit(0);
- }
- }
- });
- frame.getRootPane().getActionMap().put("window-close", new AbstractAction() {
- public void actionPerformed(ActionEvent e) {
- Window window = SwingUtilities.getWindowAncestor((Component) e.getSource());
- window.setVisible(false);
- window.dispose();
- }
- });
- frame.getRootPane().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_W, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "window-close");
-
- JLabel label = new JLabel(new BufferedImageIcon(img));
- if (bg != null) {
- label.setOpaque(true);
- label.setBackground(bg);
- }
- label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
- JScrollPane scrollPane = new JScrollPane(label);
- scrollPane.setBorder(BorderFactory.createEmptyBorder());
- frame.add(scrollPane);
-
- frame.pack();
- frame.setLocationByPlatform(true);
- frame.setVisible(true);
- }
- });
- }
- }
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/ConvolveTester.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/ConvolveTester.java
deleted file mode 100755
index 437c6449..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/ConvolveTester.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * 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 Harald Kuhr
- * @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);
-
- }
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/EasyImage.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/EasyImage.java
deleted file mode 100755
index 71427244..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/EasyImage.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * 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
- *
- *
- * @author Harald Kuhr
- * @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);
- }
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/ExtendedImageConsumer.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/ExtendedImageConsumer.java
deleted file mode 100755
index 949d6932..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/ExtendedImageConsumer.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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
- *
- *
- * @author Harald Kuhr
- * @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);
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/GenericWritableRaster.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/GenericWritableRaster.java
deleted file mode 100644
index e05fc6b2..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/GenericWritableRaster.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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 Harald Kuhr
- * @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
- );
- }
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/InstaCRTFilter.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/InstaCRTFilter.java
deleted file mode 100644
index 1929d7fe..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/InstaCRTFilter.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * 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.image;
-
-import java.awt.*;
-import java.awt.color.ColorSpace;
-import java.awt.image.BufferedImage;
-import java.awt.image.ColorConvertOp;
-import java.awt.image.RescaleOp;
-import java.io.IOException;
-import java.util.Random;
-
-/**
- * InstaCRTFilter
- *
- * @author Harald Kuhr
- * @author last modified by $Author: haraldk$
- * @version $Id: InstaCRTFilter.java,v 1.0 15.06.12 13:24 haraldk Exp$
- */
-public class InstaCRTFilter extends AbstractFilter {
-
- // NOTE: This is a PoC, and not good code...
- public BufferedImage filter(BufferedImage src, BufferedImage dest) {
- if (dest == null) {
- dest = createCompatibleDestImage(src, null);
- }
-
- // Make grayscale
- BufferedImage image = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), getRenderingHints()).filter(src, null);
-
- // Make image faded/too bright
- image = new RescaleOp(1.2f, 120f, getRenderingHints()).filter(image, image);
-
- // Blur
- image = ImageUtil.blur(image, 2.5f);
-
- Graphics2D g = dest.createGraphics();
- try {
- g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
- g.drawImage(image, 0, 0, null);
-
- // Rotate it slightly for a more analogue feeling
- double angle = .0055;
- g.rotate(angle);
-
- // Apply fake green-ish h-sync line at random position
- Random random = new Random();
- int lineStart = random.nextInt(image.getHeight() - 80);
- int lineHeight = random.nextInt(10) + 20;
-
- g.setComposite(AlphaComposite.SrcOver.derive(.3f));
- g.setPaint(new LinearGradientPaint(
- 0, lineStart, 0, lineStart + lineHeight,
- new float[] {0, .3f, .9f, 1},
- new Color[] {new Color(0, true), new Color(0x90AF66), new Color(0x99606F33, true), new Color(0, true)}
- ));
- g.fillRect(0, lineStart, image.getWidth(), lineHeight);
-
- // Apply fake large dot-pitch (black lines w/transparency)
- g.setComposite(AlphaComposite.SrcOver.derive(.55f));
- g.setColor(Color.BLACK);
-
- for (int y = 0; y < image.getHeight(); y += 3) {
- g.setStroke(new BasicStroke(random.nextFloat() / 3 + .8f));
- g.drawLine(0, y, image.getWidth(), y);
- }
-
- // Vignette/border
- g.setComposite(AlphaComposite.SrcOver.derive(.75f));
- int focus = Math.min(image.getWidth() / 8, image.getHeight() / 8);
- g.setPaint(new RadialGradientPaint(
- new Point(image.getWidth() / 2, image.getHeight() / 2),
- Math.max(image.getWidth(), image.getHeight()) / 1.6f,
- new Point(focus, focus),
- new float[] {0, .3f, .9f, 1f},
- new Color[] {new Color(0x99FFFFFF, true), new Color(0x00FFFFFF, true), new Color(0x0, true), Color.BLACK},
- MultipleGradientPaint.CycleMethod.NO_CYCLE
- ));
- g.fillRect(-2, -2, image.getWidth() + 4, image.getHeight() + 4);
-
- g.rotate(-angle);
-
- g.setComposite(AlphaComposite.SrcOver.derive(.35f));
- g.setPaint(new RadialGradientPaint(
- new Point(image.getWidth() / 2, image.getHeight() / 2),
- Math.max(image.getWidth(), image.getHeight()) / 1.65f,
- new Point(image.getWidth() / 2, image.getHeight() / 2),
- new float[] {0, .85f, 1f},
- new Color[] {new Color(0x0, true), new Color(0x0, true), Color.BLACK},
- MultipleGradientPaint.CycleMethod.NO_CYCLE
- ));
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
-
- // Highlight
- g.setComposite(AlphaComposite.SrcOver.derive(.55f));
- g.setPaint(new RadialGradientPaint(
- new Point(image.getWidth(), image.getHeight()),
- Math.max(image.getWidth(), image.getHeight()) * 1.1f,
- new Point(image.getWidth() / 2, image.getHeight() / 2),
- new float[] {0, .75f, 1f},
- new Color[] {new Color(0x00FFFFFF, true), new Color(0x00FFFFFF, true), Color.WHITE},
- MultipleGradientPaint.CycleMethod.NO_CYCLE
- ));
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- }
- finally {
- g.dispose();
- }
-
- // Round corners
- BufferedImage foo = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
- Graphics2D graphics = foo.createGraphics();
- try {
- graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- graphics.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
- graphics.setColor(Color.WHITE);
- double angle = -0.04;
- g.rotate(angle);
- graphics.fillRoundRect(1, 1, image.getWidth() - 2, image.getHeight() - 2, 20, 20);
- }
- finally {
- graphics.dispose();
- }
-
- foo = ImageUtil.blur(foo, 4.5f);
-
- // Compose image into rounded corners
- graphics = foo.createGraphics();
- try {
- graphics.setComposite(AlphaComposite.SrcIn);
- graphics.drawImage(dest, 0, 0, null);
- }
- finally {
- graphics.dispose();
- }
-
- // Draw it all back to dest
- g = dest.createGraphics();
- try {
- g.setComposite(AlphaComposite.SrcOver);
- g.setColor(Color.BLACK);
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- g.drawImage(foo, 0, 0, null);
- }
- finally {
- g.dispose();
- }
-
- return dest;
- }
-
- public static void main(String[] args) throws IOException {
- exercise(args, new InstaCRTFilter(), Color.BLACK);
- }
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/InstaLomoFilter.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/InstaLomoFilter.java
deleted file mode 100644
index 6d277717..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/InstaLomoFilter.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * 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.image;
-
-import java.awt.*;
-import java.awt.image.BufferedImage;
-import java.awt.image.RescaleOp;
-import java.io.IOException;
-import java.util.Random;
-
-/**
- * InstaLomoFilter
- *
- * @author Harald Kuhr
- * @author last modified by $Author: haraldk$
- * @version $Id: InstaLomoFilter.java,v 1.0 15.06.12 13:24 haraldk Exp$
- */
-public class InstaLomoFilter extends AbstractFilter {
- final private Random random = new Random();
-
- // NOTE: This is a PoC, and not good code...
- public BufferedImage filter(BufferedImage src, BufferedImage dest) {
- if (dest == null) {
- dest = createCompatibleDestImage(src, null);
- }
-
- // Make image faded/washed out/red-ish
- // DARK WARM
- float[] scales = new float[] { 2.2f, 2.0f, 1.55f};
- float[] offsets = new float[] {-20.0f, -90.0f, -110.0f};
-
- // BRIGHT NATURAL
-// float[] scales = new float[] { 1.1f, .9f, .7f};
-// float[] offsets = new float[] {20, 30, 80};
-
- // Faded, old-style
-// float[] scales = new float[] { 1.1f, .7f, .3f};
-// float[] offsets = new float[] {20, 30, 80};
-
-// float[] scales = new float[] { 1.2f, .4f, .4f};
-// float[] offsets = new float[] {0, 120, 120};
-
- // BRIGHT WARM
-// float[] scales = new float[] {1.1f, .8f, 1.6f};
-// float[] offsets = new float[] {60, 70, -80};
- BufferedImage image = new RescaleOp(scales, offsets, getRenderingHints()).filter(src, null);
-
- // Blur
- image = ImageUtil.blur(image, 2.5f);
-
- Graphics2D g = dest.createGraphics();
- try {
- g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
- g.drawImage(image, 0, 0, null);
-
- // Rotate it slightly for a more analogue feeling
- double angle = .0055;
- g.rotate(angle);
-
- // Scratches
- g.setComposite(AlphaComposite.SrcOver.derive(.025f));
- for (int i = 0; i < 100; i++) {
- g.setColor(random.nextBoolean() ? Color.WHITE : Color.BLACK);
- g.setStroke(new BasicStroke(random.nextFloat() * 2f));
- int x = random.nextInt(image.getWidth());
-
- int off = random.nextInt(100);
- for (int j = random.nextInt(3); j > 0; j--) {
- g.drawLine(x + j, 0, x + off - 50 + j, image.getHeight());
- }
- }
-
- // Vignette/border
- g.setComposite(AlphaComposite.SrcOver.derive(.75f));
- int focus = Math.min(image.getWidth() / 8, image.getHeight() / 8);
- g.setPaint(new RadialGradientPaint(
- new Point(image.getWidth() / 2, image.getHeight() / 2),
- Math.max(image.getWidth(), image.getHeight()) / 1.6f,
- new Point(focus, focus),
- new float[] {0, .3f, .9f, 1f},
- new Color[] {new Color(0x99FFFFFF, true), new Color(0x00FFFFFF, true), new Color(0x0, true), Color.BLACK},
- MultipleGradientPaint.CycleMethod.NO_CYCLE
- ));
- g.fillRect(-2, -2, image.getWidth() + 4, image.getHeight() + 4);
-
- g.rotate(-angle);
-
- g.setComposite(AlphaComposite.SrcOver.derive(.35f));
- g.setPaint(new RadialGradientPaint(
- new Point(image.getWidth() / 2, image.getHeight() / 2),
- Math.max(image.getWidth(), image.getHeight()) / 1.65f,
- new Point(image.getWidth() / 2, image.getHeight() / 2),
- new float[] {0, .85f, 1f},
- new Color[] {new Color(0x0, true), new Color(0x0, true), Color.BLACK},
- MultipleGradientPaint.CycleMethod.NO_CYCLE
- ));
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
-
- // Highlight
- g.setComposite(AlphaComposite.SrcOver.derive(.35f));
- g.setPaint(new RadialGradientPaint(
- new Point(image.getWidth(), image.getHeight()),
- Math.max(image.getWidth(), image.getHeight()) * 1.1f,
- new Point(image.getWidth() / 2, image.getHeight() / 2),
- new float[] {0, .75f, 1f},
- new Color[] {new Color(0x00FFFFFF, true), new Color(0x00FFFFFF, true), Color.PINK},
- MultipleGradientPaint.CycleMethod.NO_CYCLE
- ));
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- }
- finally {
- g.dispose();
- }
-
- // Noise
- NoiseFilter noise = new NoiseFilter();
- noise.setAmount(10);
- noise.setDensity(2);
- dest = noise.filter(dest, dest);
-
- // Round corners
- BufferedImage foo = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
- Graphics2D graphics = foo.createGraphics();
- try {
- graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- graphics.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
- graphics.setColor(Color.WHITE);
- double angle = (random.nextDouble() * .01) - .005;
- graphics.rotate(angle);
- graphics.fillRoundRect(4, 4, image.getWidth() - 8, image.getHeight() - 8, 20, 20);
- }
- finally {
- graphics.dispose();
- }
-
- noise.setAmount(20);
- noise.setDensity(1);
- noise.setMonochrome(true);
- foo = noise.filter(foo, foo);
-
- foo = ImageUtil.blur(foo, 4.5f);
-
- // Compose image into rounded corners
- graphics = foo.createGraphics();
- try {
- graphics.setComposite(AlphaComposite.SrcIn);
- graphics.drawImage(dest, 0, 0, null);
- }
- finally {
- graphics.dispose();
- }
-
- // Draw it all back to dest
- g = dest.createGraphics();
- try {
- if (dest.getTransparency() != Transparency.OPAQUE) {
- g.setComposite(AlphaComposite.Clear);
- }
- g.setColor(Color.WHITE);
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- g.setComposite(AlphaComposite.SrcOver);
- g.drawImage(foo, 0, 0, null);
- }
- finally {
- g.dispose();
- }
-
- return dest;
- }
-
- public static void main(String[] args) throws IOException {
- exercise(args, new InstaLomoFilter(), Color.WHITE);
- }
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/InstaSepiaFilter.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/InstaSepiaFilter.java
deleted file mode 100644
index b82c6b9c..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/InstaSepiaFilter.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * 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.image;
-
-import java.awt.*;
-import java.awt.color.ColorSpace;
-import java.awt.image.*;
-import java.io.IOException;
-import java.util.Random;
-
-/**
- * InstaLomoFilter
- *
- * @author Harald Kuhr
- * @author last modified by $Author: haraldk$
- * @version $Id: InstaLomoFilter.java,v 1.0 15.06.12 13:24 haraldk Exp$
- */
-public class InstaSepiaFilter extends AbstractFilter {
- final private Random random = new Random();
-
- // NOTE: This is a PoC, and not good code...
- @Override
- public BufferedImage filter(BufferedImage src, BufferedImage dest) {
- if (dest == null) {
- dest = createCompatibleDestImage(src, null);
- }
-
- BufferedImage image = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), getRenderingHints()).filter(src, dest);
-
- Graphics2D g2d = dest.createGraphics();
- try {
- g2d.drawImage(image, 0, 0, null);
- }
- finally {
- g2d.dispose();
- }
-
- // Blur
- image = ImageUtil.blur(image, 2.5f);
-
- Graphics2D g = dest.createGraphics();
- try {
- g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
- g.drawImage(image, 0, 0, null);
-
- // Rotate it slightly for a more analogue feeling
- double angle = -.0055;
- g.rotate(angle);
-
- // Vignette/border
- g.setComposite(AlphaComposite.SrcOver.derive(.35f));
- g.setPaint(new RadialGradientPaint(
- new Point(image.getWidth() / 2, image.getHeight() / 2),
- Math.max(image.getWidth(), image.getHeight()) / 1.65f,
- new Point(image.getWidth() / 2, image.getHeight() / 2),
- new float[] {0, .85f, 1f},
- new Color[] {new Color(0x0, true), new Color(0x0, true), Color.BLACK},
- MultipleGradientPaint.CycleMethod.NO_CYCLE
- ));
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
-
- }
- finally {
- g.dispose();
- }
-
- // Round corners
- BufferedImage foo = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
- Graphics2D graphics = foo.createGraphics();
- try {
- graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- graphics.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
- graphics.setColor(Color.WHITE);
- double angle = (random.nextDouble() * .01) - .005;
- graphics.rotate(angle);
- graphics.fillRoundRect(4, 4, image.getWidth() - 8, image.getHeight() - 8, 20, 20);
- }
- finally {
- graphics.dispose();
- }
-
- // Noise
- NoiseFilter noise = new NoiseFilter();
- noise.setAmount(20);
- noise.setDensity(1);
- noise.setMonochrome(true);
- foo = noise.filter(foo, foo);
-
- foo = ImageUtil.blur(foo, 4.5f);
-
- // Compose image into rounded corners
- graphics = foo.createGraphics();
- try {
- graphics.setComposite(AlphaComposite.SrcIn);
- graphics.drawImage(dest, 0, 0, null);
- }
- finally {
- graphics.dispose();
- }
-
- float[] scales = new float[] {1, 1, 1, 1};
- float[] offsets = new float[] {80, 40, 0, 0};
- foo = new RescaleOp(scales, offsets, getRenderingHints()).filter(foo, foo);
-
- // Draw it all back to dest
- g = dest.createGraphics();
- try {
- g.setComposite(AlphaComposite.SrcOver);
- g.setColor(Color.WHITE);
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- g.drawImage(foo, 0, 0, null);
- }
- finally {
- g.dispose();
- }
-
- return dest;
- }
-
- public static void main(String[] args) throws IOException {
- exercise(args, new InstaSepiaFilter(), null);
- }
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/MappedBufferImage.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/MappedBufferImage.java
deleted file mode 100644
index 2954364c..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/MappedBufferImage.java
+++ /dev/null
@@ -1,1019 +0,0 @@
-/*
- * 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 com.twelvemonkeys.util.LRUHashMap;
-
-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.event.ActionEvent;
-import java.awt.event.KeyEvent;
-import java.awt.image.BufferedImage;
-import java.awt.image.DataBuffer;
-import java.io.File;
-import java.io.IOException;
-import java.lang.ref.Reference;
-import java.lang.ref.SoftReference;
-import java.util.*;
-import java.util.List;
-import java.util.concurrent.*;
-
-/**
- * MappedBufferImage
- *
- * @author Harald Kuhr
- * @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 * 4);
- private static ExecutorService executorService2 = Executors.newFixedThreadPool(2);
-
- 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 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 types = reader.getImageTypes(0);
- ImageTypeSpecifier type = types.next();
-
- // TODO: Negotiate best layout according to the GraphicsConfiguration.
-
- int sub = 1;
- w = reader.getWidth(0) / sub;
- h = reader.getHeight(0) / sub;
-
- // 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);
-
- // TODO: Display image while reading
-
- ImageReadParam param = reader.getDefaultReadParam();
- param.setDestination(image);
- param.setSourceSubsampling(sub, sub, 0, 0);
-
- 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(WindowConstants.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 steps = threads * height / 100;
- final int inStep = (int) Math.ceil(image.getHeight() / (double) steps);
- final int outStep = (int) Math.ceil(height / (double) steps);
-
- final CountDownLatch latch = new CountDownLatch(steps);
-
- // 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);
-
- System.out.print("[");
- final int dotsPerStep = 78 / steps;
- for (int j = 0; j < 78 - (steps * dotsPerStep); j++) {
- System.out.print(".");
- }
-
- // Resample image in slices
- for (int i = 0; i < steps; 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_TRIANGLE).filter(in, out);
-// new ResampleOp(width, outHeight, ResampleOp.FILTER_LANCZOS).filter(in, out);
-
- for (int j = 0; j < dotsPerStep; j++) {
- System.out.print(".");
- }
- }
- catch (RuntimeException e) {
- e.printStackTrace();
- throw e;
- }
- finally {
- latch.countDown();
- }
- }
- });
- }
-
- Boolean done = null;
- try {
- done = latch.await(5L, TimeUnit.MINUTES);
- }
- catch (InterruptedException ignore) {
- }
- System.out.println("]");
-
- 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;
- private double zoom = 1;
-
- public ImageComponent(final BufferedImage image) {
- setOpaque(true); // Very important when sub classing JComponent...
- setDoubleBuffered(true);
-
- this.image = image;
- }
-
- @Override
- public void addNotify() {
- super.addNotify();
-
- texture = createTexture();
-
- Rectangle bounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
- zoom = Math.min(1.0, Math.min(bounds.getWidth() / (double) image.getWidth(), bounds.getHeight() / (double) image.getHeight()));
-
- // TODO: Take scroll pane into account when zooming (center around center point)
- AbstractAction zoomIn = new AbstractAction() {
- public void actionPerformed(ActionEvent e) {
- System.err.println("ZOOM IN");
- setZoom(zoom * 2);
- }
- };
-
- addAction(KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, getToolkit().getMenuShortcutKeyMask()), zoomIn);
- addAction(KeyStroke.getKeyStroke(KeyEvent.VK_ADD, getToolkit().getMenuShortcutKeyMask()), zoomIn);
- addAction(KeyStroke.getKeyStroke(Character.valueOf('+'), 0), zoomIn);
- addAction(KeyStroke.getKeyStroke(Character.valueOf('+'), getToolkit().getMenuShortcutKeyMask()), zoomIn);
- AbstractAction zoomOut = new AbstractAction() {
- public void actionPerformed(ActionEvent e) {
- System.err.println("ZOOM OUT");
- setZoom(zoom / 2);
- }
- };
- addAction(KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, getToolkit().getMenuShortcutKeyMask()), zoomOut);
- addAction(KeyStroke.getKeyStroke(KeyEvent.VK_SUBTRACT, getToolkit().getMenuShortcutKeyMask()), zoomOut);
- addAction(KeyStroke.getKeyStroke(Character.valueOf('-'), 0), zoomOut);
- addAction(KeyStroke.getKeyStroke(Character.valueOf('-'), getToolkit().getMenuShortcutKeyMask()), zoomOut);
- AbstractAction zoomFit = new AbstractAction() {
- public void actionPerformed(ActionEvent e) {
- System.err.println("ZOOM FIT");
-// Rectangle bounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
- Rectangle bounds = getVisibleRect();
- setZoom(Math.min(1.0, Math.min(bounds.getWidth() / (double) image.getWidth(), bounds.getHeight() / (double) image.getHeight())));
- }
- };
- addAction(KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, getToolkit().getMenuShortcutKeyMask()), zoomFit);
- addAction(KeyStroke.getKeyStroke(KeyEvent.VK_9, getToolkit().getMenuShortcutKeyMask()), zoomFit);
- addAction(KeyStroke.getKeyStroke(KeyEvent.VK_0, getToolkit().getMenuShortcutKeyMask()), new AbstractAction() {
- public void actionPerformed(ActionEvent e) {
- System.err.println("ZOOM ACTUAL");
- setZoom(1);
- }
- });
- }
-
- private void setZoom(final double newZoom) {
- if (newZoom != zoom) {
- zoom = newZoom;
- // TODO: Add PCL support for zoom and discard tiles cache based on property change
- tiles = createTileCache();
- revalidate();
- repaint();
- }
- }
-
- private Map createTileCache() {
- return Collections.synchronizedMap(new SizedLRUMap(16 * 1024 * 1024));
- }
-
- private void addAction(final KeyStroke keyStroke, final AbstractAction action) {
- UUID key = UUID.randomUUID();
- getInputMap(WHEN_IN_FOCUSED_WINDOW).put(keyStroke, key);
- getActionMap().put(key, action);
- }
-
- 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: Java 7 kills the performance from our custom painting... :-(
-
- // 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.
-
- // TODO: Cache visible rect content in buffered/volatile image (s) + visible rect (+ zoom) to speed up repaints
- // - Blit the cahced image (possibly translated) (onto itself?)
- // - Paint only the necessary parts outside the cached image
- // - Async rendering into cached image
-
- // 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);
-
- /*
- // Center image (might not be the best way to cooperate with the scroll pane)
- Rectangle imageSize = new Rectangle((int) Math.round(image.getWidth() * zoom), (int) Math.round(image.getHeight() * zoom));
- if (imageSize.width < getWidth()) {
- g2.translate((getWidth() - imageSize.width) / 2, 0);
- }
- if (imageSize.height < getHeight()) {
- g2.translate(0, (getHeight() - imageSize.height) / 2);
- }
- */
-
- // Zoom
- if (zoom != 1) {
- // NOTE: This helps mostly when scaling up, or scaling down less than 50%
- g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
-
- rect = new Rectangle(
- (int) Math.round(rect.x / zoom), (int) Math.round(rect.y / zoom),
- (int) Math.round(rect.width / zoom), (int) Math.round(rect.height / zoom)
- );
-
- rect = rect.intersection(new Rectangle(image.getWidth(), image.getHeight()));
- }
-
- long start = System.currentTimeMillis();
- repaintImage(rect, g2);
- System.err.println("repaint: " + (System.currentTimeMillis() - start) + " ms");
- }
-
- static class Tile {
- private final int size;
-
- private final int x;
- private final int y;
-
- private final Reference data;
- private final BufferedImage hardRef;
-
- Tile(int x, int y, BufferedImage data) {
- this.x = x;
- this.y = y;
- this.data = new SoftReference(data);
-
- hardRef = data;
-
- size = 16 + data.getWidth() * data.getHeight() * data.getRaster().getNumDataElements() * sizeOf(data.getRaster().getTransferType());
- }
-
- private static int sizeOf(final int transferType) {
- switch (transferType) {
- case DataBuffer.TYPE_INT:
- return 4;
- case DataBuffer.TYPE_SHORT:
- return 2;
- case DataBuffer.TYPE_BYTE:
- return 1;
- default:
- throw new IllegalArgumentException("Unsupported transfer type: " + transferType);
- }
- }
-
- public boolean drawTo(Graphics2D g) {
- BufferedImage img = data.get();
-
- if (img != null) {
- g.drawImage(img, x, y, null);
- return true;
- }
-
- return false;
- }
-
- public int getX() {
- return x;
- }
-
- public int getY() {
- return y;
- }
-
- public int getWidth() {
- BufferedImage img = data.get();
- return img != null ? img.getWidth() : -1;
- }
-
- public int getHeight() {
- BufferedImage img = data.get();
- return img != null ? img.getHeight() : -1;
- }
-
- public Rectangle getRect() {
- BufferedImage img = data.get();
- return img != null ? new Rectangle(x, y, img.getWidth(), img.getHeight()) : null;
- }
-
- public Point getLocation() {
- return new Point(x, y);
- }
-
- @Override
- public boolean equals(Object other) {
- if (this == other) {
- return true;
- }
-
- if (other == null || getClass() != other.getClass()) {
- return false;
- }
-
- Tile tile = (Tile) other;
-
- return x == tile.x && y == tile.y;
- }
-
- @Override
- public int hashCode() {
- return 997 * x + y;
- }
-
- @Override
- public String toString() {
- return String.format("Tile[%d, %d, %d, %d]", x, y, getWidth(), getHeight());
- }
-
- public int size() {
- return size;
- }
- }
-
- // TODO: Consider a fixed size (mem) LRUCache instead
- // TODO: Better yet, re-use tiles
- Map tiles = createTileCache();
-
- private void repaintImage(final Rectangle rect, final Graphics2D g2) {
-// System.err.println("rect: " + rect);
-// System.err.println("tiles: " + tiles.size());
- // TODO: Fix rounding errors
- // FIx repaint bugs
-
- try {
- // Paint tiles of the image, to preserve memory
- final int tileSize = 200;
-
- // Calculate relative to image(0,0), rather than rect(x, y)
- int xOff = rect.x % tileSize;
- int yOff = rect.y % tileSize;
-
- rect.x -= xOff;
- rect.y -= yOff;
- rect.width += xOff;
- rect.height += yOff;
-
- int tilesW = 1 + rect.width / tileSize;
- int tilesH = 1 + rect.height / tileSize;
-
- for (int yTile = 0; yTile <= tilesH; yTile++) {
- for (int xTile = 0; xTile <= tilesW; xTile++) {
- // Image (source) coordinates
- int x = rect.x + xTile * tileSize;
- int y = rect.y + yTile * tileSize;
-
- int w = xTile == tilesW ? Math.min(tileSize, rect.x + rect.width - x) : tileSize;
- int h = yTile == tilesH ? Math.min(tileSize, rect.y + rect.height - y) : tileSize;
-
- if (w == 0 || h == 0) {
- continue;
- }
-
-// System.err.printf("%04d, %04d, %04d, %04d%n", x, y, w, h);
-
- // - Get tile from cache
- // - If non-null, paint
- // - If null, request data for later use, with callback, and return
- // TODO: Could we use ImageProducer/ImageConsumer/ImageObserver interface??
-
- // Destination (display) coordinates
- int dstX = (int) Math.floor(x * zoom);
- int dstY = (int) Math.floor(y * zoom);
- int dstW = (int) Math.ceil(w * zoom);
- int dstH = (int) Math.ceil(h * zoom);
-
- if (dstW == 0 || dstH == 0) {
- continue;
- }
-
- // Don't create overlapping/duplicate tiles...
- // - Always start tile grid at 0,0
- // - Always occupy entire tile, unless edge
-
- // Source (original) coordinates
- int tileSrcX = x - x % tileSize;
- int tileSrcY = y - y % tileSize;
-// final int tileSrcW = Math.min(tileSize, image.getWidth() - tileSrcX);
-// final int tileSrcH = Math.min(tileSize, image.getHeight() - tileSrcY);
-
- // Destination (display) coordinates
- int tileDstX = (int) Math.floor(tileSrcX * zoom);
- int tileDstY = (int) Math.floor(tileSrcY * zoom);
-// final int tileDstW = (int) Math.round(tileSrcW * zoom);
-// final int tileDstH = (int) Math.round(tileSrcH * zoom);
-
- List points = new ArrayList(4);
- points.add(new Point(tileDstX, tileDstY));
- if (tileDstX != dstX) {
- points.add(new Point(tileDstX + tileSize, tileDstY));
- }
- if (tileDstY != dstY) {
- points.add(new Point(tileDstX, tileDstY + tileSize));
- }
- if (tileDstX != dstX && tileDstY != dstY) {
- points.add(new Point(tileDstX + tileSize, tileDstY + tileSize));
- }
-
- for (final Point point : points) {
- Tile tile = tiles.get(point);
-
- if (tile != null) {
- if (tile.drawTo(g2)) {
- continue;
- }
- else {
- tiles.remove(point);
- }
- }
-
-// System.err.printf("Tile miss: [%d, %d]\n", dstX, dstY);
-
- // Dispatch to off-thread worker
- final Map localTiles = tiles;
- executorService2.submit(new Runnable() {
- public void run() {
- int tileSrcX = (int) Math.round(point.x / zoom);
- int tileSrcY = (int) Math.round(point.y / zoom);
- int tileSrcW = Math.min(tileSize, image.getWidth() - tileSrcX);
- int tileSrcH = Math.min(tileSize, image.getHeight() - tileSrcY);
- int tileDstW = (int) Math.round(tileSrcW * zoom);
- int tileDstH = (int) Math.round(tileSrcH * zoom);
-
- try {
- // TODO: Consider comparing zoom/local zoom
- if (localTiles != tiles) {
- return; // Return early after re-zoom
- }
-
- if (localTiles.containsKey(point)) {
-// System.err.println("Skipping tile, already producing...");
- return;
- }
-
- // Test against current view rect, to avoid computing tiles that will be thrown away immediately
- final Rectangle visibleRect = new Rectangle();
- SwingUtilities.invokeAndWait(new Runnable() {
- public void run() {
- visibleRect.setBounds(getVisibleRect());
- }
- });
-
- if (!visibleRect.intersects(new Rectangle(point.x, point.y, tileDstW, tileDstH))) {
- return;
- }
-
-// System.err.printf("Creating tile: [%d, %d]\n", tileDstX, tileDstY);
-
- BufferedImage temp = getGraphicsConfiguration().createCompatibleImage(tileDstW, tileDstH);
- final Tile tile = new Tile(point.x, point.y, temp);
- localTiles.put(point, tile);
-
- Graphics2D graphics = temp.createGraphics();
- try {
- Object hint = g2.getRenderingHint(RenderingHints.KEY_INTERPOLATION);
-
- if (hint != null) {
- graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
- }
-
- graphics.scale(zoom, zoom);
- graphics.drawImage(image.getSubimage(tileSrcX, tileSrcY, tileSrcW, tileSrcH), 0, 0, null);
- }
- finally {
- graphics.dispose();
- }
-
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- repaint(10, tile.x, tile.y, tile.getWidth(), tile.getHeight());
- }
- });
- }
- catch (Throwable t) {
- localTiles.remove(point);
- System.err.println("Boooo: " + t.getMessage());
- }
- }
- });
- }
-
- }
- }
- }
- catch (NullPointerException e) {
-// e.printStackTrace();
- // Happens whenever apple.awt.OSXCachingSurfaceManager runs out of memory
- // TODO: Figure out why repaint(x,y,w,h) doesn't work any more..?
- System.err.println("Full repaint due to NullPointerException (probably out of memory).");
- repaint(); // NOTE: Might cause a brief flash while the component is redrawn
- }
- }
-
- private void repaintImage0(final Rectangle rect, final Graphics2D g2) {
- g2.scale(zoom, zoom);
-
- try {
- // Paint tiles of the image, to preserve memory
- final int tileSize = 200;
-
- int tilesW = rect.width / tileSize;
- int tilesH = rect.height / tileSize;
-
- for (int yTile = 0; yTile <= tilesH; yTile++) {
- for (int xTile = 0; xTile <= tilesW; xTile++) {
- // Image (source) coordinates
- final int x = rect.x + xTile * tileSize;
- final int y = rect.y + yTile * tileSize;
-
- final int w = xTile == tilesW ? Math.min(tileSize, rect.x + rect.width - x) : tileSize;
- final int h = yTile == tilesH ? Math.min(tileSize, rect.y + rect.height - y) : tileSize;
-
- 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);
-
- }
- }
- }
- catch (NullPointerException e) {
-// e.printStackTrace();
- // Happens whenever apple.awt.OSXCachingSurfaceManager runs out of memory
- // TODO: Figure out why repaint(x,y,w,h) doesn't work any more..?
- System.err.println("Full repaint due to NullPointerException (probably out of memory).");
- 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 getWidth() > getPreferredSize().width;
- }
-
- public boolean getScrollableTracksViewportHeight() {
- return getHeight() > getPreferredSize().height;
- }
- }
-
- final static class SizedLRUMap extends LRUHashMap {
- int currentSize;
- int maxSize;
-
- public SizedLRUMap(int pMaxSize) {
- super(); // Note: super.maxSize doesn't count...
- maxSize = pMaxSize;
- }
-
-
- protected int sizeOf(final Object pValue) {
- ImageComponent.Tile cached = (ImageComponent.Tile) pValue;
-
- if (cached == null) {
- return 0;
- }
-
- return cached.size();
- }
-
- @Override
- public V put(K pKey, V pValue) {
- currentSize += sizeOf(pValue);
-
- V old = super.put(pKey, pValue);
- if (old != null) {
- currentSize -= sizeOf(old);
- }
- return old;
- }
-
- @Override
- public V remove(Object pKey) {
- V old = super.remove(pKey);
- if (old != null) {
- currentSize -= sizeOf(old);
- }
- return old;
- }
-
- @Override
- protected boolean removeEldestEntry(Map.Entry pEldest) {
- if (maxSize <= currentSize) { // NOTE: maxSize here is mem size
- removeLRU();
- }
- return false;
- }
-
- @Override
- public void removeLRU() {
- while (maxSize <= currentSize) { // NOTE: maxSize here is mem size
- super.removeLRU();
- }
- }
- }
-
- 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("[");
- }
- }
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/MappedFileBuffer.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/MappedFileBuffer.java
deleted file mode 100644
index ff1acafc..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/MappedFileBuffer.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * 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 Harald Kuhr
- * @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);
- }
- }
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/MappedImageFactory.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/MappedImageFactory.java
deleted file mode 100644
index 2dd4ac58..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/MappedImageFactory.java
+++ /dev/null
@@ -1,325 +0,0 @@
-/*
- * 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 javax.imageio.ImageTypeSpecifier;
-import java.awt.*;
-import java.awt.color.ColorSpace;
-import java.awt.image.*;
-import java.io.IOException;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Modifier;
-import java.lang.reflect.UndeclaredThrowableException;
-
-/**
- * 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 Harald Kuhr
- * @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 :-/
- // - Might be possible (but slow) to copy parts to memory and do CCOp on these copies
-
- private static final boolean DEBUG = "true".equalsIgnoreCase(System.getProperty("com.twelvemonkeys.image.mapped.debug"));
-
- /* Constants for DirectColorModel masks, from BufferedImage. */
- private static final int DCM_RED_MASK = 0x00ff0000;
- private static final int DCM_GREEN_MASK = 0x0000ff00;
- private static final int DCM_BLUE_MASK = 0x000000ff;
- private static final int DCM_ALPHA_MASK = 0xff000000;
- private static final int DCM_565_RED_MASK = 0xf800;
- private static final int DCM_565_GRN_MASK = 0x07E0;
- private static final int DCM_565_BLU_MASK = 0x001F;
- private static final int DCM_555_RED_MASK = 0x7C00;
- private static final int DCM_555_GRN_MASK = 0x03E0;
- private static final int DCM_555_BLU_MASK = 0x001F;
- private static final int DCM_BGR_RED_MASK = 0x0000ff;
- private static final int DCM_BGR_GRN_MASK = 0x00ff00;
- private static final int DCM_BGR_BLU_MASK = 0xff0000;
-
- static final RasterFactory RASTER_FACTORY = createRasterFactory();
-
- 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 {
- 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, RASTER_FACTORY.createRaster(sm, buffer, new Point()), cm.isAlphaPremultiplied(), null);
- }
-
- /**
- *
- * Returns the {@code BufferedImage} image type that is compatible with the data in {@code image}.
- * This method will return compatible types, even if {@code BufferedImage.getType()} returns
- * {@code BufferedImage.TYPE_CUSTOM}.
- *
- *
- * This method is defined to work so that, for any valid {@code BufferedImage} type
- * (except {@code BufferedImage.TYPE_CUSTOM}), the following is {@code true}:
- *
- * {@code getCompatibleBufferedImageType(createCompatibleMappedImage(w, h, type)) == type}
- *
- *
- * If no standard type is compatible with the image data, {@code BufferedImage.TYPE_CUSTOM} is returned.
- *
- *
- * @param image the image to test, may not be {@code null}.
- *
- * @return the {@code BufferedImage} type.
- *
- * @throws java.lang.IllegalArgumentException if {@code image} is {@code null}.
- *
- * @see java.awt.image.BufferedImage#getType()
- */
- public static int getCompatibleBufferedImageType(final BufferedImage image) {
- Validate.notNull(image, "image");
-
- WritableRaster raster = image.getRaster();
- SampleModel sm = raster.getSampleModel();
- int numBands = raster.getNumBands();
-
- ColorModel cm = image.getColorModel();
- ColorSpace cs = cm.getColorSpace();
- boolean isAlphaPre = cm.isAlphaPremultiplied();
- int csType = cs.getType();
-
- int dataType = raster.getDataBuffer().getDataType();
-
- if (csType != ColorSpace.TYPE_RGB) {
- if (csType == ColorSpace.TYPE_GRAY && cm instanceof ComponentColorModel) {
- if (sm instanceof ComponentSampleModel && ((ComponentSampleModel) sm).getPixelStride() != numBands) {
- return BufferedImage.TYPE_CUSTOM;
- }
- else if (dataType == DataBuffer.TYPE_BYTE && raster.getNumBands() == 1 &&
- cm.getComponentSize(0) == 8 && ((ComponentSampleModel) sm).getPixelStride() == 1) {
- return BufferedImage.TYPE_BYTE_GRAY;
- }
- else if (dataType == DataBuffer.TYPE_USHORT && raster.getNumBands() == 1 &&
- cm.getComponentSize(0) == 16 && ((ComponentSampleModel) sm).getPixelStride() == 1) {
- return BufferedImage.TYPE_USHORT_GRAY;
- }
- }
- else {
- return BufferedImage.TYPE_CUSTOM;
- }
- }
-
- if ((dataType == DataBuffer.TYPE_INT) && (numBands == 3 || numBands == 4)) {
- // Check if the raster params and the color model are correct
- int pixSize = cm.getPixelSize();
-
- if (cm instanceof DirectColorModel && sm.getNumDataElements() == 1 && (pixSize == 32 || pixSize == 24)) {
- // Now check on the DirectColorModel params
- DirectColorModel dcm = (DirectColorModel) cm;
- int rmask = dcm.getRedMask();
- int gmask = dcm.getGreenMask();
- int bmask = dcm.getBlueMask();
-
- if (rmask == DCM_RED_MASK && gmask == DCM_GREEN_MASK && bmask == DCM_BLUE_MASK) {
- if (dcm.getAlphaMask() == DCM_ALPHA_MASK) {
- return isAlphaPre ? BufferedImage.TYPE_INT_ARGB_PRE : BufferedImage.TYPE_INT_ARGB;
- }
- else if (!dcm.hasAlpha()) {
- // No Alpha
- return BufferedImage.TYPE_INT_RGB;
- }
- }
- else if (rmask == DCM_BGR_RED_MASK && gmask == DCM_BGR_GRN_MASK && bmask == DCM_BGR_BLU_MASK) {
- if (!dcm.hasAlpha()) {
- return BufferedImage.TYPE_INT_BGR;
- }
- }
- }
- }
- else if ((cm instanceof IndexColorModel) && (numBands == 1) && (!cm.hasAlpha() || !isAlphaPre)) {
- IndexColorModel icm = (IndexColorModel) cm;
- int pixSize = icm.getPixelSize();
-
- if (dataType == DataBuffer.TYPE_BYTE && sm instanceof MultiPixelPackedSampleModel) {
- return BufferedImage.TYPE_BYTE_BINARY;
- }
- if (dataType == DataBuffer.TYPE_BYTE && sm instanceof ComponentSampleModel) {
- ComponentSampleModel csm = (ComponentSampleModel) sm;
-
- if (csm.getPixelStride() == 1 && pixSize <= 8) {
- return BufferedImage.TYPE_BYTE_INDEXED;
- }
- }
- }
- else if ((dataType == DataBuffer.TYPE_USHORT) &&
- (cm instanceof DirectColorModel) && (numBands == 3) && !cm.hasAlpha()) {
- DirectColorModel dcm = (DirectColorModel) cm;
-
- if (dcm.getRedMask() == DCM_565_RED_MASK &&
- dcm.getGreenMask() == DCM_565_GRN_MASK && dcm.getBlueMask() == DCM_565_BLU_MASK) {
- return BufferedImage.TYPE_USHORT_565_RGB;
- }
- else if (dcm.getRedMask() == DCM_555_RED_MASK &&
- dcm.getGreenMask() == DCM_555_GRN_MASK && dcm.getBlueMask() == DCM_555_BLU_MASK) {
- return BufferedImage.TYPE_USHORT_555_RGB;
- }
- }
- else if (dataType == DataBuffer.TYPE_BYTE && cm instanceof ComponentColorModel &&
- raster.getSampleModel() instanceof PixelInterleavedSampleModel && (numBands == 3 || numBands == 4)) {
- ComponentColorModel ccm = (ComponentColorModel) cm;
- PixelInterleavedSampleModel csm = (PixelInterleavedSampleModel) raster.getSampleModel();
-
- int[] offs = csm.getBandOffsets();
- int[] nBits = ccm.getComponentSize();
- boolean is8bit = true;
-
- for (int i = 0; i < numBands; i++) {
- if (nBits[i] != 8) {
- is8bit = false;
- break;
- }
- }
-
- if (is8bit && csm.getPixelStride() == numBands &&
- offs[0] == numBands - 1 && offs[1] == numBands - 2 && offs[2] == numBands - 3) {
- if (numBands == 3 && !ccm.hasAlpha()) {
- return BufferedImage.TYPE_3BYTE_BGR;
- }
- else if (offs[3] == 0 && ccm.hasAlpha()) {
- return isAlphaPre ? BufferedImage.TYPE_4BYTE_ABGR_PRE : BufferedImage.TYPE_4BYTE_ABGR;
- }
- }
- }
-
- return BufferedImage.TYPE_CUSTOM;
- }
-
- private static RasterFactory createRasterFactory() {
- try {
- // Try to instantiate, will throw LinkageError if it fails
- return new SunRasterFactory();
- }
- catch (LinkageError e) {
- if (DEBUG) {
- e.printStackTrace();
- }
-
- System.err.println("Could not instantiate SunWritableRaster, falling back to GenericWritableRaster.");
- }
-
- // Fall back
- return new GenericRasterFactory();
- }
-
- static interface RasterFactory {
- WritableRaster createRaster(SampleModel model, DataBuffer buffer, Point origin);
- }
-
- /**
- * Generic implementation that should work for any JRE, and creates a custom subclass of {@link WritableRaster}.
- */
- static final class GenericRasterFactory implements RasterFactory {
- public WritableRaster createRaster(final SampleModel model, final DataBuffer buffer, final Point origin) {
- return new GenericWritableRaster(model, buffer, origin);
- }
- }
-
- /**
- * Sun/Oracle JRE-specific implementation that creates {@code sun.awt.image.SunWritableRaster}.
- * Callers must catch {@link LinkageError}.
- */
- static final class SunRasterFactory implements RasterFactory {
- final private Constructor factoryMethod = getFactoryMethod();
-
- @SuppressWarnings("unchecked")
- private static Constructor getFactoryMethod() {
- try {
- Class> cls = Class.forName("sun.awt.image.SunWritableRaster");
-
- if (Modifier.isAbstract(cls.getModifiers())) {
- throw new IncompatibleClassChangeError("sun.awt.image.SunWritableRaster has become abstract and can't be instantiated");
- }
-
- return (Constructor) cls.getConstructor(SampleModel.class, DataBuffer.class, Point.class);
- }
- catch (ClassNotFoundException e) {
- throw new NoClassDefFoundError(e.getMessage());
- }
- catch (NoSuchMethodException e) {
- throw new NoSuchMethodError(e.getMessage());
- }
- }
-
- public WritableRaster createRaster(final SampleModel model, final DataBuffer buffer, final Point origin) {
- try {
- return factoryMethod.newInstance(model, buffer, origin);
- }
- catch (InstantiationException e) {
- throw new Error("Could not create SunWritableRaster: ", e); // Should never happen, as we test for abstract class
- }
- catch (IllegalAccessException e) {
- throw new Error("Could not create SunWritableRaster: ", e); // Should never happen, only public constructors are reflected
- }
- catch (InvocationTargetException e) {
- // Unwrap to allow normal exception flow
- Throwable cause = e.getCause();
-
- if (cause instanceof RuntimeException) {
- throw (RuntimeException) cause;
- }
- else if (cause instanceof Error) {
- throw (Error) cause;
- }
-
- throw new UndeclaredThrowableException(cause);
- }
- }
- }
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/NoiseFilter.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/NoiseFilter.java
deleted file mode 100644
index 73c8d50b..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/NoiseFilter.java
+++ /dev/null
@@ -1,228 +0,0 @@
-/*
- * 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.
- */
-/*
-Copyright 2006 Jerry Huxtable
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-package com.twelvemonkeys.image;
-
-import java.awt.image.BufferedImage;
-import java.awt.image.WritableRaster;
-import java.util.Random;
-
-/**
- * NoiseFilter
- *
- * @author Harald Kuhr
- * @author last modified by $Author: haraldk$
- * @version $Id: NoiseFilter.java,v 1.0 15.06.12 22:59 haraldk Exp$
- */
-public class NoiseFilter extends AbstractFilter {
-
- /**
- * Gaussian distribution for the noise.
- */
- public final static int GAUSSIAN = 0;
-
- /**
- * Uniform distribution for the noise.
- */
- public final static int UNIFORM = 1;
-
- private int amount = 25;
- private int distribution = UNIFORM;
- private boolean monochrome = false;
- private float density = 1;
- private Random randomNumbers = new Random();
-
- public NoiseFilter() {
- }
-
- /**
- * Set the amount of effect.
- *
- * @param amount the amount
- * @min-value 0
- * @max-value 1
- * @see #getAmount
- */
- public void setAmount(int amount) {
- this.amount = amount;
- }
-
- /**
- * Get the amount of noise.
- *
- * @return the amount
- * @see #setAmount
- */
- public int getAmount() {
- return amount;
- }
-
- /**
- * Set the distribution of the noise.
- *
- * @param distribution the distribution
- * @see #getDistribution
- */
- public void setDistribution(int distribution) {
- this.distribution = distribution;
- }
-
- /**
- * Get the distribution of the noise.
- *
- * @return the distribution
- * @see #setDistribution
- */
- public int getDistribution() {
- return distribution;
- }
-
- /**
- * Set whether to use monochrome noise.
- *
- * @param monochrome true for monochrome noise
- * @see #getMonochrome
- */
- public void setMonochrome(boolean monochrome) {
- this.monochrome = monochrome;
- }
-
- /**
- * Get whether to use monochrome noise.
- *
- * @return true for monochrome noise
- * @see #setMonochrome
- */
- public boolean getMonochrome() {
- return monochrome;
- }
-
- /**
- * Set the density of the noise.
- *
- * @param density the density
- * @see #getDensity
- */
- public void setDensity(float density) {
- this.density = density;
- }
-
- /**
- * Get the density of the noise.
- *
- * @return the density
- * @see #setDensity
- */
- public float getDensity() {
- return density;
- }
-
- private int random() {
- return (int) (((distribution == GAUSSIAN ? randomNumbers.nextGaussian() : 2 * randomNumbers.nextFloat() - 1)) * amount);
- }
-
- private static int clamp(int x) {
- if (x < 0) {
- return 0;
- }
- else if (x > 0xff) {
- return 0xff;
- }
- return x;
- }
-
- public int filterRGB(int x, int y, int rgb) {
- if (randomNumbers.nextFloat() <= density) {
- int a = rgb & 0xff000000;
- int r = (rgb >> 16) & 0xff;
- int g = (rgb >> 8) & 0xff;
- int b = rgb & 0xff;
-
- if (monochrome) {
- int n = random();
- r = clamp(r + n);
- g = clamp(g + n);
- b = clamp(b + n);
- }
- else {
- r = clamp(r + random());
- g = clamp(g + random());
- b = clamp(b + random());
- }
- return a | (r << 16) | (g << 8) | b;
- }
- return rgb;
- }
-
- public BufferedImage filter(BufferedImage src, BufferedImage dst) {
- int width = src.getWidth();
- int height = src.getHeight();
- int type = src.getType();
- WritableRaster srcRaster = src.getRaster();
-
- if (dst == null) {
- dst = createCompatibleDestImage(src, null);
- }
- WritableRaster dstRaster = dst.getRaster();
-
- int[] inPixels = new int[width];
- for (int y = 0; y < height; y++) {
- // We try to avoid calling getRGB on images as it causes them to become unmanaged, causing horrible performance problems.
- if (type == BufferedImage.TYPE_INT_ARGB) {
- srcRaster.getDataElements(0, y, width, 1, inPixels);
- for (int x = 0; x < width; x++) {
- inPixels[x] = filterRGB(x, y, inPixels[x]);
- }
- dstRaster.setDataElements(0, y, width, 1, inPixels);
- }
- else {
- src.getRGB(0, y, width, 1, inPixels, 0, width);
- for (int x = 0; x < width; x++) {
- inPixels[x] = filterRGB(x, y, inPixels[x]);
- }
- dst.setRGB(0, y, width, 1, inPixels, 0, width);
- }
- }
-
- return dst;
- }
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/SubsampleTester.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/SubsampleTester.java
deleted file mode 100755
index be8e52f2..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/SubsampleTester.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * 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 Harald Kuhr
- * @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 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;
- }
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/inv_cmap.c b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/inv_cmap.c
deleted file mode 100755
index efdc5600..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/inv_cmap.c
+++ /dev/null
@@ -1,524 +0,0 @@
-/*
- * 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
-#include
-
-
-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<> 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;
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/FileLockingTest.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/FileLockingTest.java
deleted file mode 100755
index 101a1179..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/FileLockingTest.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * 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 Harald Kuhr
- * @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");
- }
- }
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/FileMonitor.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/FileMonitor.java
deleted file mode 100755
index 84584c78..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/FileMonitor.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * 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 Harald Kuhr
- * @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;
- }
-
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/StringInputStream.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/StringInputStream.java
deleted file mode 100644
index 61e0fb50..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/StringInputStream.java
+++ /dev/null
@@ -1,87 +0,0 @@
-package com.twelvemonkeys.io;
-
-import com.twelvemonkeys.lang.Validate;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetEncoder;
-
-/**
- * An {@code InputStream} that reads bytes from a {@code String}.
- *
- * This class properly converts characters into bytes using a {@code Charset},
- * unlike the deprecated {@link java.io.StringBufferInputStream}.
- *
- * @author Harald Kuhr
- * @author last modified by $Author: haraldk$
- * @version $Id: StringInputStream.java,v 1.0 03.09.13 10:19 haraldk Exp$
- */
-public final class StringInputStream extends InputStream {
-
- private final CharBuffer chars;
- private final CharsetEncoder encoder;
- private final ByteBuffer buffer;
-
- public StringInputStream(final String string, final Charset charset) {
- this(Validate.notNull(string, "string"), 0, string.length(), charset);
- }
-
- public StringInputStream(final String string, int offset, int length, final Charset charset) {
- chars = CharBuffer.wrap(Validate.notNull(string, "string"), offset, offset + length);
- encoder = Validate.notNull(charset, "charset").newEncoder();
- buffer = ByteBuffer.allocate(256);
- buffer.flip();
- }
-
- private boolean fillBuffer() {
- buffer.clear();
- encoder.encode(chars, buffer, chars.hasRemaining()); // TODO: Do we have to care about the result?
- buffer.flip();
-
- return buffer.hasRemaining();
- }
-
- private boolean ensureBuffer() {
- return buffer.hasRemaining() || (chars.hasRemaining() && fillBuffer());
- }
-
- @Override
- public int read() throws IOException {
- if (!ensureBuffer()) {
- return -1;
- }
-
- return buffer.get() & 0xff;
- }
-
- @Override
- public int read(byte[] b, int off, int len) throws IOException {
- if (!ensureBuffer()) {
- return -1;
- }
-
- int count = Math.min(buffer.remaining(), len);
- buffer.get(b, off, count);
- return count;
- }
-
- @Override
- public long skip(long len) throws IOException {
- if (!ensureBuffer()) {
- return -1;
- }
-
- int count = (int) Math.min(buffer.remaining(), len);
- int position = buffer.position();
- buffer.position(position + count);
- return count;
- }
-
- @Override
- public int available() throws IOException {
- return buffer.remaining();
- }
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/enc/DeflateEncoder.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/enc/DeflateEncoder.java
deleted file mode 100644
index 176cf8b4..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/enc/DeflateEncoder.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * 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.nio.ByteBuffer;
-import java.util.zip.Deflater;
-
-/**
- * {@code Encoder} implementation for standard DEFLATE encoding.
- *
- *
- * @author Harald Kuhr
- * @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/io/enc/DeflateEncoder.java#2 $
- *
- * @see RFC 1951
- * @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(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 stream, ByteBuffer buffer)
- throws IOException
- {
- System.out.println("DeflateEncoder.encode");
- deflater.setInput(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining());
- flushInputToStream(stream);
- }
-
- 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();
-// }
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/enc/InflateDecoder.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/enc/InflateDecoder.java
deleted file mode 100644
index e69b8b68..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/io/enc/InflateDecoder.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * 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.nio.ByteBuffer;
-import java.util.zip.DataFormatException;
-import java.util.zip.Inflater;
-
-/**
- * {@code Decoder} implementation for standard DEFLATE encoding.
- *
- *
- * @see RFC 1951
- *
- * @see Inflater
- * @see DeflateEncoder
- * @see java.util.zip.InflaterInputStream
- *
- * @author Harald Kuhr
- * @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 stream, final ByteBuffer buffer) throws IOException {
- try {
- int decoded;
-
- while ((decoded = inflater.inflate(buffer.array(), buffer.arrayOffset(), buffer.capacity())) == 0) {
- if (inflater.finished() || inflater.needsDictionary()) {
- return 0;
- }
-
- if (inflater.needsInput()) {
- fill(stream);
- }
- }
-
- 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);
- }
-}
\ No newline at end of file
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/DuckType.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/DuckType.java
deleted file mode 100755
index 97eb33d1..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/DuckType.java
+++ /dev/null
@@ -1,468 +0,0 @@
-/*
- * 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…”.
- *
- * Based on an idea found at
- * The Visual Editor
- *
- * @author Harald Kuhr
- * @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());
- }
- }
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/ExceptionUtil.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/ExceptionUtil.java
deleted file mode 100755
index 9d1f89cf..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/ExceptionUtil.java
+++ /dev/null
@@ -1,89 +0,0 @@
-package com.twelvemonkeys.lang;
-
-import java.lang.reflect.UndeclaredThrowableException;
-
-import static com.twelvemonkeys.lang.Validate.notNull;
-
-/**
- * ExceptionUtil
- *
- * @author Harald Kuhr
- * @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 void throwAs(final Class 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[]) pHandlers);
- }
-
- private static void handleImpl(final Throwable pThrowable, final ThrowableHandler... pHandlers) {
- // TODO: Sort more specific throwable handlers before less specific?
- for (ThrowableHandler handler : pHandlers) {
- if (handler.handles(pThrowable)) {
- handler.handle(pThrowable);
- return;
- }
- }
-
- // Not handled, re-throw
- throwUnchecked(pThrowable);
- }
-
- public static abstract class ThrowableHandler {
- 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);
- }
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/MathUtil.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/MathUtil.java
deleted file mode 100755
index 5432d151..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/MathUtil.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * 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;
-
-/**
- * The class MathUtil contains methods for performing basic numeric operations
- * such as the elementary exponential, logarithm, square root, and
- * trigonometric functions.
- *
- * @author Harald Kuhr
- * @author last modified by $Author: haku $
- *
- * @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/lang/MathUtil.java#1 $
- */
-public final class MathUtil {
-
- /** */
- private MathUtil() {
- }
-
- /**
- * Returns the natural logarithm (base e) of a double value.
- * Equivalent to {@code java.lang.Math.log}, just with a proper name.
- *
- * @param pArg a number greater than 0.0.
- * @return the value ln {@code pArg}, the natural logarithm of
- * {@code pArg}.
- *
- * @see java.lang.Math#log(double)
- */
- public static double ln(final double pArg) {
- return Math.log(pArg);
- }
-
- /**
- * Returns the base 10 logarithm of a double value.
- *
- * @param pArg a number greater than 0.0.
- * @return the value log {@code pArg}, the base 10 logarithm of
- * {@code pArg}.
- */
- public static double log(final double pArg) {
- return Math.log10(pArg);
- }
-
- private final static double LN_2 = Math.log(2);
-
- /**
- * Returns the base 2 logarithm of a double value.
- *
- * @param pArg a number greater than 0.0.
- * @return the value log2 {@code pArg}, the base 2
- * logarithm of {@code pArg}.
- */
- public static double log2(final double pArg) {
- return Math.log(pArg) / LN_2;
- }
-
- /**
- * Returns the base N logarithm of a double value, for a given base
- * N.
- *
- * @param pArg a number greater than 0.0.
- * @param pBase a number greater than 0.0.
- *
- * @return the value logpBase {@code pArg}, the base
- * {@code pBase} logarithm of {@code pArg}.
- */
- public static double log(final double pArg, final double pBase) {
- return Math.log(pArg) / Math.log(pBase);
- }
-
- /**
- * A replacement for {@code Math.abs}, that never returns negative values.
- * {@code Math.abs(long)} does this for {@code Long.MIN_VALUE}.
- *
- * @see Math#abs(long)
- * @see Long#MIN_VALUE
- *
- * @param pNumber a number
- * @return the absolute value of {@code pNumber}
- *
- * @throws ArithmeticException if {@code pNumber == Long.MIN_VALUE}
- */
- public static long abs(final long pNumber) {
- if (pNumber == Long.MIN_VALUE) {
- throw new ArithmeticException("long overflow: 9223372036854775808");
- }
-
- return (pNumber < 0) ? -pNumber : pNumber;
- }
-
- /**
- * A replacement for {@code Math.abs}, that never returns negative values.
- * {@code Math.abs(int)} does this for {@code Integer.MIN_VALUE}.
- *
- * @see Math#abs(int)
- * @see Integer#MIN_VALUE
- *
- * @param pNumber a number
- * @return the absolute value of {@code pNumber}
- *
- * @throws ArithmeticException if {@code pNumber == Integer.MIN_VALUE}
- */
- public static int abs(final int pNumber) {
- if (pNumber == Integer.MIN_VALUE) {
- throw new ArithmeticException("int overflow: 2147483648");
- }
-
- return (pNumber < 0) ? -pNumber : pNumber;
- }
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/MostUnfortunateException.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/MostUnfortunateException.java
deleted file mode 100755
index 120f1ff1..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/MostUnfortunateException.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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
- *
- *
- * @author Harald Kuhr
- * @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);
- }
-}
\ No newline at end of file
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/NativeLoader.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/NativeLoader.java
deleted file mode 100755
index 6d097cfa..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/NativeLoader.java
+++ /dev/null
@@ -1,401 +0,0 @@
-/*
- * 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
- *
- *
- * @author Harald Kuhr
- * @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 .(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) 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 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 providers(final String nativeResource) {
- return new FilterIterator(
- providers(NativeResourceSPI.class),
- new NameFilter(nativeResource)
- );
- }
- }
-
- private static class NameFilter implements FilterIterator.Filter {
- 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());
- }
- }
-}
\ No newline at end of file
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/NativeResourceSPI.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/NativeResourceSPI.java
deleted file mode 100755
index 2290ef2a..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/lang/NativeResourceSPI.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * 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.
- *
- *
- * @author Harald Kuhr
- * @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.
- *
- * 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.
- *
- * 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.
- *
- * 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);
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/AuthenticatorFilter.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/AuthenticatorFilter.java
deleted file mode 100755
index 21171d22..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/AuthenticatorFilter.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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.net;
-
-import java.net.*;
-
-/**
- * Interface for filtering Authenticator requests, used by the
- * SimpleAuthenticator.
- *
- * @see SimpleAuthenticator
- * @see java.net.Authenticator
- *
- * @author Harald Kuhr
- * @version 1.0
- */
-public interface AuthenticatorFilter {
- public boolean accept(InetAddress pAddress, int pPort, String pProtocol, String pPrompt, String pScheme);
-}
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/BASE64.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/BASE64.java
deleted file mode 100755
index 4d4346f8..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/BASE64.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * 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.net;
-
-import com.twelvemonkeys.io.*;
-import com.twelvemonkeys.io.enc.Base64Decoder;
-import com.twelvemonkeys.io.enc.DecoderStream;
-
-import java.io.*;
-
-
-/**
- * This class does BASE64 encoding (and decoding).
- *
- * @author unascribed
- * @author last modified by $Author: haku $
- * @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/util/BASE64.java#1 $
- * @deprecated Use {@link com.twelvemonkeys.io.enc.Base64Encoder}/{@link Base64Decoder} instead
- */
-class BASE64 {
- /**
- * This array maps the characters to their 6 bit values
- */
- private final static char[] PEM_ARRAY = {
- //0 1 2 3 4 5 6 7
- 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', // 0
- 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 1
- 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 2
- 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', // 3
- 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', // 4
- 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', // 5
- 'w', 'x', 'y', 'z', '0', '1', '2', '3', // 6
- '4', '5', '6', '7', '8', '9', '+', '/' // 7
- };
-
- /**
- * Encodes the input data using the standard base64 encoding scheme.
- *
- * @param pData the bytes to encode to base64
- * @return a string with base64 encoded data
- */
- public static String encode(byte[] pData) {
- int offset = 0;
- int len;
- StringBuilder buf = new StringBuilder();
-
- while ((pData.length - offset) > 0) {
- byte a, b, c;
- if ((pData.length - offset) > 2) {
- len = 3;
- }
- else {
- len = pData.length - offset;
- }
-
- switch (len) {
- case 1:
- a = pData[offset];
- b = 0;
- buf.append(PEM_ARRAY[(a >>> 2) & 0x3F]);
- buf.append(PEM_ARRAY[((a << 4) & 0x30) + ((b >>> 4) & 0xf)]);
- buf.append('=');
- buf.append('=');
- offset++;
- break;
- case 2:
- a = pData[offset];
- b = pData[offset + 1];
- c = 0;
- buf.append(PEM_ARRAY[(a >>> 2) & 0x3F]);
- buf.append(PEM_ARRAY[((a << 4) & 0x30) + ((b >>> 4) & 0xf)]);
- buf.append(PEM_ARRAY[((b << 2) & 0x3c) + ((c >>> 6) & 0x3)]);
- buf.append('=');
- offset += offset + 2; // ???
- break;
- default:
- a = pData[offset];
- b = pData[offset + 1];
- c = pData[offset + 2];
- buf.append(PEM_ARRAY[(a >>> 2) & 0x3F]);
- buf.append(PEM_ARRAY[((a << 4) & 0x30) + ((b >>> 4) & 0xf)]);
- buf.append(PEM_ARRAY[((b << 2) & 0x3c) + ((c >>> 6) & 0x3)]);
- buf.append(PEM_ARRAY[c & 0x3F]);
- offset = offset + 3;
- break;
- }
-
- }
- return buf.toString();
- }
-
- public static byte[] decode(String pData) throws IOException {
- InputStream in = new DecoderStream(new ByteArrayInputStream(pData.getBytes()), new Base64Decoder());
- ByteArrayOutputStream bytes = new FastByteArrayOutputStream(pData.length() * 3);
- FileUtil.copy(in, bytes);
-
- return bytes.toByteArray();
- }
-
- //private final static sun.misc.BASE64Decoder DECODER = new sun.misc.BASE64Decoder();
-
- public static void main(String[] pArgs) throws IOException {
- if (pArgs.length == 1) {
- System.out.println(encode(pArgs[0].getBytes()));
- }
- else
- if (pArgs.length == 2 && ("-d".equals(pArgs[0]) || "--decode".equals(pArgs[0])))
- {
- System.out.println(new String(decode(pArgs[1])));
- }
- else {
- System.err.println("BASE64 [ -d | --decode ] arg");
- System.err.println("Encodes or decodes a given string");
- System.exit(5);
- }
- }
-}
\ No newline at end of file
diff --git a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java b/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java
deleted file mode 100755
index 62119c2b..00000000
--- a/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java
+++ /dev/null
@@ -1,1101 +0,0 @@
-/*
- * 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.net;
-
-import com.twelvemonkeys.lang.StringUtil;
-
-import java.io.*;
-import java.net.*;
-import java.util.*;
-
-/**
- * A URLConnection with support for HTTP-specific features. See
- * the spec for details.
- * This version also supports read and connect timeouts, making it more useful
- * for clients with limitted time.
- *
- * Note that the timeouts are created on the socket level, and that
- *
- * Note: This class should now work as expected, but it needs more testing before
- * it can enter production release.
- *
- * --.k
- *
- * @author Harald Kuhr
- * @author last modified by $Author: haku $
- * @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java#1 $
- * @todo Write JUnit TestCase
- * @todo ConnectionMananger!
- * @see RFC 2616
- */
-public class HttpURLConnection extends java.net.HttpURLConnection {
- /**
- * HTTP Status-Code 307: Temporary Redirect
- */
- public final static int HTTP_REDIRECT = 307;
- private final static int HTTP_DEFAULT_PORT = 80;
- private final static String HTTP_HEADER_END = "\r\n\r\n";
- private static final String HEADER_WWW_AUTH = "WWW-Authenticate";
- private final static int BUF_SIZE = 8192;
- private int maxRedirects = (System.getProperty("http.maxRedirects") != null)
- ? Integer.parseInt(System.getProperty("http.maxRedirects"))
- : 20;
- protected int timeout = -1;
- protected int connectTimeout = -1;
- private Socket socket = null;
- protected InputStream errorStream = null;
- protected InputStream inputStream = null;
- protected OutputStream outputStream = null;
- private String[] responseHeaders = null;
- protected Properties responseHeaderFields = null;
- protected Properties requestProperties = new Properties();
-
- /**
- * Creates a HttpURLConnection.
- *
- * @param pURL the URL to connect to.
- */
- protected HttpURLConnection(URL pURL) {
- this(pURL, 0, 0);
- }
-
- /**
- * Creates a HttpURLConnection with a given read and connect timeout.
- * A timeout value of zero is interpreted as an
- * infinite timeout.
- *
- * @param pURL the URL to connect to.
- * @param pTimeout the maximum time the socket will block for read
- * and connect operations.
- */
- protected HttpURLConnection(URL pURL, int pTimeout) {
- this(pURL, pTimeout, pTimeout);
- }
-
- /**
- * Creates a HttpURLConnection with a given read and connect timeout.
- * A timeout value of zero is interpreted as an
- * infinite timeout.
- *
- * @param pURL the URL to connect to.
- * @param pTimeout the maximum time the socket will block for read
- * operations.
- * @param pConnectTimeout the maximum time the socket will block for
- * connection.
- */
- protected HttpURLConnection(URL pURL, int pTimeout, int pConnectTimeout) {
- super(pURL);
- setTimeout(pTimeout);
- connectTimeout = pConnectTimeout;
- }
-
- /**
- * Sets the general request property. If a property with the key already
- * exists, overwrite its value with the new value.
- *
- *
NOTE: HTTP requires all request properties which can
- * legally have multiple instances with the same key
- * to use a comma-seperated list syntax which enables multiple
- * properties to be appended into a single property.
- *
- * @param pKey the keyword by which the request is known
- * (e.g., "{@code accept}").
- * @param pValue the value associated with it.
- * @see #getRequestProperty(java.lang.String)
- */
- public void setRequestProperty(String pKey, String pValue) {
- if (connected) {
- throw new IllegalAccessError("Already connected");
- }
- String oldValue = requestProperties.getProperty(pKey);
-
- if (oldValue == null) {
- requestProperties.setProperty(pKey, pValue);
- }
- else {
- requestProperties.setProperty(pKey, oldValue + ", " + pValue);
- }
- }
-
- /**
- * Returns the value of the named general request property for this
- * connection.
- *
- * @param pKey the keyword by which the request is known (e.g., "accept").
- * @return the value of the named general request property for this
- * connection.
- * @see #setRequestProperty(java.lang.String, java.lang.String)
- */
- public String getRequestProperty(String pKey) {
- if (connected) {
- throw new IllegalAccessError("Already connected");
- }
- return requestProperties.getProperty(pKey);
- }
-
- /**
- * Gets HTTP response status from responses like:
- *
- * Extracts the ints 200 and 401 respectively.
- * Returns -1 if none can be discerned
- * from the response (i.e., the response is not valid HTTP).
- *
- *
- *
- * @return the HTTP Status-Code
- * @throws IOException if an error occurred connecting to the server.
- */
- public int getResponseCode() throws IOException {
- if (responseCode != -1) {
- return responseCode;
- }
-
- // Make sure we've gotten the headers
- getInputStream();
- String resp = getHeaderField(0);
-
- // should have no leading/trailing LWS
- // expedite the typical case by assuming it has the
- // form "HTTP/1.x 2XX "
- int ind;
-
- try {
- ind = resp.indexOf(' ');
- while (resp.charAt(ind) == ' ') {
- ind++;
- }
- responseCode = Integer.parseInt(resp.substring(ind, ind + 3));
- responseMessage = resp.substring(ind + 4).trim();
- return responseCode;
- }
- catch (Exception e) {
- return responseCode;
- }
- }
-
- /**
- * Returns the name of the specified header field.
- *
- * @param pName the name of a header field.
- * @return the value of the named header field, or {@code null}
- * if there is no such field in the header.
- */
- public String getHeaderField(String pName) {
- return responseHeaderFields.getProperty(StringUtil.toLowerCase(pName));
- }
-
- /**
- * Returns the value for the {@code n}th header field.
- * It returns {@code null} if there are fewer than
- * {@code n} fields.
- *
- * This method can be used in conjunction with the
- * {@code getHeaderFieldKey} method to iterate through all
- * the headers in the message.
- *
- * @param pIndex an index.
- * @return the value of the {@code n}th header field.
- * @see java.net.URLConnection#getHeaderFieldKey(int)
- */
- public String getHeaderField(int pIndex) {
- // TODO: getInputStream() first, to make sure we have header fields
- if (pIndex >= responseHeaders.length) {
- return null;
- }
- String field = responseHeaders[pIndex];
-
- // pIndex == 0, means the response code etc (i.e. "HTTP/1.1 200 OK").
- if ((pIndex == 0) || (field == null)) {
- return field;
- }
- int idx = field.indexOf(':');
-
- return ((idx > 0)
- ? field.substring(idx).trim()
- : ""); // TODO: "" or null?
- }
-
- /**
- * Returns the key for the {@code n}th header field.
- *
- * @param pIndex an index.
- * @return the key for the {@code n}th header field,
- * or {@code null} if there are fewer than {@code n}
- * fields.
- */
- public String getHeaderFieldKey(int pIndex) {
- // TODO: getInputStream() first, to make sure we have header fields
- if (pIndex >= responseHeaders.length) {
- return null;
- }
- String field = responseHeaders[pIndex];
-
- if (StringUtil.isEmpty(field)) {
- return null;
- }
- int idx = field.indexOf(':');
-
- return StringUtil.toLowerCase(((idx > 0)
- ? field.substring(0, idx)
- : field));
- }
-
- /**
- * Sets the read timeout for the undelying socket.
- * A timeout of zero is interpreted as an
- * infinite timeout.
- *
- * @param pTimeout the maximum time the socket will block for read
- * operations, in milliseconds.
- */
- public void setTimeout(int pTimeout) {
- if (pTimeout < 0) { // Must be positive
- throw new IllegalArgumentException("Timeout must be positive.");
- }
- timeout = pTimeout;
- if (socket != null) {
- try {
- socket.setSoTimeout(pTimeout);
- }
- catch (SocketException se) {
- // Not much to do about that...
- }
- }
- }
-
- /**
- * Gets the read timeout for the undelying socket.
- *
- * @return the maximum time the socket will block for read operations, in
- * milliseconds.
- * The default value is zero, which is interpreted as an
- * infinite timeout.
- */
- public int getTimeout() {
-
- try {
- return ((socket != null)
- ? socket.getSoTimeout()
- : timeout);
- }
- catch (SocketException se) {
- return timeout;
- }
- }
-
- /**
- * Returns an input stream that reads from this open connection.
- *
- * @return an input stream that reads from this open connection.
- * @throws IOException if an I/O error occurs while
- * creating the input stream.
- */
- public synchronized InputStream getInputStream() throws IOException {
- if (!connected) {
- connect();
- }
-
- // Nothing to return
- if (responseCode == HTTP_NOT_FOUND) {
- throw new FileNotFoundException(url.toString());
- }
- int length;
-
- if (inputStream == null) {
- return null;
- }
-
- // "De-chunk" the output stream
- else if ("chunked".equalsIgnoreCase(getHeaderField("Transfer-Encoding"))) {
- if (!(inputStream instanceof ChunkedInputStream)) {
- inputStream = new ChunkedInputStream(inputStream);
- }
- }
-
- // Make sure we don't wait forever, if the content-length is known
- else if ((length = getHeaderFieldInt("Content-Length", -1)) >= 0) {
- if (!(inputStream instanceof FixedLengthInputStream)) {
- inputStream = new FixedLengthInputStream(inputStream, length);
- }
- }
- return inputStream;
- }
-
- /**
- * Returns an output stream that writes to this connection.
- *
- * @return an output stream that writes to this connection.
- * @throws IOException if an I/O error occurs while
- * creating the output stream.
- */
- public synchronized OutputStream getOutputStream() throws IOException {
-
- if (!connected) {
- connect();
- }
- return outputStream;
- }
-
- /**
- * Indicates that other requests to the server
- * are unlikely in the near future. Calling disconnect()
- * should not imply that this HttpURLConnection
- * instance can be reused for other requests.
- */
- public void disconnect() {
- if (socket != null) {
- try {
- socket.close();
- }
- catch (IOException ioe) {
-
- // Does not matter, I guess.
- }
- socket = null;
- }
- connected = false;
- }
-
- /**
- * Internal connect method.
- */
- private void connect(final URL pURL, PasswordAuthentication pAuth, String pAuthType, int pRetries) throws IOException {
- // Find correct port
- final int port = (pURL.getPort() > 0)
- ? pURL.getPort()
- : HTTP_DEFAULT_PORT;
-
- // Create socket if we don't have one
- if (socket == null) {
- //socket = new Socket(pURL.getHost(), port); // Blocks...
- socket = createSocket(pURL, port, connectTimeout);
- socket.setSoTimeout(timeout);
- }
-
- // Get Socket output stream
- OutputStream os = socket.getOutputStream();
-
- // Connect using HTTP
- writeRequestHeaders(os, pURL, method, requestProperties, usingProxy(), pAuth, pAuthType);
-
- // Get response input stream
- InputStream sis = socket.getInputStream();
- BufferedInputStream is = new BufferedInputStream(sis);
-
- // Detatch reponse headers from reponse input stream
- InputStream header = detatchResponseHeader(is);
-
- // Parse headers and set response code/message
- responseHeaders = parseResponseHeader(header);
- responseHeaderFields = parseHeaderFields(responseHeaders);
-
- //System.err.println("Headers fields:");
- //responseHeaderFields.list(System.err);
- // Test HTTP response code, to see if further action is needed
- switch (getResponseCode()) {
- case HTTP_OK:
- // 200 OK
- inputStream = is;
- errorStream = null;
- break;
-
- /*
- case HTTP_PROXY_AUTH:
- // 407 Proxy Authentication Required
- */
- case HTTP_UNAUTHORIZED:
- // 401 Unauthorized
- // Set authorization and try again.. Slightly more compatible
- responseCode = -1;
-
- // IS THIS REDIRECTION??
- //if (instanceFollowRedirects) { ???
- String auth = getHeaderField(HEADER_WWW_AUTH);
-
- // Missing WWW-Authenticate header for 401 response is an error
- if (StringUtil.isEmpty(auth)) {
- throw new ProtocolException("Missing \"" + HEADER_WWW_AUTH + "\" header for response: 401 " + responseMessage);
- }
-
- // Get real mehtod from WWW-Authenticate header
- int SP = auth.indexOf(" ");
- String method;
- String realm = null;
-
- if (SP >= 0) {
- method = auth.substring(0, SP);
- if (auth.length() >= SP + 7) {
- realm = auth.substring(SP + 7); // " realm=".lenght() == 7
- }
-
- // else no realm
- }
- else {
- // Default mehtod is Basic
- method = SimpleAuthenticator.BASIC;
- }
-
- // Get PasswordAuthentication
- PasswordAuthentication pa = Authenticator.requestPasswordAuthentication(NetUtil.createInetAddressFromURL(pURL), port,
- pURL.getProtocol(), realm, method);
-
- // Avoid infinite loop
- if (pRetries++ <= 0) {
- throw new ProtocolException("Server redirected too many times (" + maxRedirects + ") (Authentication required: " + auth + ")"); // This is what sun.net.www.protocol.http.HttpURLConnection does
- }
- else if (pa != null) {
- connect(pURL, pa, method, pRetries);
- }
- break;
- case HTTP_MOVED_PERM:
- // 301 Moved Permanently
- case HTTP_MOVED_TEMP:
- // 302 Found
- case HTTP_SEE_OTHER:
- // 303 See Other
- /*
- case HTTP_USE_PROXY:
- // 305 Use Proxy
- // How do we handle this?
- */
- case HTTP_REDIRECT:
- // 307 Temporary Redirect
- //System.err.println("Redirecting " + getResponseCode());
- if (instanceFollowRedirects) {
- // Redirect
- responseCode = -1; // Because of the java.net.URLConnection
-
- // getResponseCode implementation...
- // ---
- // I think redirects must be get?
- //setRequestMethod("GET");
- // ---
- String location = getHeaderField("Location");
- URL newLoc = new URL(pURL, location);
-
- // Test if we can reuse the Socket
- if (!(newLoc.getAuthority().equals(pURL.getAuthority()) && (newLoc.getPort() == pURL.getPort()))) {
- socket.close(); // Close the socket, won't need it anymore
- socket = null;
- }
- if (location != null) {
- //System.err.println("Redirecting to " + location);
- // Avoid infinite loop
- if (--pRetries <= 0) {
- throw new ProtocolException("Server redirected too many times (5)");
- }
- else {
- connect(newLoc, pAuth, pAuthType, pRetries);
- }
- }
- break;
- }
-
- // ...else, fall through default (if no Location: header)
- default :
- // Not 200 OK, or any of the redirect responses
- // Probably an error...
- errorStream = is;
- inputStream = null;
- }
-
- // --- Need rethinking...
- // No further questions, let the Socket wait forever (until the server
- // closes the connection)
- //socket.setSoTimeout(0);
- // Probably not... The timeout should only kick if the read BLOCKS.
- // Shutdown output, meaning any writes to the outputstream below will
- // probably fail...
- //socket.shutdownOutput();
- // Not a good idea at all... POSTs need the outputstream to send the
- // form-data.
- // --- /Need rethinking.
- outputStream = os;
- }
-
- private static interface SocketConnector extends Runnable {
-
- /**
- * Method getSocket
- *
- * @return the socket
- * @throws IOException
- */
- public Socket getSocket() throws IOException;
- }
-
- /**
- * Creates a socket to the given URL and port, with the given connect
- * timeout. If the socket waits more than the given timout to connect,
- * an ConnectException is thrown.
- *
- * @param pURL the URL to connect to
- * @param pPort the port to connect to
- * @param pConnectTimeout the connect timeout
- * @return the created Socket.
- * @throws ConnectException if the connection is refused or otherwise
- * times out.
- * @throws UnknownHostException if the IP address of the host could not be
- * determined.
- * @throws IOException if an I/O error occurs when creating the socket.
- * @todo Move this code to a SocetImpl or similar?
- * @see Socket#Socket(String,int)
- */
- private Socket createSocket(final URL pURL, final int pPort, int pConnectTimeout) throws IOException {
- Socket socket;
- final Object current = this;
- SocketConnector connector;
- Thread t = new Thread(connector = new SocketConnector() {
-
- private IOException mConnectException = null;
- private Socket mLocalSocket = null;
-
- public Socket getSocket() throws IOException {
-
- if (mConnectException != null) {
- throw mConnectException;
- }
- return mLocalSocket;
- }
-
- // Run method
- public void run() {
-
- try {
- mLocalSocket = new Socket(pURL.getHost(), pPort); // Blocks...
- }
- catch (IOException ioe) {
-
- // Store this exception for later
- mConnectException = ioe;
- }
-
- // Signal that we are done
- synchronized (current) {
- current.notify();
- }
- }
- });
-
- t.start();
-
- // Wait for connect
- synchronized (this) {
- try {
-
- /// Only wait if thread is alive!
- if (t.isAlive()) {
- if (pConnectTimeout > 0) {
- wait(pConnectTimeout);
- }
- else {
- wait();
- }
- }
- }
- catch (InterruptedException ie) {
-
- // Continue excecution on interrupt? Hmmm..
- }
- }
-
- // Throw exception if the socket didn't connect fast enough
- if ((socket = connector.getSocket()) == null) {
- throw new ConnectException("Socket connect timed out!");
- }
- return socket;
- }
-
- /**
- * Opens a communications link to the resource referenced by this
- * URL, if such a connection has not already been established.
- *
- * If the {@code connect} method is called when the connection
- * has already been opened (indicated by the {@code connected}
- * field having the value {@code true}), the call is ignored.
- *
- * URLConnection objects go through two phases: first they are
- * created, then they are connected. After being created, and
- * before being connected, various options can be specified
- * (e.g., doInput and UseCaches). After connecting, it is an
- * error to try to set them. Operations that depend on being
- * connected, like getContentLength, will implicitly perform the
- * connection, if necessary.
- *
- * @throws IOException if an I/O error occurs while opening the
- * connection.
- * @see java.net.URLConnection#connected
- * @see RFC 2616
- */
- public void connect() throws IOException {
- if (connected) {
- return; // Ignore
- }
- connected = true;
- connect(url, null, null, maxRedirects);
- }
-
- /**
- * TODO: Proxy support is still missing.
- *
- * @return this method returns false, as proxy suport is not implemented.
- */
- public boolean usingProxy() {
- return false;
- }
-
- /**
- * Writes the HTTP request headers, for HTTP GET method.
- *
- * @see RFC 2616
- */
- private static void writeRequestHeaders(OutputStream pOut, URL pURL, String pMethod, Properties pProps, boolean pUsingProxy,
- PasswordAuthentication pAuth, String pAuthType) {
- PrintWriter out = new PrintWriter(pOut, true); // autoFlush
-
- if (!pUsingProxy) {
- out.println(pMethod + " " + (!StringUtil.isEmpty(pURL.getPath())
- ? pURL.getPath()
- : "/") + ((pURL.getQuery() != null)
- ? "?" + pURL.getQuery()
- : "") + " HTTP/1.1"); // HTTP/1.1
-
- // out.println("Connection: close"); // No persistent connections yet
-
- /*
- System.err.println(pMethod + " "
- + (!StringUtil.isEmpty(pURL.getPath()) ? pURL.getPath() : "/")
- + (pURL.getQuery() != null ? "?" + pURL.getQuery() : "")
- + " HTTP/1.1"); // HTTP/1.1
- */
-
- // Authority (Host: HTTP/1.1 field, but seems to work for HTTP/1.0)
- out.println("Host: " + pURL.getHost() + ((pURL.getPort() != -1)
- ? ":" + pURL.getPort()
- : ""));
-
- /*
- System.err.println("Host: " + pURL.getHost()
- + (pURL.getPort() != -1 ? ":" + pURL.getPort() : ""));
- */
- }
- else {
-
- ////-- PROXY (absolute) VERSION
- out.println(pMethod + " " + pURL.getProtocol() + "://" + pURL.getHost() + ((pURL.getPort() != -1)
- ? ":" + pURL.getPort()
- : "") + pURL.getPath() + ((pURL.getQuery() != null)
- ? "?" + pURL.getQuery()
- : "") + " HTTP/1.1");
- }
-
- // Check if we have authentication
- if (pAuth != null) {
-
- // If found, set Authorization header
- byte[] userPass = (pAuth.getUserName() + ":" + new String(pAuth.getPassword())).getBytes();
-
- // "Authorization" ":" credentials
- out.println("Authorization: " + pAuthType + " " + BASE64.encode(userPass));
-
- /*
- System.err.println("Authorization: " + pAuthType + " "
- + BASE64.encode(userPass));
- */
- }
-
- // Iterate over properties
-
- for (Map.Entry
- *
- *
Tag Reference
- *
- *
- *
notEqual
- *
Availability: 1.0
- *
- *
- *
Tag for testing if an attribute is NOT equal to a given value.
- *
- *
- *
- * @version 1.0
- * @author Eirik Torske
- * @see equal
- */
-public class NotEqualTag extends ConditionalTagBase {
-
- /**
- *
- *
- * The condition that must be met in order to display the body of this tag:
- *
- *
The attribute name property ({@code name} -> {@code mObjectName}) must not be empty.
- *
The attribute must exist.
- *
The attribute must be an instance of one of the supported classes:
- *
- *
{@code java.lang.String}
- *
{@code javax.servlet.http.Cookie}
- *
- *
The value of the attribute must NOT be equal to the object value property ({@code value} -> {@code mObjectValue}).
- *
- *
- * NB! If the object value property ({@code value} -> {@code mObjectValue}) is empty than {@code true} will be returned.
- *