mirror of
https://github.com/haraldk/TwelveMonkeys.git
synced 2026-05-27 00:00:02 -04:00
Re-added test case lost in large merge
- Removed imageio-jmagick (again) - Removed internal Maven repo - fixed line endings on a number of files to avoid a humongous merge diff when getting changes into upstream - Re-enabled a few tests
This commit is contained in:
@@ -1,90 +1,90 @@
|
||||
/*
|
||||
* Copyright (c) 2008, Harald Kuhr
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name "TwelveMonkeys" nor the
|
||||
* names of its contributors may be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
package com.twelvemonkeys.io.enc;
|
||||
|
||||
import java.io.OutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.zip.Deflater;
|
||||
|
||||
/**
|
||||
* {@code Encoder} implementation for standard DEFLATE encoding.
|
||||
* <p/>
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/io/enc/DeflateEncoder.java#2 $
|
||||
*
|
||||
* @see <a href="http://tools.ietf.org/html/rfc1951">RFC 1951</a>
|
||||
* @see Deflater
|
||||
* @see InflateDecoder
|
||||
* @see java.util.zip.DeflaterOutputStream
|
||||
*/
|
||||
final class DeflateEncoder implements Encoder {
|
||||
|
||||
private final Deflater deflater;
|
||||
private final byte[] buffer = new byte[1024];
|
||||
|
||||
public DeflateEncoder() {
|
||||
this(new Deflater(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();
|
||||
// }
|
||||
}
|
||||
/*
|
||||
* 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.
|
||||
* <p/>
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/io/enc/DeflateEncoder.java#2 $
|
||||
*
|
||||
* @see <a href="http://tools.ietf.org/html/rfc1951">RFC 1951</a>
|
||||
* @see Deflater
|
||||
* @see InflateDecoder
|
||||
* @see java.util.zip.DeflaterOutputStream
|
||||
*/
|
||||
final class DeflateEncoder implements Encoder {
|
||||
|
||||
private final Deflater deflater;
|
||||
private final byte[] buffer = new byte[1024];
|
||||
|
||||
public DeflateEncoder() {
|
||||
this(new Deflater(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();
|
||||
// }
|
||||
}
|
||||
|
||||
+109
-109
@@ -1,110 +1,110 @@
|
||||
/*
|
||||
* 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.
|
||||
* <p/>
|
||||
*
|
||||
* @see <a href="http://tools.ietf.org/html/rfc1951">RFC 1951</a>
|
||||
*
|
||||
* @see Inflater
|
||||
* @see DeflateEncoder
|
||||
* @see java.util.zip.InflaterInputStream
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/io/enc/InflateDecoder.java#2 $
|
||||
*/
|
||||
final class InflateDecoder implements Decoder {
|
||||
|
||||
private final Inflater inflater;
|
||||
|
||||
private final byte[] buffer;
|
||||
|
||||
/**
|
||||
* Creates an {@code InflateDecoder}
|
||||
*
|
||||
*/
|
||||
public InflateDecoder() {
|
||||
this(new Inflater(true));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an {@code InflateDecoder}
|
||||
*
|
||||
* @param pInflater the inflater instance to use
|
||||
*/
|
||||
public InflateDecoder(final Inflater pInflater) {
|
||||
if (pInflater == null) {
|
||||
throw new IllegalArgumentException("inflater == null");
|
||||
}
|
||||
|
||||
inflater = pInflater;
|
||||
buffer = new byte[1024];
|
||||
}
|
||||
|
||||
public int decode(final InputStream 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);
|
||||
}
|
||||
/*
|
||||
* 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.
|
||||
* <p/>
|
||||
*
|
||||
* @see <a href="http://tools.ietf.org/html/rfc1951">RFC 1951</a>
|
||||
*
|
||||
* @see Inflater
|
||||
* @see DeflateEncoder
|
||||
* @see java.util.zip.InflaterInputStream
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/io/enc/InflateDecoder.java#2 $
|
||||
*/
|
||||
final class InflateDecoder implements Decoder {
|
||||
|
||||
private final Inflater inflater;
|
||||
|
||||
private final byte[] buffer;
|
||||
|
||||
/**
|
||||
* Creates an {@code InflateDecoder}
|
||||
*
|
||||
*/
|
||||
public InflateDecoder() {
|
||||
this(new Inflater(true));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an {@code InflateDecoder}
|
||||
*
|
||||
* @param pInflater the inflater instance to use
|
||||
*/
|
||||
public InflateDecoder(final Inflater pInflater) {
|
||||
if (pInflater == null) {
|
||||
throw new IllegalArgumentException("inflater == null");
|
||||
}
|
||||
|
||||
inflater = pInflater;
|
||||
buffer = new byte[1024];
|
||||
}
|
||||
|
||||
public int decode(final InputStream 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);
|
||||
}
|
||||
}
|
||||
@@ -1,401 +1,401 @@
|
||||
/*
|
||||
* Copyright (c) 2008, Harald Kuhr
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name "TwelveMonkeys" nor the
|
||||
* names of its contributors may be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
package com.twelvemonkeys.lang;
|
||||
|
||||
import com.twelvemonkeys.io.FileUtil;
|
||||
import com.twelvemonkeys.util.FilterIterator;
|
||||
import com.twelvemonkeys.util.service.ServiceRegistry;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
|
||||
/**
|
||||
* NativeLoader
|
||||
* <p/>
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/lang/NativeLoader.java#2 $
|
||||
*/
|
||||
final class NativeLoader {
|
||||
// TODO: Considerations:
|
||||
// - Rename all libs like the current code, to <library>.(so|dll|dylib)?
|
||||
// - Keep library filename from jar, and rather store a separate
|
||||
// properties-file with the library->library-file mappings?
|
||||
// - As all invocations are with library file name, we could probably skip
|
||||
// both renaming and properties-file altogether...
|
||||
|
||||
// TODO: The real trick here, is how to load the correct library for the
|
||||
// current platform...
|
||||
// - Change String pResource to String[] pResources?
|
||||
// - NativeResource class, that has a list of multiple resources?
|
||||
// NativeResource(Map<String, String>) os->native lib mapping
|
||||
|
||||
// TODO: Consider exposing the method from SystemUtil
|
||||
|
||||
// TODO: How about a SPI based solution?!
|
||||
// public interface com.twelvemonkeys.lang.NativeResourceProvider
|
||||
//
|
||||
// imlementations return a pointer to the correct resource for a given (by
|
||||
// this class) OS.
|
||||
//
|
||||
// String getResourceName(...)
|
||||
//
|
||||
// See http://tolstoy.com/samizdat/sysprops.html
|
||||
// System properties:
|
||||
// "os.name"
|
||||
// Windows, Linux, Solaris/SunOS,
|
||||
// Mac OS/Mac OS X/Rhapsody (aka Mac OS X Server)
|
||||
// General Unix (AIX, Digital Unix, FreeBSD, HP-UX, Irix)
|
||||
// OS/2
|
||||
// "os.arch"
|
||||
// Windows: x86
|
||||
// Linux: x86, i386, i686, x86_64, ia64,
|
||||
// Solaris: sparc, sparcv9, x86
|
||||
// Mac OS: PowerPC, ppc, i386
|
||||
// AIX: x86, ppc
|
||||
// Digital Unix: alpha
|
||||
// FreeBSD: x86, sparc
|
||||
// HP-UX: PA-RISC
|
||||
// Irix: mips
|
||||
// OS/2: x86
|
||||
// "os.version"
|
||||
// Windows: 4.0 -> NT/95, 5.0 -> 2000, 5.1 -> XP (don't care about old versions, CE etc)
|
||||
// Mac OS: 8.0, 8.1, 10.0 -> OS X, 10.x.x -> OS X, 5.6 -> Rhapsody (!)
|
||||
//
|
||||
// Normalize os.name, os.arch and os.version?!
|
||||
|
||||
|
||||
///** Normalized operating system constant */
|
||||
//static final OperatingSystem OS_NAME = normalizeOperatingSystem();
|
||||
//
|
||||
///** Normalized system architecture constant */
|
||||
//static final Architecture OS_ARCHITECTURE = normalizeArchitecture();
|
||||
//
|
||||
///** Unormalized operating system version constant (for completeness) */
|
||||
//static final String OS_VERSION = System.getProperty("os.version");
|
||||
|
||||
static final NativeResourceRegistry sRegistry = new NativeResourceRegistry();
|
||||
|
||||
private NativeLoader() {
|
||||
}
|
||||
|
||||
/*
|
||||
private static Architecture normalizeArchitecture() {
|
||||
String arch = System.getProperty("os.arch");
|
||||
if (arch == null) {
|
||||
throw new IllegalStateException("System property \"os.arch\" == null");
|
||||
}
|
||||
|
||||
arch = arch.toLowerCase();
|
||||
if (OS_NAME == OperatingSystem.Windows
|
||||
&& (arch.startsWith("x86") || arch.startsWith("i386"))) {
|
||||
return Architecture.X86;
|
||||
// TODO: 64 bit
|
||||
}
|
||||
else if (OS_NAME == OperatingSystem.Linux) {
|
||||
if (arch.startsWith("x86") || arch.startsWith("i386")) {
|
||||
return Architecture.I386;
|
||||
}
|
||||
else if (arch.startsWith("i686")) {
|
||||
return Architecture.I686;
|
||||
}
|
||||
// TODO: More Linux options?
|
||||
// TODO: 64 bit
|
||||
}
|
||||
else if (OS_NAME == OperatingSystem.MacOS) {
|
||||
if (arch.startsWith("power") || arch.startsWith("ppc")) {
|
||||
return Architecture.PPC;
|
||||
}
|
||||
else if (arch.startsWith("i386")) {
|
||||
return Architecture.I386;
|
||||
}
|
||||
}
|
||||
else if (OS_NAME == OperatingSystem.Solaris) {
|
||||
if (arch.startsWith("sparc")) {
|
||||
return Architecture.SPARC;
|
||||
}
|
||||
if (arch.startsWith("x86")) {
|
||||
// TODO: Should we use i386 as Linux and Mac does?
|
||||
return Architecture.X86;
|
||||
}
|
||||
// TODO: 64 bit
|
||||
}
|
||||
|
||||
return Architecture.Unknown;
|
||||
}
|
||||
*/
|
||||
|
||||
/*
|
||||
private static OperatingSystem normalizeOperatingSystem() {
|
||||
String os = System.getProperty("os.name");
|
||||
if (os == null) {
|
||||
throw new IllegalStateException("System property \"os.name\" == null");
|
||||
}
|
||||
|
||||
os = os.toLowerCase();
|
||||
if (os.startsWith("windows")) {
|
||||
return OperatingSystem.Windows;
|
||||
}
|
||||
else if (os.startsWith("linux")) {
|
||||
return OperatingSystem.Linux;
|
||||
}
|
||||
else if (os.startsWith("mac os")) {
|
||||
return OperatingSystem.MacOS;
|
||||
}
|
||||
else if (os.startsWith("solaris") || os.startsWith("sunos")) {
|
||||
return OperatingSystem.Solaris;
|
||||
}
|
||||
|
||||
return OperatingSystem.Unknown;
|
||||
}
|
||||
*/
|
||||
|
||||
// TODO: We could actually have more than one resource for each lib...
|
||||
private static String getResourceFor(String pLibrary) {
|
||||
Iterator<NativeResourceSPI> providers = sRegistry.providers(pLibrary);
|
||||
while (providers.hasNext()) {
|
||||
NativeResourceSPI resourceSPI = providers.next();
|
||||
|
||||
try {
|
||||
return resourceSPI.getClassPathResource(Platform.get());
|
||||
}
|
||||
catch (Throwable t) {
|
||||
// Dergister and try next
|
||||
sRegistry.deregister(resourceSPI);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a native library.
|
||||
*
|
||||
* @param pLibrary name of the library
|
||||
*
|
||||
* @throws UnsatisfiedLinkError
|
||||
*/
|
||||
public static void loadLibrary(String pLibrary) {
|
||||
loadLibrary0(pLibrary, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a native library.
|
||||
*
|
||||
* @param pLibrary name of the library
|
||||
* @param pLoader the class loader to use
|
||||
*
|
||||
* @throws UnsatisfiedLinkError
|
||||
*/
|
||||
public static void loadLibrary(String pLibrary, ClassLoader pLoader) {
|
||||
loadLibrary0(pLibrary, null, pLoader);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a native library.
|
||||
*
|
||||
* @param pLibrary name of the library
|
||||
* @param pResource name of the resource
|
||||
* @param pLoader the class loader to use
|
||||
*
|
||||
* @throws UnsatisfiedLinkError
|
||||
*/
|
||||
static void loadLibrary0(String pLibrary, String pResource, ClassLoader pLoader) {
|
||||
if (pLibrary == null) {
|
||||
throw new IllegalArgumentException("library == null");
|
||||
}
|
||||
|
||||
// Try loading normal way
|
||||
UnsatisfiedLinkError unsatisfied;
|
||||
try {
|
||||
System.loadLibrary(pLibrary);
|
||||
return;
|
||||
}
|
||||
catch (UnsatisfiedLinkError err) {
|
||||
// Ignore
|
||||
unsatisfied = err;
|
||||
}
|
||||
|
||||
final ClassLoader loader = pLoader != null ? pLoader : Thread.currentThread().getContextClassLoader();
|
||||
final String resource = pResource != null ? pResource : getResourceFor(pLibrary);
|
||||
|
||||
// TODO: resource may be null, and that MIGHT be okay, IFF the resource
|
||||
// is allready unpacked to the user dir... However, we then need another
|
||||
// way to resolve the library extension...
|
||||
// Right now we just fail in a predictable way (no NPE)!
|
||||
if (resource == null) {
|
||||
throw unsatisfied;
|
||||
}
|
||||
|
||||
// Default to load/store from user.home
|
||||
File dir = new File(System.getProperty("user.home") + "/.twelvemonkeys/lib");
|
||||
dir.mkdirs();
|
||||
//File libraryFile = new File(dir.getAbsolutePath(), pLibrary + LIBRARY_EXTENSION);
|
||||
File libraryFile = new File(dir.getAbsolutePath(), pLibrary + "." + FileUtil.getExtension(resource));
|
||||
|
||||
if (!libraryFile.exists()) {
|
||||
try {
|
||||
extractToUserDir(resource, libraryFile, loader);
|
||||
}
|
||||
catch (IOException ioe) {
|
||||
UnsatisfiedLinkError err = new UnsatisfiedLinkError("Unable to extract resource to dir: " + libraryFile.getAbsolutePath());
|
||||
err.initCause(ioe);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// Try to load the library from the file we just wrote
|
||||
System.load(libraryFile.getAbsolutePath());
|
||||
}
|
||||
|
||||
private static void extractToUserDir(String pResource, File pLibraryFile, ClassLoader pLoader) throws IOException {
|
||||
// Get resource from classpath
|
||||
InputStream in = pLoader.getResourceAsStream(pResource);
|
||||
if (in == null) {
|
||||
throw new FileNotFoundException("Unable to locate classpath resource: " + pResource);
|
||||
}
|
||||
|
||||
// Write to file in user dir
|
||||
FileOutputStream fileOut = null;
|
||||
try {
|
||||
fileOut = new FileOutputStream(pLibraryFile);
|
||||
|
||||
byte[] tmp = new byte[1024];
|
||||
// copy the contents of our resource out to the destination
|
||||
// dir 1K at a time. 1K may seem arbitrary at first, but today
|
||||
// is a Tuesday, so it makes perfect sense.
|
||||
int bytesRead = in.read(tmp);
|
||||
while (bytesRead != -1) {
|
||||
fileOut.write(tmp, 0, bytesRead);
|
||||
bytesRead = in.read(tmp);
|
||||
}
|
||||
}
|
||||
finally {
|
||||
FileUtil.close(fileOut);
|
||||
FileUtil.close(in);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Validate OS names?
|
||||
// Windows
|
||||
// Linux
|
||||
// Solaris
|
||||
// Mac OS (OSX+)
|
||||
// Generic Unix?
|
||||
// Others?
|
||||
|
||||
// TODO: OSes that support different architectures might require different
|
||||
// resources for each architecture.. Need a namespace/flavour system
|
||||
// TODO: 32 bit/64 bit issues?
|
||||
// Eg: Windows, Windows/32, Windows/64, Windows/Intel/64?
|
||||
// Solaris/Sparc, Solaris/Intel/64
|
||||
// MacOS/PowerPC, MacOS/Intel
|
||||
/*
|
||||
public static class NativeResource {
|
||||
private Map mMap;
|
||||
|
||||
public NativeResource(String[] pOSNames, String[] pReourceNames) {
|
||||
if (pOSNames == null) {
|
||||
throw new IllegalArgumentException("osNames == null");
|
||||
}
|
||||
if (pReourceNames == null) {
|
||||
throw new IllegalArgumentException("resourceNames == null");
|
||||
}
|
||||
if (pOSNames.length != pReourceNames.length) {
|
||||
throw new IllegalArgumentException("osNames.length != resourceNames.length");
|
||||
}
|
||||
|
||||
Map map = new HashMap();
|
||||
for (int i = 0; i < pOSNames.length; i++) {
|
||||
map.put(pOSNames[i], pReourceNames[i]);
|
||||
}
|
||||
|
||||
mMap = Collections.unmodifiableMap(map);
|
||||
}
|
||||
|
||||
public NativeResource(Map pMap) {
|
||||
if (pMap == null) {
|
||||
throw new IllegalArgumentException("map == null");
|
||||
}
|
||||
|
||||
Map map = new HashMap(pMap);
|
||||
|
||||
Iterator it = map.keySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
Map.Entry entry = (Map.Entry) it.next();
|
||||
if (!(entry.getKey() instanceof String && entry.getValue() instanceof String)) {
|
||||
throw new IllegalArgumentException("map contains non-string entries: " + entry);
|
||||
}
|
||||
}
|
||||
|
||||
mMap = Collections.unmodifiableMap(map);
|
||||
}
|
||||
|
||||
protected NativeResource() {
|
||||
}
|
||||
|
||||
public final String resourceForCurrentOS() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
protected String getResourceName(String pOSName) {
|
||||
return (String) mMap.get(pOSName);
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
private static class NativeResourceRegistry extends ServiceRegistry {
|
||||
public NativeResourceRegistry() {
|
||||
super(Collections.singletonList(NativeResourceSPI.class).iterator());
|
||||
registerApplicationClasspathSPIs();
|
||||
}
|
||||
|
||||
Iterator<NativeResourceSPI> providers(final String nativeResource) {
|
||||
return new FilterIterator<NativeResourceSPI>(
|
||||
providers(NativeResourceSPI.class),
|
||||
new NameFilter(nativeResource)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private static class NameFilter implements FilterIterator.Filter<NativeResourceSPI> {
|
||||
private final String name;
|
||||
|
||||
NameFilter(String pName) {
|
||||
if (pName == null) {
|
||||
throw new IllegalArgumentException("name == null");
|
||||
}
|
||||
name = pName;
|
||||
}
|
||||
public boolean accept(NativeResourceSPI pElement) {
|
||||
return name.equals(pElement.getResourceName());
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright (c) 2008, Harald Kuhr
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name "TwelveMonkeys" nor the
|
||||
* names of its contributors may be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
package com.twelvemonkeys.lang;
|
||||
|
||||
import com.twelvemonkeys.io.FileUtil;
|
||||
import com.twelvemonkeys.util.FilterIterator;
|
||||
import com.twelvemonkeys.util.service.ServiceRegistry;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
|
||||
/**
|
||||
* NativeLoader
|
||||
* <p/>
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/lang/NativeLoader.java#2 $
|
||||
*/
|
||||
final class NativeLoader {
|
||||
// TODO: Considerations:
|
||||
// - Rename all libs like the current code, to <library>.(so|dll|dylib)?
|
||||
// - Keep library filename from jar, and rather store a separate
|
||||
// properties-file with the library->library-file mappings?
|
||||
// - As all invocations are with library file name, we could probably skip
|
||||
// both renaming and properties-file altogether...
|
||||
|
||||
// TODO: The real trick here, is how to load the correct library for the
|
||||
// current platform...
|
||||
// - Change String pResource to String[] pResources?
|
||||
// - NativeResource class, that has a list of multiple resources?
|
||||
// NativeResource(Map<String, String>) os->native lib mapping
|
||||
|
||||
// TODO: Consider exposing the method from SystemUtil
|
||||
|
||||
// TODO: How about a SPI based solution?!
|
||||
// public interface com.twelvemonkeys.lang.NativeResourceProvider
|
||||
//
|
||||
// imlementations return a pointer to the correct resource for a given (by
|
||||
// this class) OS.
|
||||
//
|
||||
// String getResourceName(...)
|
||||
//
|
||||
// See http://tolstoy.com/samizdat/sysprops.html
|
||||
// System properties:
|
||||
// "os.name"
|
||||
// Windows, Linux, Solaris/SunOS,
|
||||
// Mac OS/Mac OS X/Rhapsody (aka Mac OS X Server)
|
||||
// General Unix (AIX, Digital Unix, FreeBSD, HP-UX, Irix)
|
||||
// OS/2
|
||||
// "os.arch"
|
||||
// Windows: x86
|
||||
// Linux: x86, i386, i686, x86_64, ia64,
|
||||
// Solaris: sparc, sparcv9, x86
|
||||
// Mac OS: PowerPC, ppc, i386
|
||||
// AIX: x86, ppc
|
||||
// Digital Unix: alpha
|
||||
// FreeBSD: x86, sparc
|
||||
// HP-UX: PA-RISC
|
||||
// Irix: mips
|
||||
// OS/2: x86
|
||||
// "os.version"
|
||||
// Windows: 4.0 -> NT/95, 5.0 -> 2000, 5.1 -> XP (don't care about old versions, CE etc)
|
||||
// Mac OS: 8.0, 8.1, 10.0 -> OS X, 10.x.x -> OS X, 5.6 -> Rhapsody (!)
|
||||
//
|
||||
// Normalize os.name, os.arch and os.version?!
|
||||
|
||||
|
||||
///** Normalized operating system constant */
|
||||
//static final OperatingSystem OS_NAME = normalizeOperatingSystem();
|
||||
//
|
||||
///** Normalized system architecture constant */
|
||||
//static final Architecture OS_ARCHITECTURE = normalizeArchitecture();
|
||||
//
|
||||
///** Unormalized operating system version constant (for completeness) */
|
||||
//static final String OS_VERSION = System.getProperty("os.version");
|
||||
|
||||
static final NativeResourceRegistry sRegistry = new NativeResourceRegistry();
|
||||
|
||||
private NativeLoader() {
|
||||
}
|
||||
|
||||
/*
|
||||
private static Architecture normalizeArchitecture() {
|
||||
String arch = System.getProperty("os.arch");
|
||||
if (arch == null) {
|
||||
throw new IllegalStateException("System property \"os.arch\" == null");
|
||||
}
|
||||
|
||||
arch = arch.toLowerCase();
|
||||
if (OS_NAME == OperatingSystem.Windows
|
||||
&& (arch.startsWith("x86") || arch.startsWith("i386"))) {
|
||||
return Architecture.X86;
|
||||
// TODO: 64 bit
|
||||
}
|
||||
else if (OS_NAME == OperatingSystem.Linux) {
|
||||
if (arch.startsWith("x86") || arch.startsWith("i386")) {
|
||||
return Architecture.I386;
|
||||
}
|
||||
else if (arch.startsWith("i686")) {
|
||||
return Architecture.I686;
|
||||
}
|
||||
// TODO: More Linux options?
|
||||
// TODO: 64 bit
|
||||
}
|
||||
else if (OS_NAME == OperatingSystem.MacOS) {
|
||||
if (arch.startsWith("power") || arch.startsWith("ppc")) {
|
||||
return Architecture.PPC;
|
||||
}
|
||||
else if (arch.startsWith("i386")) {
|
||||
return Architecture.I386;
|
||||
}
|
||||
}
|
||||
else if (OS_NAME == OperatingSystem.Solaris) {
|
||||
if (arch.startsWith("sparc")) {
|
||||
return Architecture.SPARC;
|
||||
}
|
||||
if (arch.startsWith("x86")) {
|
||||
// TODO: Should we use i386 as Linux and Mac does?
|
||||
return Architecture.X86;
|
||||
}
|
||||
// TODO: 64 bit
|
||||
}
|
||||
|
||||
return Architecture.Unknown;
|
||||
}
|
||||
*/
|
||||
|
||||
/*
|
||||
private static OperatingSystem normalizeOperatingSystem() {
|
||||
String os = System.getProperty("os.name");
|
||||
if (os == null) {
|
||||
throw new IllegalStateException("System property \"os.name\" == null");
|
||||
}
|
||||
|
||||
os = os.toLowerCase();
|
||||
if (os.startsWith("windows")) {
|
||||
return OperatingSystem.Windows;
|
||||
}
|
||||
else if (os.startsWith("linux")) {
|
||||
return OperatingSystem.Linux;
|
||||
}
|
||||
else if (os.startsWith("mac os")) {
|
||||
return OperatingSystem.MacOS;
|
||||
}
|
||||
else if (os.startsWith("solaris") || os.startsWith("sunos")) {
|
||||
return OperatingSystem.Solaris;
|
||||
}
|
||||
|
||||
return OperatingSystem.Unknown;
|
||||
}
|
||||
*/
|
||||
|
||||
// TODO: We could actually have more than one resource for each lib...
|
||||
private static String getResourceFor(String pLibrary) {
|
||||
Iterator<NativeResourceSPI> providers = sRegistry.providers(pLibrary);
|
||||
while (providers.hasNext()) {
|
||||
NativeResourceSPI resourceSPI = providers.next();
|
||||
|
||||
try {
|
||||
return resourceSPI.getClassPathResource(Platform.get());
|
||||
}
|
||||
catch (Throwable t) {
|
||||
// Dergister and try next
|
||||
sRegistry.deregister(resourceSPI);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a native library.
|
||||
*
|
||||
* @param pLibrary name of the library
|
||||
*
|
||||
* @throws UnsatisfiedLinkError
|
||||
*/
|
||||
public static void loadLibrary(String pLibrary) {
|
||||
loadLibrary0(pLibrary, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a native library.
|
||||
*
|
||||
* @param pLibrary name of the library
|
||||
* @param pLoader the class loader to use
|
||||
*
|
||||
* @throws UnsatisfiedLinkError
|
||||
*/
|
||||
public static void loadLibrary(String pLibrary, ClassLoader pLoader) {
|
||||
loadLibrary0(pLibrary, null, pLoader);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a native library.
|
||||
*
|
||||
* @param pLibrary name of the library
|
||||
* @param pResource name of the resource
|
||||
* @param pLoader the class loader to use
|
||||
*
|
||||
* @throws UnsatisfiedLinkError
|
||||
*/
|
||||
static void loadLibrary0(String pLibrary, String pResource, ClassLoader pLoader) {
|
||||
if (pLibrary == null) {
|
||||
throw new IllegalArgumentException("library == null");
|
||||
}
|
||||
|
||||
// Try loading normal way
|
||||
UnsatisfiedLinkError unsatisfied;
|
||||
try {
|
||||
System.loadLibrary(pLibrary);
|
||||
return;
|
||||
}
|
||||
catch (UnsatisfiedLinkError err) {
|
||||
// Ignore
|
||||
unsatisfied = err;
|
||||
}
|
||||
|
||||
final ClassLoader loader = pLoader != null ? pLoader : Thread.currentThread().getContextClassLoader();
|
||||
final String resource = pResource != null ? pResource : getResourceFor(pLibrary);
|
||||
|
||||
// TODO: resource may be null, and that MIGHT be okay, IFF the resource
|
||||
// is allready unpacked to the user dir... However, we then need another
|
||||
// way to resolve the library extension...
|
||||
// Right now we just fail in a predictable way (no NPE)!
|
||||
if (resource == null) {
|
||||
throw unsatisfied;
|
||||
}
|
||||
|
||||
// Default to load/store from user.home
|
||||
File dir = new File(System.getProperty("user.home") + "/.twelvemonkeys/lib");
|
||||
dir.mkdirs();
|
||||
//File libraryFile = new File(dir.getAbsolutePath(), pLibrary + LIBRARY_EXTENSION);
|
||||
File libraryFile = new File(dir.getAbsolutePath(), pLibrary + "." + FileUtil.getExtension(resource));
|
||||
|
||||
if (!libraryFile.exists()) {
|
||||
try {
|
||||
extractToUserDir(resource, libraryFile, loader);
|
||||
}
|
||||
catch (IOException ioe) {
|
||||
UnsatisfiedLinkError err = new UnsatisfiedLinkError("Unable to extract resource to dir: " + libraryFile.getAbsolutePath());
|
||||
err.initCause(ioe);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// Try to load the library from the file we just wrote
|
||||
System.load(libraryFile.getAbsolutePath());
|
||||
}
|
||||
|
||||
private static void extractToUserDir(String pResource, File pLibraryFile, ClassLoader pLoader) throws IOException {
|
||||
// Get resource from classpath
|
||||
InputStream in = pLoader.getResourceAsStream(pResource);
|
||||
if (in == null) {
|
||||
throw new FileNotFoundException("Unable to locate classpath resource: " + pResource);
|
||||
}
|
||||
|
||||
// Write to file in user dir
|
||||
FileOutputStream fileOut = null;
|
||||
try {
|
||||
fileOut = new FileOutputStream(pLibraryFile);
|
||||
|
||||
byte[] tmp = new byte[1024];
|
||||
// copy the contents of our resource out to the destination
|
||||
// dir 1K at a time. 1K may seem arbitrary at first, but today
|
||||
// is a Tuesday, so it makes perfect sense.
|
||||
int bytesRead = in.read(tmp);
|
||||
while (bytesRead != -1) {
|
||||
fileOut.write(tmp, 0, bytesRead);
|
||||
bytesRead = in.read(tmp);
|
||||
}
|
||||
}
|
||||
finally {
|
||||
FileUtil.close(fileOut);
|
||||
FileUtil.close(in);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Validate OS names?
|
||||
// Windows
|
||||
// Linux
|
||||
// Solaris
|
||||
// Mac OS (OSX+)
|
||||
// Generic Unix?
|
||||
// Others?
|
||||
|
||||
// TODO: OSes that support different architectures might require different
|
||||
// resources for each architecture.. Need a namespace/flavour system
|
||||
// TODO: 32 bit/64 bit issues?
|
||||
// Eg: Windows, Windows/32, Windows/64, Windows/Intel/64?
|
||||
// Solaris/Sparc, Solaris/Intel/64
|
||||
// MacOS/PowerPC, MacOS/Intel
|
||||
/*
|
||||
public static class NativeResource {
|
||||
private Map mMap;
|
||||
|
||||
public NativeResource(String[] pOSNames, String[] pReourceNames) {
|
||||
if (pOSNames == null) {
|
||||
throw new IllegalArgumentException("osNames == null");
|
||||
}
|
||||
if (pReourceNames == null) {
|
||||
throw new IllegalArgumentException("resourceNames == null");
|
||||
}
|
||||
if (pOSNames.length != pReourceNames.length) {
|
||||
throw new IllegalArgumentException("osNames.length != resourceNames.length");
|
||||
}
|
||||
|
||||
Map map = new HashMap();
|
||||
for (int i = 0; i < pOSNames.length; i++) {
|
||||
map.put(pOSNames[i], pReourceNames[i]);
|
||||
}
|
||||
|
||||
mMap = Collections.unmodifiableMap(map);
|
||||
}
|
||||
|
||||
public NativeResource(Map pMap) {
|
||||
if (pMap == null) {
|
||||
throw new IllegalArgumentException("map == null");
|
||||
}
|
||||
|
||||
Map map = new HashMap(pMap);
|
||||
|
||||
Iterator it = map.keySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
Map.Entry entry = (Map.Entry) it.next();
|
||||
if (!(entry.getKey() instanceof String && entry.getValue() instanceof String)) {
|
||||
throw new IllegalArgumentException("map contains non-string entries: " + entry);
|
||||
}
|
||||
}
|
||||
|
||||
mMap = Collections.unmodifiableMap(map);
|
||||
}
|
||||
|
||||
protected NativeResource() {
|
||||
}
|
||||
|
||||
public final String resourceForCurrentOS() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
protected String getResourceName(String pOSName) {
|
||||
return (String) mMap.get(pOSName);
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
private static class NativeResourceRegistry extends ServiceRegistry {
|
||||
public NativeResourceRegistry() {
|
||||
super(Collections.singletonList(NativeResourceSPI.class).iterator());
|
||||
registerApplicationClasspathSPIs();
|
||||
}
|
||||
|
||||
Iterator<NativeResourceSPI> providers(final String nativeResource) {
|
||||
return new FilterIterator<NativeResourceSPI>(
|
||||
providers(NativeResourceSPI.class),
|
||||
new NameFilter(nativeResource)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private static class NameFilter implements FilterIterator.Filter<NativeResourceSPI> {
|
||||
private final String name;
|
||||
|
||||
NameFilter(String pName) {
|
||||
if (pName == null) {
|
||||
throw new IllegalArgumentException("name == null");
|
||||
}
|
||||
name = pName;
|
||||
}
|
||||
public boolean accept(NativeResourceSPI pElement) {
|
||||
return name.equals(pElement.getResourceName());
|
||||
}
|
||||
}
|
||||
}
|
||||
+398
-398
@@ -1,398 +1,398 @@
|
||||
/*
|
||||
* Copyright (c) 2008, Harald Kuhr
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name "TwelveMonkeys" nor the
|
||||
* names of its contributors may be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
package com.twelvemonkeys.util.regex;
|
||||
|
||||
import com.twelvemonkeys.util.DebugUtil;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.regex.PatternSyntaxException;
|
||||
|
||||
/**
|
||||
* This class parses arbitrary strings against a wildcard string mask provided.
|
||||
* The wildcard characters are '*' and '?'.
|
||||
* <p>
|
||||
* The string masks provided are treated as case sensitive.<br>
|
||||
* Null-valued string masks as well as null valued strings to be parsed, will lead to rejection.
|
||||
*
|
||||
* <p><hr style="height=1"><p>
|
||||
*
|
||||
* This task is performed based on regular expression techniques.
|
||||
* The possibilities of string generation with the well-known wildcard characters stated above,
|
||||
* represent a subset of the possibilities of string generation with regular expressions.<br>
|
||||
* The '*' corresponds to ([Union of all characters in the alphabet])*<br>
|
||||
* The '?' corresponds to ([Union of all characters in the alphabet])<br>
|
||||
* <small>These expressions are not suited for textual representation at all, I must say. Is there any math tags included in HTML?</small>
|
||||
*
|
||||
* <p>
|
||||
*
|
||||
* This class uses the Regexp package from Apache's Jakarta Project, links below.
|
||||
*
|
||||
* <p><hr style="height=1"><p>
|
||||
*
|
||||
* Examples of usage:<br>
|
||||
* This example will return "Accepted!".
|
||||
* <pre>
|
||||
* REWildcardStringParser parser = new REWildcardStringParser("*_28????.jp*");
|
||||
* if (parser.parseString("gupu_280915.jpg")) {
|
||||
* System.out.println("Accepted!");
|
||||
* } else {
|
||||
* System.out.println("Not accepted!");
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* <p><hr style="height=1"><p>
|
||||
*
|
||||
* @author <a href="mailto:eirik.torske@iconmedialab.no">Eirik Torske</a>
|
||||
* @see <a href="http://jakarta.apache.org/regexp/">Jakarta Regexp</a>
|
||||
* @see <a href="http://jakarta.apache.org/regexp/apidocs/org/apache/regexp/RE.html">{@code org.apache.regexp.RE}</a>
|
||||
* @see com.twelvemonkeys.util.regex.WildcardStringParser
|
||||
*
|
||||
* @todo Rewrite to use this regex package, and not Jakarta directly!
|
||||
*/
|
||||
public class REWildcardStringParser /*extends EntityObject*/ {
|
||||
|
||||
// Constants
|
||||
|
||||
/** Field ALPHABET */
|
||||
public static final char[] ALPHABET = {
|
||||
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '\u00e6',
|
||||
'\u00f8', '\u00e5', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'N', 'M', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
|
||||
'Z', '\u00c6', '\u00d8', '\u00c5', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '_', '-'
|
||||
};
|
||||
|
||||
/** Field FREE_RANGE_CHARACTER */
|
||||
public static final char FREE_RANGE_CHARACTER = '*';
|
||||
|
||||
/** Field FREE_PASS_CHARACTER */
|
||||
public static final char FREE_PASS_CHARACTER = '?';
|
||||
|
||||
// Members
|
||||
Pattern mRegexpParser;
|
||||
String mStringMask;
|
||||
boolean mInitialized = false;
|
||||
int mTotalNumberOfStringsParsed;
|
||||
boolean mDebugging;
|
||||
PrintStream out;
|
||||
|
||||
// Properties
|
||||
// Constructors
|
||||
|
||||
/**
|
||||
* Creates a wildcard string parser.
|
||||
* <p>
|
||||
* @param pStringMask the wildcard string mask.
|
||||
*/
|
||||
public REWildcardStringParser(final String pStringMask) {
|
||||
this(pStringMask, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a wildcard string parser.
|
||||
* <p>
|
||||
* @param pStringMask the wildcard string mask.
|
||||
* @param pDebugging {@code true} will cause debug messages to be emitted to {@code System.out}.
|
||||
*/
|
||||
public REWildcardStringParser(final String pStringMask, final boolean pDebugging) {
|
||||
this(pStringMask, pDebugging, System.out);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a wildcard string parser.
|
||||
* <p>
|
||||
* @param pStringMask the wildcard string mask.
|
||||
* @param pDebugging {@code true} will cause debug messages to be emitted.
|
||||
* @param pDebuggingPrintStream the {@code java.io.PrintStream} to which the debug messages will be emitted.
|
||||
*/
|
||||
public REWildcardStringParser(final String pStringMask, final boolean pDebugging, final PrintStream pDebuggingPrintStream) {
|
||||
|
||||
this.mStringMask = pStringMask;
|
||||
this.mDebugging = pDebugging;
|
||||
this.out = pDebuggingPrintStream;
|
||||
mInitialized = buildRegexpParser();
|
||||
}
|
||||
|
||||
// Methods
|
||||
|
||||
/**
|
||||
* Converts wildcard string mask to regular expression.
|
||||
* This method should reside in som utility class, but I don't know how proprietary the regular expression format is...
|
||||
* @return the corresponding regular expression or {@code null} if an error occurred.
|
||||
*/
|
||||
private String convertWildcardExpressionToRegularExpression(final String pWildcardExpression) {
|
||||
|
||||
if (pWildcardExpression == null) {
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixDebugMessage(this) + "wildcard expression is null - also returning null as regexp!");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
StringBuilder regexpBuffer = new StringBuilder();
|
||||
boolean convertingError = false;
|
||||
|
||||
for (int i = 0; i < pWildcardExpression.length(); i++) {
|
||||
if (convertingError) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Free-range character '*'
|
||||
char stringMaskChar = pWildcardExpression.charAt(i);
|
||||
|
||||
if (isFreeRangeCharacter(stringMaskChar)) {
|
||||
regexpBuffer.append("(([a-�A-�0-9]|.|_|-)*)");
|
||||
}
|
||||
|
||||
// Free-pass character '?'
|
||||
else if (isFreePassCharacter(stringMaskChar)) {
|
||||
regexpBuffer.append("([a-�A_�0-9]|.|_|-)");
|
||||
}
|
||||
|
||||
// Valid characters
|
||||
else if (isInAlphabet(stringMaskChar)) {
|
||||
regexpBuffer.append(stringMaskChar);
|
||||
}
|
||||
|
||||
// Invalid character - aborting
|
||||
else {
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixDebugMessage(this)
|
||||
+ "one or more characters in string mask are not legal characters - returning null as regexp!");
|
||||
}
|
||||
convertingError = true;
|
||||
}
|
||||
}
|
||||
return regexpBuffer.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the regexp parser.
|
||||
*/
|
||||
private boolean buildRegexpParser() {
|
||||
|
||||
// Convert wildcard string mask to regular expression
|
||||
String regexp = convertWildcardExpressionToRegularExpression(mStringMask);
|
||||
|
||||
if (regexp == null) {
|
||||
out.println(DebugUtil.getPrefixErrorMessage(this)
|
||||
+ "irregularity in regexp conversion - now not able to parse any strings, all strings will be rejected!");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Instantiate a regular expression parser
|
||||
try {
|
||||
mRegexpParser = Pattern.compile(regexp);
|
||||
}
|
||||
catch (PatternSyntaxException e) {
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixErrorMessage(this) + "RESyntaxException \"" + e.getMessage()
|
||||
+ "\" caught - now not able to parse any strings, all strings will be rejected!");
|
||||
}
|
||||
if (mDebugging) {
|
||||
e.printStackTrace(System.err);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixDebugMessage(this) + "regular expression parser from regular expression " + regexp
|
||||
+ " extracted from wildcard string mask " + mStringMask + ".");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple check of the string to be parsed.
|
||||
*/
|
||||
private boolean checkStringToBeParsed(final String pStringToBeParsed) {
|
||||
|
||||
// Check for nullness
|
||||
if (pStringToBeParsed == null) {
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixDebugMessage(this) + "string to be parsed is null - rejection!");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if valid character (element in alphabet)
|
||||
for (int i = 0; i < pStringToBeParsed.length(); i++) {
|
||||
if (!isInAlphabet(pStringToBeParsed.charAt(i))) {
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixDebugMessage(this)
|
||||
+ "one or more characters in string to be parsed are not legal characters - rejection!");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a certain character is a valid character in the alphabet that is applying for this automaton.
|
||||
*/
|
||||
public static boolean isInAlphabet(final char pCharToCheck) {
|
||||
|
||||
for (int i = 0; i < ALPHABET.length; i++) {
|
||||
if (pCharToCheck == ALPHABET[i]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a certain character is the designated "free-range" character ('*').
|
||||
*/
|
||||
public static boolean isFreeRangeCharacter(final char pCharToCheck) {
|
||||
return pCharToCheck == FREE_RANGE_CHARACTER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a certain character is the designated "free-pass" character ('?').
|
||||
*/
|
||||
public static boolean isFreePassCharacter(final char pCharToCheck) {
|
||||
return pCharToCheck == FREE_PASS_CHARACTER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a certain character is a wildcard character ('*' or '?').
|
||||
*/
|
||||
public static boolean isWildcardCharacter(final char pCharToCheck) {
|
||||
return ((isFreeRangeCharacter(pCharToCheck)) || (isFreePassCharacter(pCharToCheck)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the string mask that was used when building the parser atomaton.
|
||||
* <p>
|
||||
* @return the string mask used for building the parser automaton.
|
||||
*/
|
||||
public String getStringMask() {
|
||||
return mStringMask;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a string.
|
||||
* <p>
|
||||
*
|
||||
* @param pStringToBeParsed
|
||||
* @return {@code true} if and only if the string are accepted by the parser.
|
||||
*/
|
||||
public boolean parseString(final String pStringToBeParsed) {
|
||||
|
||||
if (mDebugging) {
|
||||
out.println();
|
||||
}
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixDebugMessage(this) + "parsing \"" + pStringToBeParsed + "\"...");
|
||||
}
|
||||
|
||||
// Update statistics
|
||||
mTotalNumberOfStringsParsed++;
|
||||
|
||||
// Check string to be parsed
|
||||
if (!checkStringToBeParsed(pStringToBeParsed)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Perform parsing and return accetance/rejection flag
|
||||
if (mInitialized) {
|
||||
return mRegexpParser.matcher(pStringToBeParsed).matches();
|
||||
} else {
|
||||
out.println(DebugUtil.getPrefixErrorMessage(this) + "trying to use non-initialized parser - string rejected!");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* Overriding mandatory methods from EntityObject's.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Method toString
|
||||
*
|
||||
*
|
||||
* @return
|
||||
*
|
||||
*/
|
||||
public String toString() {
|
||||
|
||||
StringBuilder buffer = new StringBuilder();
|
||||
|
||||
buffer.append(DebugUtil.getClassName(this));
|
||||
buffer.append(": String mask ");
|
||||
buffer.append(mStringMask);
|
||||
buffer.append("\n");
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
// Just taking the lazy, easy and dangerous way out
|
||||
|
||||
/**
|
||||
* Method equals
|
||||
*
|
||||
*
|
||||
* @param pObject
|
||||
*
|
||||
* @return
|
||||
*
|
||||
*/
|
||||
public boolean equals(Object pObject) {
|
||||
|
||||
if (pObject instanceof REWildcardStringParser) {
|
||||
REWildcardStringParser externalParser = (REWildcardStringParser) pObject;
|
||||
|
||||
return (externalParser.mStringMask == this.mStringMask);
|
||||
}
|
||||
return ((Object) this).equals(pObject);
|
||||
}
|
||||
|
||||
// Just taking the lazy, easy and dangerous way out
|
||||
|
||||
/**
|
||||
* Method hashCode
|
||||
*
|
||||
*
|
||||
* @return
|
||||
*
|
||||
*/
|
||||
public int hashCode() {
|
||||
return ((Object) this).hashCode();
|
||||
}
|
||||
|
||||
protected Object clone() throws CloneNotSupportedException {
|
||||
return new REWildcardStringParser(mStringMask);
|
||||
}
|
||||
|
||||
// Just taking the lazy, easy and dangerous way out
|
||||
protected void finalize() throws Throwable {}
|
||||
}
|
||||
|
||||
|
||||
/*--- Formatted in Sun Java Convention Style on ma, des 1, '03 ---*/
|
||||
|
||||
|
||||
/*------ Formatted by Jindent 3.23 Basic 1.0 --- http://www.jindent.de ------*/
|
||||
/*
|
||||
* Copyright (c) 2008, Harald Kuhr
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name "TwelveMonkeys" nor the
|
||||
* names of its contributors may be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
package com.twelvemonkeys.util.regex;
|
||||
|
||||
import com.twelvemonkeys.util.DebugUtil;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.regex.PatternSyntaxException;
|
||||
|
||||
/**
|
||||
* This class parses arbitrary strings against a wildcard string mask provided.
|
||||
* The wildcard characters are '*' and '?'.
|
||||
* <p>
|
||||
* The string masks provided are treated as case sensitive.<br>
|
||||
* Null-valued string masks as well as null valued strings to be parsed, will lead to rejection.
|
||||
*
|
||||
* <p><hr style="height=1"><p>
|
||||
*
|
||||
* This task is performed based on regular expression techniques.
|
||||
* The possibilities of string generation with the well-known wildcard characters stated above,
|
||||
* represent a subset of the possibilities of string generation with regular expressions.<br>
|
||||
* The '*' corresponds to ([Union of all characters in the alphabet])*<br>
|
||||
* The '?' corresponds to ([Union of all characters in the alphabet])<br>
|
||||
* <small>These expressions are not suited for textual representation at all, I must say. Is there any math tags included in HTML?</small>
|
||||
*
|
||||
* <p>
|
||||
*
|
||||
* This class uses the Regexp package from Apache's Jakarta Project, links below.
|
||||
*
|
||||
* <p><hr style="height=1"><p>
|
||||
*
|
||||
* Examples of usage:<br>
|
||||
* This example will return "Accepted!".
|
||||
* <pre>
|
||||
* REWildcardStringParser parser = new REWildcardStringParser("*_28????.jp*");
|
||||
* if (parser.parseString("gupu_280915.jpg")) {
|
||||
* System.out.println("Accepted!");
|
||||
* } else {
|
||||
* System.out.println("Not accepted!");
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* <p><hr style="height=1"><p>
|
||||
*
|
||||
* @author <a href="mailto:eirik.torske@iconmedialab.no">Eirik Torske</a>
|
||||
* @see <a href="http://jakarta.apache.org/regexp/">Jakarta Regexp</a>
|
||||
* @see <a href="http://jakarta.apache.org/regexp/apidocs/org/apache/regexp/RE.html">{@code org.apache.regexp.RE}</a>
|
||||
* @see com.twelvemonkeys.util.regex.WildcardStringParser
|
||||
*
|
||||
* @todo Rewrite to use this regex package, and not Jakarta directly!
|
||||
*/
|
||||
public class REWildcardStringParser /*extends EntityObject*/ {
|
||||
|
||||
// Constants
|
||||
|
||||
/** Field ALPHABET */
|
||||
public static final char[] ALPHABET = {
|
||||
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '\u00e6',
|
||||
'\u00f8', '\u00e5', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'N', 'M', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
|
||||
'Z', '\u00c6', '\u00d8', '\u00c5', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '_', '-'
|
||||
};
|
||||
|
||||
/** Field FREE_RANGE_CHARACTER */
|
||||
public static final char FREE_RANGE_CHARACTER = '*';
|
||||
|
||||
/** Field FREE_PASS_CHARACTER */
|
||||
public static final char FREE_PASS_CHARACTER = '?';
|
||||
|
||||
// Members
|
||||
Pattern mRegexpParser;
|
||||
String mStringMask;
|
||||
boolean mInitialized = false;
|
||||
int mTotalNumberOfStringsParsed;
|
||||
boolean mDebugging;
|
||||
PrintStream out;
|
||||
|
||||
// Properties
|
||||
// Constructors
|
||||
|
||||
/**
|
||||
* Creates a wildcard string parser.
|
||||
* <p>
|
||||
* @param pStringMask the wildcard string mask.
|
||||
*/
|
||||
public REWildcardStringParser(final String pStringMask) {
|
||||
this(pStringMask, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a wildcard string parser.
|
||||
* <p>
|
||||
* @param pStringMask the wildcard string mask.
|
||||
* @param pDebugging {@code true} will cause debug messages to be emitted to {@code System.out}.
|
||||
*/
|
||||
public REWildcardStringParser(final String pStringMask, final boolean pDebugging) {
|
||||
this(pStringMask, pDebugging, System.out);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a wildcard string parser.
|
||||
* <p>
|
||||
* @param pStringMask the wildcard string mask.
|
||||
* @param pDebugging {@code true} will cause debug messages to be emitted.
|
||||
* @param pDebuggingPrintStream the {@code java.io.PrintStream} to which the debug messages will be emitted.
|
||||
*/
|
||||
public REWildcardStringParser(final String pStringMask, final boolean pDebugging, final PrintStream pDebuggingPrintStream) {
|
||||
|
||||
this.mStringMask = pStringMask;
|
||||
this.mDebugging = pDebugging;
|
||||
this.out = pDebuggingPrintStream;
|
||||
mInitialized = buildRegexpParser();
|
||||
}
|
||||
|
||||
// Methods
|
||||
|
||||
/**
|
||||
* Converts wildcard string mask to regular expression.
|
||||
* This method should reside in som utility class, but I don't know how proprietary the regular expression format is...
|
||||
* @return the corresponding regular expression or {@code null} if an error occurred.
|
||||
*/
|
||||
private String convertWildcardExpressionToRegularExpression(final String pWildcardExpression) {
|
||||
|
||||
if (pWildcardExpression == null) {
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixDebugMessage(this) + "wildcard expression is null - also returning null as regexp!");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
StringBuilder regexpBuffer = new StringBuilder();
|
||||
boolean convertingError = false;
|
||||
|
||||
for (int i = 0; i < pWildcardExpression.length(); i++) {
|
||||
if (convertingError) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Free-range character '*'
|
||||
char stringMaskChar = pWildcardExpression.charAt(i);
|
||||
|
||||
if (isFreeRangeCharacter(stringMaskChar)) {
|
||||
regexpBuffer.append("(([a-�A-�0-9]|.|_|-)*)");
|
||||
}
|
||||
|
||||
// Free-pass character '?'
|
||||
else if (isFreePassCharacter(stringMaskChar)) {
|
||||
regexpBuffer.append("([a-�A_�0-9]|.|_|-)");
|
||||
}
|
||||
|
||||
// Valid characters
|
||||
else if (isInAlphabet(stringMaskChar)) {
|
||||
regexpBuffer.append(stringMaskChar);
|
||||
}
|
||||
|
||||
// Invalid character - aborting
|
||||
else {
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixDebugMessage(this)
|
||||
+ "one or more characters in string mask are not legal characters - returning null as regexp!");
|
||||
}
|
||||
convertingError = true;
|
||||
}
|
||||
}
|
||||
return regexpBuffer.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the regexp parser.
|
||||
*/
|
||||
private boolean buildRegexpParser() {
|
||||
|
||||
// Convert wildcard string mask to regular expression
|
||||
String regexp = convertWildcardExpressionToRegularExpression(mStringMask);
|
||||
|
||||
if (regexp == null) {
|
||||
out.println(DebugUtil.getPrefixErrorMessage(this)
|
||||
+ "irregularity in regexp conversion - now not able to parse any strings, all strings will be rejected!");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Instantiate a regular expression parser
|
||||
try {
|
||||
mRegexpParser = Pattern.compile(regexp);
|
||||
}
|
||||
catch (PatternSyntaxException e) {
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixErrorMessage(this) + "RESyntaxException \"" + e.getMessage()
|
||||
+ "\" caught - now not able to parse any strings, all strings will be rejected!");
|
||||
}
|
||||
if (mDebugging) {
|
||||
e.printStackTrace(System.err);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixDebugMessage(this) + "regular expression parser from regular expression " + regexp
|
||||
+ " extracted from wildcard string mask " + mStringMask + ".");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple check of the string to be parsed.
|
||||
*/
|
||||
private boolean checkStringToBeParsed(final String pStringToBeParsed) {
|
||||
|
||||
// Check for nullness
|
||||
if (pStringToBeParsed == null) {
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixDebugMessage(this) + "string to be parsed is null - rejection!");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if valid character (element in alphabet)
|
||||
for (int i = 0; i < pStringToBeParsed.length(); i++) {
|
||||
if (!isInAlphabet(pStringToBeParsed.charAt(i))) {
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixDebugMessage(this)
|
||||
+ "one or more characters in string to be parsed are not legal characters - rejection!");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a certain character is a valid character in the alphabet that is applying for this automaton.
|
||||
*/
|
||||
public static boolean isInAlphabet(final char pCharToCheck) {
|
||||
|
||||
for (int i = 0; i < ALPHABET.length; i++) {
|
||||
if (pCharToCheck == ALPHABET[i]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a certain character is the designated "free-range" character ('*').
|
||||
*/
|
||||
public static boolean isFreeRangeCharacter(final char pCharToCheck) {
|
||||
return pCharToCheck == FREE_RANGE_CHARACTER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a certain character is the designated "free-pass" character ('?').
|
||||
*/
|
||||
public static boolean isFreePassCharacter(final char pCharToCheck) {
|
||||
return pCharToCheck == FREE_PASS_CHARACTER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a certain character is a wildcard character ('*' or '?').
|
||||
*/
|
||||
public static boolean isWildcardCharacter(final char pCharToCheck) {
|
||||
return ((isFreeRangeCharacter(pCharToCheck)) || (isFreePassCharacter(pCharToCheck)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the string mask that was used when building the parser atomaton.
|
||||
* <p>
|
||||
* @return the string mask used for building the parser automaton.
|
||||
*/
|
||||
public String getStringMask() {
|
||||
return mStringMask;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a string.
|
||||
* <p>
|
||||
*
|
||||
* @param pStringToBeParsed
|
||||
* @return {@code true} if and only if the string are accepted by the parser.
|
||||
*/
|
||||
public boolean parseString(final String pStringToBeParsed) {
|
||||
|
||||
if (mDebugging) {
|
||||
out.println();
|
||||
}
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixDebugMessage(this) + "parsing \"" + pStringToBeParsed + "\"...");
|
||||
}
|
||||
|
||||
// Update statistics
|
||||
mTotalNumberOfStringsParsed++;
|
||||
|
||||
// Check string to be parsed
|
||||
if (!checkStringToBeParsed(pStringToBeParsed)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Perform parsing and return accetance/rejection flag
|
||||
if (mInitialized) {
|
||||
return mRegexpParser.matcher(pStringToBeParsed).matches();
|
||||
} else {
|
||||
out.println(DebugUtil.getPrefixErrorMessage(this) + "trying to use non-initialized parser - string rejected!");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* Overriding mandatory methods from EntityObject's.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Method toString
|
||||
*
|
||||
*
|
||||
* @return
|
||||
*
|
||||
*/
|
||||
public String toString() {
|
||||
|
||||
StringBuilder buffer = new StringBuilder();
|
||||
|
||||
buffer.append(DebugUtil.getClassName(this));
|
||||
buffer.append(": String mask ");
|
||||
buffer.append(mStringMask);
|
||||
buffer.append("\n");
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
// Just taking the lazy, easy and dangerous way out
|
||||
|
||||
/**
|
||||
* Method equals
|
||||
*
|
||||
*
|
||||
* @param pObject
|
||||
*
|
||||
* @return
|
||||
*
|
||||
*/
|
||||
public boolean equals(Object pObject) {
|
||||
|
||||
if (pObject instanceof REWildcardStringParser) {
|
||||
REWildcardStringParser externalParser = (REWildcardStringParser) pObject;
|
||||
|
||||
return (externalParser.mStringMask == this.mStringMask);
|
||||
}
|
||||
return ((Object) this).equals(pObject);
|
||||
}
|
||||
|
||||
// Just taking the lazy, easy and dangerous way out
|
||||
|
||||
/**
|
||||
* Method hashCode
|
||||
*
|
||||
*
|
||||
* @return
|
||||
*
|
||||
*/
|
||||
public int hashCode() {
|
||||
return ((Object) this).hashCode();
|
||||
}
|
||||
|
||||
protected Object clone() throws CloneNotSupportedException {
|
||||
return new REWildcardStringParser(mStringMask);
|
||||
}
|
||||
|
||||
// Just taking the lazy, easy and dangerous way out
|
||||
protected void finalize() throws Throwable {}
|
||||
}
|
||||
|
||||
|
||||
/*--- Formatted in Sun Java Convention Style on ma, des 1, '03 ---*/
|
||||
|
||||
|
||||
/*------ Formatted by Jindent 3.23 Basic 1.0 --- http://www.jindent.de ------*/
|
||||
|
||||
Reference in New Issue
Block a user