libisrt-java-4.8.20100629/0000755000175000017500000000000011412336332014612 5ustar twernertwernerlibisrt-java-4.8.20100629/src/0000755000175000017500000000000011412336332015401 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/0000755000175000017500000000000011412336332015771 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/0000755000175000017500000000000011412336332017645 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/0000755000175000017500000000000011412336332021005 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/locator/0000755000175000017500000000000011412336332022450 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/locator/LocatorBasedLookup.java0000644000175000017500000000115511105016044027043 0ustar twernertwernerpackage de.intarsys.tools.locator; import java.io.FileNotFoundException; import java.io.IOException; public class LocatorBasedLookup extends AbstractLocatorLookup { final private ILocator locator; public LocatorBasedLookup(ILocator locator) { super(); this.locator = locator; } public ILocator createLocator(String location) throws IOException { ILocator lookup = getLocator().getChild(location); if (lookup.exists()) { return lookup; } throw new FileNotFoundException("locator '" + location + "' not found"); } public ILocator getLocator() { return locator; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/LocatorFactory.java0000644000175000017500000000361410751651500026254 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locator; /** * Singleton access to the {@link ILocatorFactory}. */ public class LocatorFactory { private static ILocatorFactory ACTIVE = new FileLocatorFactory(); public static ILocatorFactory get() { return ACTIVE; } public static void set(ILocatorFactory factory) { ACTIVE = factory; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/ReadOnlyLocator.java0000644000175000017500000000351211061151622026352 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locator; /** * A simple read only locator. * */ public class ReadOnlyLocator extends DelegatingLocator { public ReadOnlyLocator(ILocator delegate) { super(delegate); } @Override public boolean isReadOnly() { return true; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/StringLocator.java0000644000175000017500000001604711411055574026122 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locator; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.URL; import de.intarsys.tools.file.FileTools; import de.intarsys.tools.randomaccess.IRandomAccess; import de.intarsys.tools.randomaccess.RandomAccessByteArray; /** * A simple adapter from a {@link String} to {@link ILocator}. * */ public class StringLocator extends CommonLocator { final private String content; private String encoding = System.getProperty("file.encoding"); private String localName; private String type; public StringLocator(String content, String name, String type) { super(); this.content = content; this.localName = name; this.type = type; } @Override public void delete() throws IOException { // nothing to do... } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#exists() */ public boolean exists() { return getContent() != null; } protected byte[] getBytes() { byte[] bytes; try { bytes = getContent().getBytes(encoding); } catch (UnsupportedEncodingException e) { bytes = getContent().getBytes(); } return bytes; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getChild(java.lang.String) */ public ILocator getChild(String child) { return null; } public String getContent() { return content; } public String getEncoding() { return encoding; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getFullName() */ public String getFullName() { if (getType() == null) { return getLocalName(); } else { return getLocalName() + "." + getType(); } } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getInputStream() */ public InputStream getInputStream() throws IOException { byte[] bytes = getBytes(); return new ByteArrayInputStream(bytes); } @Override public long getLength() throws IOException { return getBytes().length; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getLocalName() */ public String getLocalName() { return localName; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getOutputStream() */ public OutputStream getOutputStream() throws IOException { throw new IOException("locator is read only"); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getParent() */ public ILocator getParent() { return null; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getRandomAccessData() */ public IRandomAccess getRandomAccess() throws IOException { byte[] bytes = getBytes(); return new RandomAccessByteArray(bytes); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getReader() */ public Reader getReader() throws IOException { return new StringReader(getContent()); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getReader(java.lang.String) */ public Reader getReader(String encoding) throws IOException { return new StringReader(getContent()); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getType() */ public String getType() { return type; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getTypedName() */ public String getTypedName() { return (type == null) ? localName : (localName + "." + type); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getWriter() */ public Writer getWriter() throws IOException { throw new IOException("locator is read only"); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getWriter(java.lang.String) */ public Writer getWriter(String encoding) throws IOException { throw new IOException("locator is read only"); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#isDirectory() */ public boolean isDirectory() { return false; } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#isOutOfSynch() */ public boolean isOutOfSynch() { return false; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#isReadOnly() */ @Override public boolean isReadOnly() { return true; } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#isSynchSynchronous() */ public boolean isSynchSynchronous() { return false; } /* * (non-Javadoc) * * @see * de.intarsys.tools.locator.ILocator#listLocators(de.intarsys.tools.locator * .ILocatorNameFilter) */ public ILocator[] listLocators(ILocatorNameFilter filter) throws IOException { return new ILocator[0]; } @Override public void rename(String newName) throws IOException { localName = FileTools.getBaseName(newName); type = FileTools.getExtension(newName, getType()); } public void setEncoding(String encoding) { this.encoding = encoding; } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#synch() */ public void synch() { // } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#toURL() */ public URL toURL() { return null; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/AbsoluteFileLocatorLookup.java0000644000175000017500000000070711105016044030405 0ustar twernertwernerpackage de.intarsys.tools.locator; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; public class AbsoluteFileLocatorLookup extends AbstractLocatorLookup { public ILocator createLocator(String location) throws IOException { File file = new File(location); if (file.exists()) { return new FileLocator(file); } throw new FileNotFoundException("locator '" + location + "' not found"); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/FileLocator.java0000644000175000017500000003334411222634260025525 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locator; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Level; import de.intarsys.tools.file.FileTools; import de.intarsys.tools.locking.ILock; import de.intarsys.tools.locking.ILockLevel; import de.intarsys.tools.locking.ILockSupport; import de.intarsys.tools.logging.LogTools; import de.intarsys.tools.randomaccess.IRandomAccess; import de.intarsys.tools.randomaccess.RandomAccessFile; import de.intarsys.tools.stream.StreamTools; import de.intarsys.tools.stream.TempFileOutputStream; /** * File based implementation of {@link ILocator}. */ public class FileLocator extends CommonLocator implements ILockSupport { class FileLocatorLock implements ILock { private java.io.RandomAccessFile ra; public boolean acquire(Object owner, ILockLevel level) { try { ra = new java.io.RandomAccessFile(getFile(), "r"); return true; } catch (FileNotFoundException e) { return false; } } public void release(Object owner) { StreamTools.close(ra); } } /** * The file referenced by the locator */ private File file; /** * The encoding of the designated source */ private String encoding; /** * Flag if the resource is out of synch */ private boolean outOfSynch; /** * flag if we synchronize synchronously with every check */ private boolean synchSynchronous = false; /** * Timestamp of last modification to the resource. */ private long lastModified = 0; /** * flag if output is created initially in a temporary file */ private boolean useTempFile = false; private File canonicalFile; public FileLocator(File file) { super(); this.file = file; } public FileLocator(String path) { this(new File(path)); } @Override public void delete() throws IOException { if (getFile() == null) { return; } getFile().delete(); } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (!(obj instanceof FileLocator)) { return false; } return getCanonicalFile() .equals(((FileLocator) obj).getCanonicalFile()); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#exists() */ public boolean exists() { return getFile().exists(); } /** * The canonical file represented by this. * * @return The canonical file represented by this. */ public File getCanonicalFile() { if (canonicalFile == null) { try { canonicalFile = getFile().getCanonicalFile(); } catch (IOException e) { canonicalFile = getFile(); } } return canonicalFile; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getChild(java.lang.String) */ public ILocator getChild(String name) { File childfile = new File(getFile(), name); FileLocator result = new FileLocator(childfile); result.setSynchSynchronous(isSynchSynchronous()); return result; } /** * The encoding of the file. * * @return Returns the encoding. */ protected String getEncoding() { return encoding; } /** * Answer the file represented by this. * * @return The canonical file represented by this. */ public File getFile() { return file; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getFullName() */ public String getFullName() { if (getFile() == null) { return "unknown"; } return getFile().getAbsolutePath(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getInputStream() */ public InputStream getInputStream() throws IOException { // trigger timestamp reading getLastModified(); return new FileInputStream(getFile()); } /** * Answer the timestamp of the last modification. * * @return the timestamp of the last modification. */ protected long getLastModified() { if (lastModified == 0) { if (file.exists()) { lastModified = file.lastModified(); } } return lastModified; } @Override public long getLength() throws IOException { return file.length(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getLocalName() */ public String getLocalName() { if (getFile() == null) { return "unknown"; } return FileTools.getBaseName(getFile()); } public ILock getLock() { return new FileLocatorLock(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getOutputStream() */ public OutputStream getOutputStream() throws IOException { // trigger timestamp reading getLastModified(); if (!getFile().getParentFile().exists()) { getFile().getParentFile().mkdirs(); } if (isUseTempFile()) { return new TempFileOutputStream(getFile(), "tmp_", "." + getType()); } return new FileOutputStream(getFile()); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getParent() */ public ILocator getParent() { File parentFile = FileTools.getParentFile(getFile()); if (parentFile == null) { return null; } FileLocator result = new FileLocator(parentFile); result.setSynchSynchronous(isSynchSynchronous()); return result; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getRandomAccess() */ public IRandomAccess getRandomAccess() throws IOException { // trigger timestamp reading getLastModified(); if (isUseTempFile()) { throw new UnsupportedOperationException( "no random access to temp file"); } return new RandomAccessFile(getFile()); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getReader() */ public Reader getReader() throws IOException { // trigger timestamp reading getLastModified(); if ((getEncoding() == null) || getEncoding().equals("")) { return new InputStreamReader(getInputStream()); } return new InputStreamReader(getInputStream(), getEncoding()); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getReader(java.lang.String) */ public Reader getReader(String newEncoding) throws IOException { // trigger timestamp reading getLastModified(); if ((newEncoding == null) || newEncoding.equals("")) { return getReader(); } return new InputStreamReader(getInputStream(), newEncoding); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getType() */ public String getType() { if (getFile() == null) { return ""; } return FileTools.getExtension(getFile()); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getTypedName() */ public String getTypedName() { if (getFile() == null) { return "unknown"; } return getFile().getName(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getWriter() */ public Writer getWriter() throws IOException { // trigger timestamp reading getLastModified(); if ((getEncoding() == null) || getEncoding().equals("")) { return new OutputStreamWriter(getOutputStream()); } return new OutputStreamWriter(getOutputStream(), getEncoding()); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getWriter(java.lang.String) */ public Writer getWriter(String newEncoding) throws IOException { // trigger timestamp reading getLastModified(); if ((newEncoding == null) || newEncoding.equals("")) { return getWriter(); } return new OutputStreamWriter(getOutputStream(), newEncoding); } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { try { return getFile().getCanonicalFile().hashCode(); } catch (IOException e) { return 17; } } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#isDirectory() */ public boolean isDirectory() { return getFile().isDirectory(); } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#isOutOfSynch() */ public synchronized boolean isOutOfSynch() { if (isSynchSynchronous()) { synch(); } return outOfSynch; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#isReadOnly() */ @Override public boolean isReadOnly() { if (super.isReadOnly()) { return true; } IRandomAccess r = null; try { if (!getFile().exists()) { if (getFile().createNewFile()) { getFile().delete(); return false; } return true; } r = getRandomAccess(); if (r == null || r.isReadOnly()) { return true; } return false; } catch (IOException e) { return true; } finally { StreamTools.close(r); } } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#isSynchSynchronous() */ public boolean isSynchSynchronous() { return synchSynchronous; } /** * true if temp file should be used. * * @return true if temp file should be used. */ public boolean isUseTempFile() { return useTempFile; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#listLocators(de.intarsys.tools.locator.ILocatorNameFilter) */ public ILocator[] listLocators(final ILocatorNameFilter filter) throws IOException { if (!getFile().exists()) { throw new FileNotFoundException(getFile().getName() + " not found"); } if (!getFile().isDirectory()) { throw new IOException(getFile().getName() + " not a directory"); } File[] candidates; if (filter == null) { candidates = getFile().listFiles(); } else { candidates = getFile().listFiles(new FilenameFilter() { public boolean accept(File dir, String current) { return filter.accept(FileLocator.this, current); } }); } if (candidates == null) { throw new IOException("error listing resources"); } ILocator[] result = new ILocator[candidates.length]; for (int i = 0; i < result.length; i++) { FileLocator l = new FileLocator(candidates[i].getPath()); l.setSynchSynchronous(isSynchSynchronous()); l.setEncoding(getEncoding()); result[i] = l; } return result; } @Override public void rename(String newName) throws IOException { if (getFile() == null) { return; } File parent = getFile().getParentFile(); if (parent == null) { parent = getFile().getAbsoluteFile().getParentFile(); } File newFile; if (parent == null) { newFile = new File(newName); } else { newFile = new File(parent, newName); } FileTools.renameFile(getFile(), newFile); file = newFile; canonicalFile = null; lastModified = 0; } protected void setEncoding(String encoding) { this.encoding = encoding; } /** * @param synchSynchronous */ public void setSynchSynchronous(boolean synchSynchronous) { this.synchSynchronous = synchSynchronous; } /** * @param useTempFile */ public void setUseTempFile(boolean useTempFile) { this.useTempFile = useTempFile; } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#synch() */ public synchronized void synch() { if (getFile() == null) { return; } if ((getLastModified() != getFile().lastModified())) { LogTools.getLogger(this.getClass()).log(Level.FINEST, "'" + getFullName() + "' out of synch!"); outOfSynch = true; } } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return getFile().toString(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#toURL() */ public URL toURL() { try { return new URL("file", null, getFullName() + "/"); } catch (MalformedURLException e) { return null; } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/ILocatorFactory.java0000644000175000017500000000417710767427524026410 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locator; import java.io.IOException; /** * A factory for {@link de.intarsys.tools.locator.ILocator} objects. */ public interface ILocatorFactory { /** * Create a {@link de.intarsys.tools.locator.ILocator} object. * *

* path may for example define a file in the file system. *

* * @param location * The fully qualified location definition. * * @return The ILocator object created from the location. */ public ILocator createLocator(String location) throws IOException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/AbstractLocatorLookup.java0000644000175000017500000000016511105016044027570 0ustar twernertwernerpackage de.intarsys.tools.locator; abstract public class AbstractLocatorLookup implements ILocatorFactory { } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/LocatorViewport.java0000644000175000017500000002543211222634260026464 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locator; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.URL; import de.intarsys.tools.adapter.AdapterTools; import de.intarsys.tools.adapter.IAdapterSupport; import de.intarsys.tools.randomaccess.AbstractRandomAccess; import de.intarsys.tools.randomaccess.IRandomAccess; /** * A viewport implementation for {@link ILocator}. This object defines a range * of bytes visible to the client of the viewport. */ public class LocatorViewport extends CommonLocator implements IAdapterSupport { private class InputStreamProxy extends InputStream { private InputStream is; private int current = 0; public InputStreamProxy(InputStream is) { this.is = is; } @Override public void close() throws IOException { is.close(); } @Override public int read() throws IOException { while (current < getStart()) { is.read(); current++; } if (getEnd() != -1 && current >= getEnd()) { return -1; } int i = is.read(); current++; return i; } } private class RandomAccessProxy extends AbstractRandomAccess { private IRandomAccess ra; private long ptrLocal = 0; private long ptrHost = 0; public RandomAccessProxy(IRandomAccess ra) { this.ra = ra; try { seek(0); } catch (IOException e) { throw new RuntimeException(e); } } public void close() throws IOException { ra.close(); } public void flush() throws IOException { ra.flush(); } public long getLength() throws IOException { long end = Math.min(getEnd(), ra.getLength()); return end - getStart(); } public long getOffset() throws IOException { return ra.getOffset() - getStart(); } public boolean isReadOnly() { return true; } public int read() throws IOException { if (ptrHost < getStart()) { throw new IOException("index out of scope"); } if (getEnd() != -1 && ptrHost >= getEnd()) { return -1; } int i = ra.read(); ptrHost++; ptrLocal++; return i; } public int read(byte[] buffer) throws IOException { if (ptrHost < getStart()) { throw new IOException("index out of scope"); } if (getEnd() != -1 && ptrHost >= getEnd()) { return -1; } int numBytes = Math.min(buffer.length, (int) getEnd() - (int) ptrHost); int i = ra.read(buffer, 0, numBytes); ptrHost += i; ptrLocal += i; return i; } public int read(byte[] buffer, int start, int numBytes) throws IOException { if (ptrHost < getStart()) { throw new IOException("index out of scope"); } if (getEnd() != -1 && ptrHost >= getEnd()) { return -1; } numBytes = Math.min(numBytes, (int) getEnd() - (int) ptrHost); int i = ra.read(buffer, start, numBytes); ptrHost += i; ptrLocal += i; return i; } public void seek(long offset) throws IOException { ra.seek(getStart() + offset); ptrHost = getStart() + offset; ptrLocal = offset; } public void seekBy(long delta) throws IOException { ra.seek(ptrHost + delta); ptrHost += delta; ptrLocal += delta; } public void setLength(long newLength) throws IOException { } public void write(byte[] buffer) throws IOException { } public void write(byte[] buffer, int start, int numBytes) throws IOException { } public void write(int b) throws IOException { } } private class ReaderProxy extends Reader { private Reader r; private int current = 0; public ReaderProxy(Reader r) { this.r = r; } @Override public void close() throws IOException { r.close(); } @Override public int read(char[] cbuf, int off, int len) throws IOException { while (current < getStart()) { r.read(); current++; } if (current >= getEnd()) { return -1; } len = Math.min(len, (int) getEnd() - current); int i = r.read(cbuf, off, len); current += i; return i; } } private ILocator delegate; private long start = 0; private long end = -1; private String name; public LocatorViewport(ILocator delegate) { super(); setDelegate(delegate); } @Override public void delete() throws IOException { // nothing to do... } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#exists() */ public boolean exists() { return getDelegate().exists(); } public T getAdapter(Class clazz) { return AdapterTools.getAdapter(delegate, clazz); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getChild(java.lang.String) */ public ILocator getChild(String name) { return getDelegate().getChild(name); } public ILocator getDelegate() { return delegate; } public long getEnd() { return end; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getFullName() */ public String getFullName() { if (getName() != null) { return getName(); } return getDelegate().getFullName(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getInputStream() */ public InputStream getInputStream() throws IOException { return new InputStreamProxy(getDelegate().getInputStream()); } @Override public long getLength() { return getEnd() - getStart(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getLocalName() */ public String getLocalName() { if (getName() != null) { return getName(); } return getDelegate().getLocalName(); } public String getName() { return name; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getOutputStream() */ public OutputStream getOutputStream() throws IOException { return null; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getParent() */ public ILocator getParent() { return getDelegate().getParent(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getRandomAccess() */ public IRandomAccess getRandomAccess() throws IOException { return new RandomAccessProxy(getDelegate().getRandomAccess()); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getReader() */ public Reader getReader() throws IOException { return new ReaderProxy(getDelegate().getReader()); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getReader(java.lang.String) */ public Reader getReader(String encoding) throws IOException { return new ReaderProxy(getDelegate().getReader(encoding)); } public long getStart() { return start; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getType() */ public String getType() { return getDelegate().getType(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getTypedName() */ public String getTypedName() { return getDelegate().getTypedName(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getWriter() */ public Writer getWriter() throws IOException { return null; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getWriter(java.lang.String) */ public Writer getWriter(String encoding) throws IOException { return null; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#isDirectory() */ public boolean isDirectory() { return getDelegate().isDirectory(); } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#isOutOfSynch() */ public boolean isOutOfSynch() { return getDelegate().isOutOfSynch(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#isReadOnly() */ @Override public boolean isReadOnly() { return true; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#listLocators(de.intarsys.tools.locator.ILocatorNameFilter) */ public ILocator[] listLocators(ILocatorNameFilter filter) throws IOException { return getDelegate().listLocators(filter); } @Override public void rename(String newName) throws IOException { getDelegate().rename(newName); } protected void setDelegate(ILocator delegate) { this.delegate = delegate; } public void setEnd(long end) { try { if ((end < 0) || (end > getDelegate().getLength())) { throw new IllegalArgumentException("end"); } } catch (IOException e) { throw new RuntimeException(e); } this.end = end; } public void setName(String name) { this.name = name; } public void setStart(long start) { try { if ((start < 0) || (start > getDelegate().getLength())) { throw new IllegalArgumentException("start"); } } catch (IOException e) { throw new RuntimeException(e); } this.start = start; } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#synch() */ public void synch() { getDelegate().synch(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#toURL() */ public URL toURL() { return getDelegate().toURL(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/DelegatingLocatorLookup.java0000644000175000017500000000272211105016044030071 0ustar twernertwernerpackage de.intarsys.tools.locator; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import de.intarsys.tools.exception.ExceptionTools; public class DelegatingLocatorLookup extends AbstractLocatorLookup { private List factories = new ArrayList(); public boolean addLocatorFactory(ILocatorFactory factory) { if (factory == this) { // common mistake throw new IllegalArgumentException("can not delegate to myself"); } return factories.add(factory); } public ILocator createLocator(String location) throws IOException { for (Iterator it = factories.iterator(); it.hasNext();) { ILocatorFactory factory = (ILocatorFactory) it.next(); try { return factory.createLocator(location); } catch (FileNotFoundException e) { // search on } catch (IOException e) { // we tried to load but failed throw e; } catch (Exception e) { // we tried to load but failed for unknown reason throw ExceptionTools.createIOException("", e); } } // we tried all but failed throw new FileNotFoundException(location); } public void clear() { factories.clear(); } public List getLocatorFactories() { return new ArrayList(factories); } public boolean removeLocatorFactory(ILocatorFactory factory) { return factories.remove(factory); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/NullLocator.java0000644000175000017500000000411111271607250025551 0ustar twernertwernerpackage de.intarsys.tools.locator; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.URL; import de.intarsys.tools.randomaccess.IRandomAccess; public class NullLocator implements ILocator { public void delete() throws IOException { throw new IOException("unsupported operation"); } public boolean exists() { return false; } public ILocator getChild(String name) { return null; } public String getFullName() { return "null"; } public InputStream getInputStream() throws IOException { throw new IOException("unsupported operation"); } public long getLength() throws IOException { return 0; } public String getLocalName() { return "null"; } public OutputStream getOutputStream() throws IOException { throw new IOException("unsupported operation"); } public ILocator getParent() { return null; } public IRandomAccess getRandomAccess() throws IOException { throw new IOException("unsupported operation"); } public Reader getReader() throws IOException { throw new IOException("unsupported operation"); } public Reader getReader(String encoding) throws IOException { throw new IOException("unsupported operation"); } public String getType() { return "null"; } public String getTypedName() { return "null"; } public Writer getWriter() throws IOException { throw new IOException("unsupported operation"); } public Writer getWriter(String encoding) throws IOException { throw new IOException("unsupported operation"); } public boolean isDirectory() { return false; } public boolean isOutOfSynch() { return false; } public boolean isReadOnly() { return true; } public ILocator[] listLocators(ILocatorNameFilter filter) throws IOException { return null; } public void rename(String newName) throws IOException { } public void setReadOnly() { } public void synch() { } public URL toURL() { return null; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/StreamLocator.java0000644000175000017500000001566310761311016026103 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locator; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.net.URL; import de.intarsys.tools.file.FileTools; import de.intarsys.tools.randomaccess.IRandomAccess; /** * A simple adapter from {@link InputStream} to {@link ILocator}. *

* This one has different behavior as you can only request input or output * stream ONCE. No backing copy of the input / output stream is made by the * locator. */ public class StreamLocator extends CommonLocator { private boolean inputUsed = false; private boolean outputUsed = false; private final InputStream inputStream; private final OutputStream outputStream; private String type; private String localName; public StreamLocator(InputStream is, OutputStream os, String name, String type) { super(); this.inputStream = is; this.outputStream = os; this.localName = name; this.type = type; } public StreamLocator(InputStream stream, String name, String type) { this(stream, null, name, type); } public StreamLocator(OutputStream stream, String name, String type) { this(null, stream, name, type); } @Override public void delete() throws IOException { // nothing to do... } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#exists() */ public boolean exists() { return inputStream != null; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getChild(java.lang.String) */ public ILocator getChild(String child) { return null; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getFullName() */ public String getFullName() { return getLocalName(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getInputStream() */ public InputStream getInputStream() throws IOException { if (inputUsed) { throw new IOException("input already requested"); } inputUsed = true; return inputStream; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getLocalName() */ public String getLocalName() { return localName; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getOutputStream() */ public OutputStream getOutputStream() throws IOException { if (outputUsed) { throw new IOException("output already requested"); } outputUsed = true; return outputStream; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getParent() */ public ILocator getParent() { return null; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getRandomAccessData() */ public IRandomAccess getRandomAccess() throws IOException { throw new UnsupportedOperationException(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getReader() */ public Reader getReader() throws IOException { return new InputStreamReader(getInputStream()); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getReader(java.lang.String) */ public Reader getReader(String encoding) throws IOException { return new InputStreamReader(getInputStream(), encoding); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getType() */ public String getType() { return type; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getTypedName() */ public String getTypedName() { return (type == null) ? localName : (localName + "." + type); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getWriter() */ public Writer getWriter() throws IOException { return new OutputStreamWriter(getOutputStream()); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getWriter(java.lang.String) */ public Writer getWriter(String encoding) throws IOException { return new OutputStreamWriter(getOutputStream(), encoding); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#isDirectory() */ public boolean isDirectory() { return false; } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#isOutOfSynch() */ public boolean isOutOfSynch() { return false; } @Override public boolean isReadOnly() { if (super.isReadOnly()) { return true; } return outputStream == null; } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#isSynchSynchronous() */ public boolean isSynchSynchronous() { return false; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#listLocators(de.intarsys.tools.locator.ILocatorNameFilter) */ public ILocator[] listLocators(ILocatorNameFilter filter) { return new ILocator[0]; } @Override public void rename(String newName) throws IOException { localName = FileTools.getBaseName(newName); type = FileTools.getExtension(newName); } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#synch() */ public void synch() { // } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#toURL() */ public URL toURL() { return null; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/ILocatorNameFilter.java0000644000175000017500000000433710751651500027007 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locator; /** * ILocatorNameFilter objects can filter {@link * de.intarsys.tools.locator.ILocator} objects when listing their children. */ public interface ILocatorNameFilter { /** * This method returns true if the {@link ILocator} with name * name within parent should be included in * the result list. * * @param parent * The parent locator. * @param name * The name of the locator within the parent. * * @return true if locator should be included in the result * list. */ public boolean accept(ILocator parent, String name); } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/TransientLocator.java0000644000175000017500000001643710751651500026623 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locator; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.URL; import de.intarsys.tools.file.FileTools; import de.intarsys.tools.randomaccess.IRandomAccess; /** * A "non persistent" locator. This is used as a placeholder where an * {@link ILocator} is necessary but no real location is yet defined. */ public class TransientLocator extends CommonLocator { private boolean alwaysUnchanged; private String canonicalName; private String localName; private String type; public TransientLocator(String name, String type) { if ((name == null) || (type == null)) { throw new NullPointerException( "name and type may not be null for TransientLocator"); } this.localName = name; this.canonicalName = canonical(name); this.type = canonical(type); } private String canonical(String name) { return name.trim().toLowerCase(); } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (obj instanceof TransientLocator) { TransientLocator other = (TransientLocator) obj; return other.canonicalName.equals(canonicalName) && other.type.equals(type); } return false; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#exists() */ public boolean exists() { return false; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getChild(java.lang.String) */ public ILocator getChild(String name) { return null; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getFullName() */ public String getFullName() { return localName + "." + type; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getInputStream() */ public InputStream getInputStream() throws IOException { throw new FileNotFoundException("transient locator"); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getLocalName() */ public String getLocalName() { return localName; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getOutputStream() */ public OutputStream getOutputStream() throws IOException { throw new FileNotFoundException("transient locator"); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getParent() */ public ILocator getParent() { return null; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getRandomAccess() */ public IRandomAccess getRandomAccess() throws IOException { throw new FileNotFoundException("transient locator"); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getReader() */ public Reader getReader() throws IOException { throw new FileNotFoundException("transient locator"); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getReader(java.lang.String) */ public Reader getReader(String encoding) throws IOException { throw new FileNotFoundException("transient locator"); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getType() */ public String getType() { return type; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getTypedName() */ public String getTypedName() { return localName + "." + type; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getWriter() */ public Writer getWriter() throws IOException { throw new FileNotFoundException("transient locator"); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getWriter(java.lang.String) */ public Writer getWriter(String encoding) throws IOException { throw new FileNotFoundException("transient locator"); } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ public int hashCode() { return canonicalName.hashCode(); } public boolean isAlwaysUnchanged() { return alwaysUnchanged; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#isDirectory() */ public boolean isDirectory() { return false; } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#isOutOfSynch() */ public boolean isOutOfSynch() { return false; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#isReadOnly() */ public boolean isReadOnly() { return true; } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#isSynchSynchronous() */ public boolean isSynchSynchronous() { return false; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#listLocators(de.intarsys.tools.locator.ILocatorNameFilter) */ public ILocator[] listLocators(ILocatorNameFilter filter) throws IOException { return new ILocator[0]; } public void rename(String newName) throws IOException { localName = FileTools.getBaseName(newName); type = FileTools.getExtension(newName); } public void setAlwaysUnchanged(boolean paramAlwaysUnchanged) { alwaysUnchanged = paramAlwaysUnchanged; } public void setLocalName(String name) { this.localName = name; this.canonicalName = canonical(name); } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#synch() */ public void synch() { // no op } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#toURL() */ public URL toURL() { return null; } public void delete() throws IOException { // nothing to do... } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/CommonLocator.java0000644000175000017500000000546711222634260026103 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locator; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import de.intarsys.tools.file.TempTools; import de.intarsys.tools.stream.StreamTools; abstract public class CommonLocator implements ILocator { private boolean readOnly = false; protected ILocator createTempFileLocator() throws IOException { File file = TempTools.createTempFile("locator", ".tmp"); file.deleteOnExit(); InputStream is = null; OutputStream os = null; try { is = getInputStream(); os = new FileOutputStream(file); StreamTools.copyStream(is, false, os, false); } finally { StreamTools.close(is); StreamTools.close(os); } ILocator tempFileLocator = new FileLocator(file); tempFileLocator.setReadOnly(); return tempFileLocator; } public void delete() throws IOException { throw new IOException("unsupported operation"); } public long getLength() throws IOException { return -1; } public boolean isReadOnly() { return readOnly; } public void rename(String newName) throws IOException { throw new IOException("unsupported operation"); } public void setReadOnly() { readOnly = true; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/LocatorTools.java0000644000175000017500000000621611411055574025751 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locator; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import de.intarsys.tools.stream.StreamTools; /** * Tool methods for dealing with {@link ILocator}. * */ public class LocatorTools { public static final String PATH_SEPARATOR = ";"; //$NON-NLS-1$ public static ILocator[] createLocators(String paths, ILocatorFactory factory) throws IOException { if (factory == null) { factory = LocatorFactory.get(); } List locators = new ArrayList(); for (StringTokenizer t = new StringTokenizer(paths, PATH_SEPARATOR); t .hasMoreTokens();) { String path = t.nextToken(); locators.add(factory.createLocator(path)); } ILocator[] result = new ILocator[locators.size()]; return locators.toArray(result); } public static final byte[] getBytes(ILocator locator) throws IOException { if (locator instanceof ByteArrayLocator) { return ((ByteArrayLocator) locator).getBytes(); } InputStream is = null; try { is = locator.getInputStream(); return StreamTools.toByteArray(is); } finally { StreamTools.close(is); } } public static final File getFile(ILocator locator) throws IOException { if (locator instanceof FileLocator) { return ((FileLocator) locator).getFile(); } // add conversion (temp file) code throw new IOException("can't create file for '" + locator.getFullName() //$NON-NLS-1$ + "'"); //$NON-NLS-1$ } private LocatorTools() { } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/ILocatorSupport.java0000644000175000017500000000372010751651500026430 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locator; /** * Indicate support for locating the receivers resource physically. */ public interface ILocatorSupport { /** * Return the {@link ILocator} that defines the physical resource location * for the reciver. * * @return Return the {@link ILocator} that defines the physical resource * location for the reciver. */ public ILocator getLocator(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/SearchPathLocatorLookup.java0000644000175000017500000000210211105016044030040 0ustar twernertwernerpackage de.intarsys.tools.locator; import java.io.File; import java.util.Enumeration; import java.util.StringTokenizer; public class SearchPathLocatorLookup extends DelegatingLocatorLookup { public static final String PATH_SEPARATOR = ";"; //$NON-NLS-1$ protected void addSearchPath(File parent, String path) { File child = new File(path); ILocator locator; if (child.isAbsolute() || parent == null) { locator = new FileLocator(child); ((FileLocator) locator).setSynchSynchronous(true); } else { FileLocator parentLocator = new FileLocator(parent); parentLocator.setSynchSynchronous(true); locator = parentLocator.getChild(path); } addLocatorFactory(new LocatorBasedLookup(locator)); } public void setSearchPath(File parent, String paths) { clear(); // set up search paths for (Enumeration e = new StringTokenizer(paths, PATH_SEPARATOR); e .hasMoreElements();) { String path = (String) e.nextElement(); if ((path != null) && (path.trim().length() > 0)) { addSearchPath(parent, path); } } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/ClassLoaderResourceLocator.java0000644000175000017500000002021711001376076030550 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locator; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.URL; import de.intarsys.tools.file.FileTools; import de.intarsys.tools.randomaccess.IRandomAccess; /** * An {@link ILocator} for java resources identified directly by a class loader. * */ public class ClassLoaderResourceLocator extends CommonLocator { private final ClassLoader classLoader; private final String name; /** The encoding of the designated source */ private String encoding; private ILocator tempFileLocator; public ClassLoaderResourceLocator(ClassLoader classLoader, String name) { super(); this.classLoader = classLoader; this.name = name; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (!(obj instanceof ClassLoaderResourceLocator)) { return false; } return getName().equals(((ClassLoaderResourceLocator) obj).getName()); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#exists() */ public boolean exists() { return getClassLoader().getResource(getName()) != null; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getChild(java.lang.String) */ public ILocator getChild(String childName) { String child = getName() + "/" + childName; ClassLoaderResourceLocator result = new ClassLoaderResourceLocator( getClassLoader(), child); return result; } /** * The {@link ClassLoader} used to access the resource. * * @return The {@link ClassLoader} used to access the resource. */ public ClassLoader getClassLoader() { return classLoader; } protected String getEncoding() { return encoding; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getFullName() */ public String getFullName() { return getName(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getInputStream() */ public InputStream getInputStream() throws IOException { return getClassLoader().getResourceAsStream(getName()); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getLocalName() */ public String getLocalName() { if (getName() == null) { return "unknown"; } else { return FileTools.getBaseName(getName()); } } /** * The resource name defined when constructing this. * * @return The resource name defined when constructing this. */ public String getName() { return name; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getOutputStream() */ public OutputStream getOutputStream() throws IOException { throw new IOException("locator is read only"); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getParent() */ public ILocator getParent() { int index = getName().lastIndexOf("/"); if (index > -1) { String parentname = getName().substring(0, index); return new ClassLoaderResourceLocator(getClassLoader(), parentname); } else { return null; } } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getRandomAccessData() */ synchronized public IRandomAccess getRandomAccess() throws IOException { if (tempFileLocator == null) { tempFileLocator = createTempFileLocator(); } return tempFileLocator.getRandomAccess(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getReader() */ public Reader getReader() throws IOException { if (getEncoding() == null) { return new InputStreamReader(getInputStream()); } else { return new InputStreamReader(getInputStream(), getEncoding()); } } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getReader(java.lang.String) */ public Reader getReader(String newEncoding) throws IOException { if ((newEncoding == null) || newEncoding.equals("")) { return getReader(); } else { return new InputStreamReader(getInputStream(), newEncoding); } } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getType() */ public String getType() { if (getName() == null) { return ""; } return FileTools.getExtension(new File(getName())); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getTypedName() */ public String getTypedName() { if (getName() == null) { return ""; } return new File(getName()).getName(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getWriter() */ public Writer getWriter() throws IOException { throw new IOException("locator is read only"); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getWriter(java.lang.String) */ public Writer getWriter(String pEncoding) throws IOException { throw new IOException("locator is read only"); } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return getName().hashCode(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#isDirectory() */ public boolean isDirectory() { return false; } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#isOutOfSynch() */ public boolean isOutOfSynch() { return false; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#isReadOnly() */ @Override public boolean isReadOnly() { return true; } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#isSynchSynchronous() */ public boolean isSynchSynchronous() { return false; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#listLocators(de.intarsys.tools.locator.ILocatorNameFilter) */ public ILocator[] listLocators(final ILocatorNameFilter filter) throws IOException { return new ILocator[0]; } protected void setEncoding(String encoding) { this.encoding = encoding; } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#synch() */ public void synch() { // do nothing } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return getName(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#toURL() */ public URL toURL() { return null; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/MappedLocatorLookup.java0000644000175000017500000000146011105016044027232 0ustar twernertwernerpackage de.intarsys.tools.locator; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class MappedLocatorLookup extends AbstractLocatorLookup { private Map locators = new HashMap(); public void addMap(String name, ILocator locator) { locators.put(name, locator); } public ILocator createLocator(String location) throws IOException { ILocator lookup = locators.get(location); if (lookup != null) { return lookup; } throw new FileNotFoundException("locator '" + location + "' not found"); } public Map getMaps() { return new HashMap(locators); } public void removeMap(String name) { locators.remove(name); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/FileLocatorFactory.java0000644000175000017500000001066611411055574027064 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locator; import java.io.File; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import de.intarsys.tools.file.FileTools; /** * The factory for {@link FileLocator} objects. * *

* {@link FileLocator} instances are created either using an absolute path name * or are looked up relative to the factorys search path. Multiple search paths * may be defined. *

*/ public class FileLocatorFactory implements ILocatorFactory { /** The separator character for the definition of multiple search paths */ public static final String PATH_SEPARATOR = ";"; /** The root path where we look up relative references */ private String searchPathDefinition; /** The collection of search paths to be looked up when creating a locator */ private List searchPaths; /** flag if we synchronize synchronously with every check */ private boolean synchSynchronous = true; /** * Create a new factory. */ public FileLocatorFactory() { super(); setSearchPathDefinition("./"); } /** * The file locator factory supports looking up resources in multiple paths. * To preserve compatibility to ILocatorFactory, the last locator created is * returned if no match is found. This is a valid locator, even so no * existing physical resource is designated. * * @see de.intarsys.tools.locator.ILocatorFactory#createLocator(java.lang.String) */ public ILocator createLocator(String path) { FileLocator result = null; for (Iterator it = getSearchPaths().iterator(); it.hasNext();) { String searchPath = (String) it.next(); File parent = new File(searchPath); File absolutePath = FileTools.resolvePath(parent, path); result = new FileLocator(absolutePath); // avoid exists check if possible if (!it.hasNext() || result.exists()) { break; } } if (result != null) { result.setSynchSynchronous(isSynchSynchronous()); } return result; } public String getSearchPathDefinition() { return searchPathDefinition; } public List getSearchPaths() { return searchPaths; } public boolean isSynchSynchronous() { return synchSynchronous; } public void setSearchPathDefinition(String searchPath) { this.searchPathDefinition = searchPath; // set up search paths searchPaths = new ArrayList(); for (Enumeration e = new StringTokenizer(searchPathDefinition, PATH_SEPARATOR); e.hasMoreElements();) { String path = (String) e.nextElement(); if ((path != null) && (path.trim().length() > 0) && !searchPaths.contains(path)) { searchPaths.add(path); } } } public void setSearchPaths(List searchPaths) { this.searchPaths = searchPaths; } public void setSynchSynchronous(boolean synchSynchronous) { this.synchSynchronous = synchSynchronous; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/ByteArrayLocator.java0000644000175000017500000001663211411055574026556 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locator; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Serializable; import java.io.Writer; import java.net.URL; import de.intarsys.tools.file.FileTools; import de.intarsys.tools.randomaccess.IRandomAccess; import de.intarsys.tools.randomaccess.RandomAccessByteArray; import de.intarsys.tools.string.StringTools; /** * An adapter from a byte[] object to {@link ILocator}. */ public class ByteArrayLocator extends CommonLocator implements Serializable { protected byte[] content; protected int length; private String fullName; private String localName; private String type; public ByteArrayLocator(byte[] data, String pFullName) { if (data == null) { data = new byte[0]; } this.content = data; this.length = data.length; setFullName(pFullName); } public ByteArrayLocator(byte[] data, String pName, String pType) { if (data == null) { data = new byte[0]; } this.content = data; this.length = data.length; if (StringTools.isEmpty(pType)) { setFullName(pName); } else { setFullName(pName + "." + pType); } } @Override public void delete() throws IOException { // nothing to do... } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#exists() */ public boolean exists() { return content != null; } public byte[] getBytes() { byte[] result = new byte[length]; System.arraycopy(content, 0, result, 0, length); return result; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getChild(java.lang.String) */ public ILocator getChild(String name) { return null; } public byte[] getContent() { return content; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getFullName() */ public String getFullName() { return fullName; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getInputStream() */ public InputStream getInputStream() { return new ByteArrayInputStream(content, 0, length); } @Override public long getLength() { return length; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getLocalName() */ public String getLocalName() { return localName; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getOutputStream() */ public OutputStream getOutputStream() { return new ByteArrayOutputStream() { @Override public void close() throws IOException { super.close(); content = buf; length = count; } @Override public void flush() throws IOException { super.flush(); content = buf; length = count; } }; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getParent() */ public ILocator getParent() { return null; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getRandomAccessData() */ public IRandomAccess getRandomAccess() { return new RandomAccessByteArray(content, length) { @Override public void flush() throws IOException { super.flush(); ByteArrayLocator.this.content = this.data; ByteArrayLocator.this.length = this.length; } }; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getReader() */ public Reader getReader() { return new InputStreamReader(getInputStream()); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getReader(java.lang.String) */ public Reader getReader(String encoding) throws IOException { return new InputStreamReader(getInputStream(), encoding); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getType() */ public String getType() { return type; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getTypedName() */ public String getTypedName() { return (type == null) ? localName : (localName + "." + type); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getWriter() */ public Writer getWriter() { return new OutputStreamWriter(getOutputStream()); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getWriter(java.lang.String) */ public Writer getWriter(String encoding) throws IOException { return new OutputStreamWriter(getOutputStream(), encoding); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#isDirectory() */ public boolean isDirectory() { return false; } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#isOutOfSynch() */ public boolean isOutOfSynch() { return false; } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#isSynchSynchronous() */ public boolean isSynchSynchronous() { return false; } /* * (non-Javadoc) * * @see * de.intarsys.tools.locator.ILocator#listLocators(de.intarsys.tools.locator * .ILocatorNameFilter) */ public ILocator[] listLocators(ILocatorNameFilter filter) { return new ILocator[0]; } @Override public void rename(String newName) throws IOException { setFullName(newName); } protected void setFullName(String newName) { fullName = newName; localName = FileTools.getBaseName(newName); type = FileTools.getExtension(newName, getType()); } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#synch() */ public void synch() { // } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#toURL() */ public URL toURL() { return null; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/ClassResourceLocator.java0000644000175000017500000002162411001376076027424 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locator; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.URL; import de.intarsys.tools.file.FileTools; import de.intarsys.tools.randomaccess.IRandomAccess; /** * An {@link ILocator} for java resources relative to a given class. */ public class ClassResourceLocator extends CommonLocator { private final Class clazz; private final String name; final private String resolvedName; /** The encoding of the designated source */ private String encoding; private ILocator tempFileLocator; public ClassResourceLocator(Class clazz, String name) { super(); this.clazz = clazz; this.name = name; this.resolvedName = resolveName(name); } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (!(obj instanceof ClassResourceLocator)) { return false; } return getResolvedName().equals( ((ClassResourceLocator) obj).getResolvedName()); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#exists() */ public boolean exists() { return getClazz().getResource(getResolvedName()) != null; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getChild(java.lang.String) */ public ILocator getChild(String childName) { String child = getResolvedName() + "/" + childName; ClassResourceLocator result = new ClassResourceLocator(getClazz(), child); return result; } /** * The {@link Class} used to define this. *

* The resource will be accessed the "getResourceAsStream" of this * {@link Class} object. * * @return The {@link Class} used to define this. */ public Class getClazz() { return clazz; } protected String getEncoding() { return encoding; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getFullName() */ public String getFullName() { return getResolvedName(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getInputStream() */ public InputStream getInputStream() throws IOException { return getClazz().getResourceAsStream(getResolvedName()); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getLocalName() */ public String getLocalName() { if (getName() == null) { return "unknown"; } else { return FileTools.getBaseName(getName()); } } /** * The resource name used when constructing this. * * @return The resource name used when constructing this. */ public String getName() { return name; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getOutputStream() */ public OutputStream getOutputStream() throws IOException { throw new IOException("locator is read only"); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getParent() */ public ILocator getParent() { int index = getResolvedName().lastIndexOf("/"); if (index > -1) { String parentname = getResolvedName().substring(0, index); return new ClassResourceLocator(getClazz(), parentname); } else { return null; } } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getRandomAccessData() */ synchronized public IRandomAccess getRandomAccess() throws IOException { if (tempFileLocator == null) { tempFileLocator = createTempFileLocator(); } return tempFileLocator.getRandomAccess(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getReader() */ public Reader getReader() throws IOException { if (getEncoding() == null) { return new InputStreamReader(getInputStream()); } else { return new InputStreamReader(getInputStream(), getEncoding()); } } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getReader(java.lang.String) */ public Reader getReader(String newEncoding) throws IOException { if ((newEncoding == null) || newEncoding.equals("")) { return getReader(); } else { return new InputStreamReader(getInputStream(), newEncoding); } } protected String getResolvedName() { return resolvedName; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getType() */ public String getType() { if (getName() == null) { return ""; } return FileTools.getExtension(new File(getName())); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getTypedName() */ public String getTypedName() { if (getName() == null) { return ""; } return new File(getName()).getName(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getWriter() */ public Writer getWriter() throws IOException { throw new IOException("locator is read only"); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#getWriter(java.lang.String) */ public Writer getWriter(String pEncoding) throws IOException { throw new IOException("locator is read only"); } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return getResolvedName().hashCode(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#isDirectory() */ public boolean isDirectory() { return false; } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#isOutOfSynch() */ public boolean isOutOfSynch() { return false; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#isReadOnly() */ @Override public boolean isReadOnly() { return true; } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#isSynchSynchronous() */ public boolean isSynchSynchronous() { return false; } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#listLocators(de.intarsys.tools.locator.ILocatorNameFilter) */ public ILocator[] listLocators(final ILocatorNameFilter filter) throws IOException { return new ILocator[0]; } /** * ..this is borrowed partially from java.lang.Class. * * @param pName * The name to resolve. * * @return The resolved name. */ private String resolveName(String pName) { if (pName == null) { return pName; } if (!pName.startsWith("/")) { Class c = getClazz(); while (c.isArray()) { c = c.getComponentType(); } String baseName = c.getName(); int index = baseName.lastIndexOf('.'); if (index != -1) { pName = "/" + baseName.substring(0, index).replace('.', '/') + "/" + pName; } } return pName; } protected void setEncoding(String encoding) { this.encoding = encoding; } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#synch() */ public void synch() { // do nothing } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return getResolvedName(); } /* * (non-Javadoc) * * @see de.intarsys.tools.locator.ILocator#toURL() */ public URL toURL() { return null; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/DelegatingLocator.java0000644000175000017500000001231511411055574026711 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locator; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.URL; import de.intarsys.tools.adapter.AdapterTools; import de.intarsys.tools.adapter.IAdapterSupport; import de.intarsys.tools.randomaccess.IRandomAccess; /** * An adapter for implementing a delegation model. * */ abstract public class DelegatingLocator implements ILocator, IAdapterSupport { protected ILocator delegate; public DelegatingLocator(ILocator delegate) { super(); this.delegate = delegate; } public void delete() throws IOException { getDelegate().delete(); } public boolean exists() { try { return getDelegate().exists(); } catch (IOException e) { return false; } } public T getAdapter(Class clazz) { try { return AdapterTools.getAdapter(getDelegate(), clazz); } catch (IOException e) { return null; } } public ILocator getChild(String name) { try { return getDelegate().getChild(name); } catch (IOException e) { return null; } } public ILocator getDelegate() throws IOException { return delegate; } public String getFullName() { try { return getDelegate().getFullName(); } catch (IOException e) { return ""; } } public InputStream getInputStream() throws IOException { return getDelegate().getInputStream(); } public long getLength() throws IOException { return getDelegate().getLength(); } public String getLocalName() { try { return getDelegate().getLocalName(); } catch (IOException e) { return ""; } } public OutputStream getOutputStream() throws IOException { return getDelegate().getOutputStream(); } public ILocator getParent() { try { return getDelegate().getParent(); } catch (IOException e) { return null; } } public IRandomAccess getRandomAccess() throws IOException { return getDelegate().getRandomAccess(); } public Reader getReader() throws IOException { return getDelegate().getReader(); } public Reader getReader(String encoding) throws IOException { return getDelegate().getReader(encoding); } public String getType() { try { return getDelegate().getType(); } catch (IOException e) { return ""; } } public String getTypedName() { try { return getDelegate().getTypedName(); } catch (IOException e) { return ""; } } public Writer getWriter() throws IOException { return getDelegate().getWriter(); } public Writer getWriter(String encoding) throws IOException { return getDelegate().getWriter(encoding); } public boolean isDirectory() { try { return getDelegate().isDirectory(); } catch (IOException e) { return false; } } public boolean isOutOfSynch() { try { return getDelegate().isOutOfSynch(); } catch (IOException e) { return false; } } public boolean isReadOnly() { try { return getDelegate().isReadOnly(); } catch (IOException e) { return true; } } public ILocator[] listLocators(ILocatorNameFilter filter) throws IOException { return getDelegate().listLocators(filter); } public void rename(String newName) throws IOException { getDelegate().rename(newName); } public void setReadOnly() { try { getDelegate().setReadOnly(); } catch (IOException e) { // } } public void synch() { try { getDelegate().synch(); } catch (IOException e) { // } } public URL toURL() { try { return getDelegate().toURL(); } catch (IOException e) { return null; } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/ILocator.java0000644000175000017500000001767411222634260025046 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locator; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.URL; import de.intarsys.tools.component.ISynchronizable; import de.intarsys.tools.randomaccess.IRandomAccess; /** * The locator specifies the physical location of a resource. *

*/ public interface ILocator extends ISynchronizable { /** * Delete the artifact referenced by this. * * @throws IOException */ public void delete() throws IOException; /** * Answer true if the location designated by this exists. * * @return Answer true if the location designated by this * exists. */ public boolean exists(); /** * The locator for the resource name within the context of * this. This may for example be an {@link ILocator} to a file within a * directory. * * @param name * The name of the resource to be located. * * @return The {@link ILocator} for the resource with the name "name" within * the context of this. */ public ILocator getChild(String name); /** * The full physical name of this. * *

* This method returns a representation that is proprietary to the * underlying physical representation, for example a file name, a SQL * statement or so on. *

* * @return The full physical name of the receiver. */ public String getFullName(); /** * Return an {@link InputStream} on the data represented by the receiver. * * @return An {@link InputStream} on the data represented by the receiver. * * @throws IOException */ public InputStream getInputStream() throws IOException; /** * Returns the length of this data container or -1 if unknown * * @return the length of this data container, measured in bytes. * @exception IOException * if an I/O error occurs. */ public long getLength() throws IOException; /** * The local name of the receiver within its parent. * * @return The local name of the receiver within its parent. */ public String getLocalName(); /** * Return an {@link OutputStream} on the location represented by the * receiver. * * @return An {@link OutputStream} on the location represented by the * receiver. * * @throws IOException */ public OutputStream getOutputStream() throws IOException; /** * The {@link ILocator} that is one hierarchy level up or null. This may be * for example the directory where the currently designated resource is * found. * * @return The {@link ILocator}that is one hierarchy level up or null. */ public ILocator getParent(); /** * The {@link IRandomAccess} for this. * * @return The {@link IRandomAccess} for this. * @throws IOException */ public IRandomAccess getRandomAccess() throws IOException; /** * A {@link Reader} on the data represented by the receiver. * * @return A {@link Reader} on the data represented by the receiver. * * @throws IOException */ public Reader getReader() throws IOException; /** * A {@link Reader} on the data represented by the receiver for the given * encoding. * * @param encoding * The encoding. * * @return A {@link Reader} on the data represented by the receiver for the * given encoding. * * @throws IOException */ public Reader getReader(String encoding) throws IOException; /** * The type of the resource. This may be for example a mime type or the file * extension of the underlying file. * * @return The type of the resource */ public String getType(); /** * The qualified local name of the receiver within its parent that includes * the type specification for the destination if appropriate. This is for * example a filename with its correct suffix. Some locator may return the * same name as "getLocalName". * * @return The qualified local name of the receiver within its parent that * includes the type specification for the destination if * appropriate. */ public String getTypedName(); /** * A {@link Writer} on the location represented by the receiver. * * @return A {@link Writer} on the location represented by the receiver. * * @throws IOException */ public Writer getWriter() throws IOException; /** * A {@link Writer} on the location represented by the receiver for the * given encoding. * * @param encoding * The encoding. * * @return A {@link Writer} on the location represented by the receiver for * the given encoding. * * @throws IOException */ public Writer getWriter(String encoding) throws IOException; /** * Answer true if the location designated by this is a * directory. A directory location serves as a container for other * resources, you can never getInputStream on this. * * @return Answer true if the location designated by this is * a directory. */ public boolean isDirectory(); /** * true if the specified resource is read only. * * @return true if the specified resource is read only. */ public boolean isReadOnly(); /** * Return an array of {@link ILocator} that are children of the receiver * that conform to filter. This method never returns null. * * @param filter * The filter used to examine the child resources. * * @return An array of {@link ILocator} objects that conform to the filter * argument. * * @throws IOException */ public ILocator[] listLocators(ILocatorNameFilter filter) throws IOException; /** * Rename the complete physical name to newName. * * @param newName * The new name of the {@link ILocator}. The new name is * expected to contain both local and type part of the name. * @throws IOException */ public void rename(String newName) throws IOException; /** * Make the receiver read only. This is a one way switch only. */ public void setReadOnly(); /** * The location designated by this as an {@link URL}. * * @return The location designated by this as an {@link URL}. */ public URL toURL(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/locator/LocatorByReference.java0000644000175000017500000001101011222634260027021 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locator; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.URL; import de.intarsys.tools.adapter.AdapterTools; import de.intarsys.tools.adapter.IAdapterSupport; import de.intarsys.tools.randomaccess.IRandomAccess; /** * This {@link ILocator} serves as an adapter for an {@link ILocatorSupport} * instance. */ public class LocatorByReference implements ILocator, IAdapterSupport { private ILocatorSupport locatorSupport; public LocatorByReference(ILocatorSupport locatorSupport) { super(); this.locatorSupport = locatorSupport; } public void delete() throws IOException { getLocator().delete(); } public boolean exists() { return getLocator().exists(); } public T getAdapter(Class clazz) { return AdapterTools.getAdapter(getLocator(), clazz); } public ILocator getChild(String name) { return getLocator().getChild(name); } public String getFullName() { return getLocator().getFullName(); } public InputStream getInputStream() throws IOException { return getLocator().getInputStream(); } public long getLength() throws IOException { return getLocator().getLength(); } public String getLocalName() { return getLocator().getLocalName(); } protected ILocator getLocator() { return locatorSupport.getLocator(); } public ILocatorSupport getLocatorSupport() { return locatorSupport; } public OutputStream getOutputStream() throws IOException { return getLocator().getOutputStream(); } public ILocator getParent() { return getLocator().getParent(); } public IRandomAccess getRandomAccess() throws IOException { return getLocator().getRandomAccess(); } public Reader getReader() throws IOException { return getLocator().getReader(); } public Reader getReader(String encoding) throws IOException { return getLocator().getReader(encoding); } public String getType() { return getLocator().getType(); } public String getTypedName() { return getLocator().getTypedName(); } public Writer getWriter() throws IOException { return getLocator().getWriter(); } public Writer getWriter(String encoding) throws IOException { return getLocator().getWriter(encoding); } public boolean isDirectory() { return getLocator().isDirectory(); } public boolean isOutOfSynch() { return getLocator().isOutOfSynch(); } public boolean isReadOnly() { return getLocator().isReadOnly(); } public ILocator[] listLocators(ILocatorNameFilter filter) throws IOException { return getLocator().listLocators(filter); } public void rename(String newName) throws IOException { getLocator().rename(newName); } public void setReadOnly() { getLocator().setReadOnly(); } public void synch() { getLocator().synch(); } public URL toURL() { return getLocator().toURL(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/lang/0000755000175000017500000000000011412336332021726 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/lang/LangTools.java0000644000175000017500000000040111037063022024462 0ustar twernertwernerpackage de.intarsys.tools.lang; public class LangTools { static public boolean equals(Object a, Object b) { if (a == null && b == null) { return true; } if (a == null && b != null) { return false; } return a.equals(b); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/lang/BooleanTools.java0000644000175000017500000000035411335525232025176 0ustar twernertwernerpackage de.intarsys.tools.lang; public class BooleanTools { static public String toStringThreeState(Boolean value) { if (value == null) { return "?"; } if (value) { return "true"; } return "false"; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/logging/0000755000175000017500000000000011412336332022433 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/logging/MemoryLogHandler.java0000644000175000017500000000611311253414464026515 0ustar twernertwernerpackage de.intarsys.tools.logging; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import de.intarsys.tools.event.AttributeChangedEvent; import de.intarsys.tools.event.Event; import de.intarsys.tools.event.EventDispatcher; import de.intarsys.tools.event.EventType; import de.intarsys.tools.event.INotificationListener; import de.intarsys.tools.event.INotificationSupport; public class MemoryLogHandler extends Handler implements INotificationSupport { private final static int DEFAULT_SIZE = 1000; private int size; private String id; private LogRecord buffer[]; private int start, count; private EventDispatcher dispatcher = new EventDispatcher(this); public MemoryLogHandler() { init(); } public MemoryLogHandler(String id, int size) { if (size <= 0) { throw new IllegalArgumentException(); } this.size = size; this.id = id; init(); } public void addNotificationListener(EventType type, INotificationListener listener) { dispatcher.addNotificationListener(type, listener); } public synchronized void clear() { buffer = new LogRecord[size]; start = 0; count = 0; triggerChanged(null, null, null); } @Override public void close() throws SecurityException { buffer = null; setLevel(Level.OFF); } @Override public void flush() { } public String getId() { return id; } synchronized public LogRecord[] getLogRecords() { LogRecord[] result = new LogRecord[count]; System.arraycopy(buffer, start, result, 0, count); return result; } synchronized public int getSize() { return size; } public String getString() { StringBuilder sb = new StringBuilder(); LogRecord[] records = getLogRecords(); for (int i = 0; i < records.length; i++) { LogRecord record = records[i]; try { sb.append(getFormatter().format(record)); } catch (Exception ex) { // } } return sb.toString(); } private void init() { setFormatter(new SimpleFormatter()); size = DEFAULT_SIZE; buffer = new LogRecord[size]; start = 0; count = 0; } @Override public synchronized void publish(LogRecord record) { if (!isLoggable(record)) { return; } int ix = (start + count) % buffer.length; buffer[ix] = record; if (count < buffer.length) { count++; } else { start++; } triggerChanged(null, null, record); } public void removeNotificationListener(EventType type, INotificationListener listener) { dispatcher.removeNotificationListener(type, listener); } public void setId(String id) { this.id = id; } synchronized public void setSize(int size) { // todo... this.size = size; } protected void triggerChanged(Object attribute, Object oldValue, Object newValue) { Event event = new AttributeChangedEvent(this, attribute, oldValue, newValue); triggerEvent(event); } protected void triggerEvent(Event event) { try { dispatcher.triggerEvent(event); } catch (RuntimeException e) { // ignore } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/logging/SimpleFormatter.java0000644000175000017500000001702511411055574026425 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.logging; import java.io.PrintWriter; import java.io.StringWriter; import java.text.Format; import java.util.Calendar; import java.util.Date; import java.util.logging.Formatter; import java.util.logging.LogManager; import java.util.logging.LogRecord; import de.intarsys.tools.format.TrivialDateFormat; import de.intarsys.tools.string.StringTools; /** * A simple usable formatter for java logging */ public class SimpleFormatter extends Formatter { /** The line separator. */ private static final String LF = System.getProperty("line.separator"); static { // force classloading - strange problems may arise when logging within // classloader new TrivialDateFormat(); StringTools.isEmpty(""); Calendar.getInstance(); SDC.get(); } /** A thread safe date format. */ private Format dateFormat = new TrivialDateFormat(); /** The StringBuffer to format the message (this is not thread safe). */ private final StringBuffer sb = new StringBuffer(); private int widthSDC = 20; private boolean showDate = true; private boolean showLevel = true; private boolean showName = true; private boolean showSDC = false; private boolean showThread = true; private int widthLevel = 7; private int widthName = 30; private int widthThread = 15; /** * */ public SimpleFormatter() { super(); configure(); } protected void configure() { String cname = getClass().getName(); setShowSDC(getBooleanProperty(cname + ".sdc.show", isShowSDC())); setWidthSDC(getIntProperty(cname + ".sdc.width", getWidthSDC())); setShowThread(getBooleanProperty(cname + ".thread.show", isShowThread())); setWidthThread(getIntProperty(cname + ".thread.width", getWidthThread())); setShowDate(getBooleanProperty(cname + ".date.show", isShowDate())); setShowLevel(getBooleanProperty(cname + ".level.show", isShowLevel())); setWidthLevel(getIntProperty(cname + ".level.width", getWidthLevel())); setShowName(getBooleanProperty(cname + ".name.show", isShowName())); setWidthName(getIntProperty(cname + ".name.width", getWidthName())); } @Override public synchronized String format(LogRecord record) { sb.setLength(0); if (isShowDate()) { sb.append("["); int index = sb.length(); dateFormat.format(new Date(record.getMillis()), sb, null); for (int i = sb.length() - index; i < 24; i++) { sb.append(' '); } sb.append("]"); } if (isShowLevel()) { sb.append("["); String levelString = record.getLevel().toString(); sb.append(levelString); for (int i = levelString.length(); i < widthLevel; i++) { sb.append(' '); } sb.append("]"); } if (isShowName()) { String loggerString = record.getLoggerName(); if (loggerString == null) { loggerString = ""; } if (loggerString.length() > widthName) { loggerString = StringTools.getTrailing(loggerString, widthName); } sb.append("["); sb.append(loggerString); for (int i = loggerString.length(); i < widthName; i++) { sb.append(' '); } sb.append("]"); } if (isShowThread()) { String threadString = Thread.currentThread().getName(); if (threadString.length() > widthThread) { threadString = StringTools.getTrailing(threadString, widthThread); } sb.append("["); sb.append(threadString); for (int i = threadString.length(); i < widthThread; i++) { sb.append(' '); } sb.append("]"); } if (isShowSDC()) { sb.append("["); String sdcString = String.valueOf(SDC.get()); sb.append(sdcString); for (int i = sdcString.length(); i < widthSDC; i++) { sb.append(' '); } sb.append("]"); } sb.append(" "); sb.append(record.getMessage()); sb.append(LF); if (record.getThrown() != null) { try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); record.getThrown().printStackTrace(pw); pw.close(); sb.append(sw.toString()); sb.append(LF); } catch (Exception ex) { // ignore } } return sb.toString(); } protected boolean getBooleanProperty(String name, boolean defaultValue) { LogManager manager = LogManager.getLogManager(); String property = manager.getProperty(name); if (StringTools.isEmpty(property)) { return defaultValue; } return Boolean.valueOf(property.trim()); } protected int getIntProperty(String name, int defaultValue) { LogManager manager = LogManager.getLogManager(); String property = manager.getProperty(name); if (StringTools.isEmpty(property)) { return defaultValue; } try { return Integer.valueOf(property.trim()); } catch (NumberFormatException e) { return defaultValue; } } public int getWidthLevel() { return widthLevel; } public int getWidthName() { return widthName; } public int getWidthSDC() { return widthSDC; } public int getWidthThread() { return widthThread; } public boolean isShowDate() { return showDate; } public boolean isShowLevel() { return showLevel; } public boolean isShowName() { return showName; } public boolean isShowSDC() { return showSDC; } public boolean isShowThread() { return showThread; } public void setShowDate(boolean showDate) { this.showDate = showDate; } public void setShowLevel(boolean showLevel) { this.showLevel = showLevel; } public void setShowName(boolean showName) { this.showName = showName; } public void setShowSDC(boolean showSDC) { this.showSDC = showSDC; } public void setShowThread(boolean showThread) { this.showThread = showThread; } public void setWidthLevel(int widthLevel) { this.widthLevel = widthLevel; } public void setWidthName(int widthLoggername) { this.widthName = widthLoggername; } public void setWidthSDC(int widthSDC) { this.widthSDC = widthSDC; } public void setWidthThread(int widthThread) { this.widthThread = widthThread; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/logging/IDumpObject.java0000644000175000017500000000025711341001604025437 0ustar twernertwernerpackage de.intarsys.tools.logging; import java.util.List; public interface IDumpObject { List dump(String prefix, Object object, IDumpObject details); } libisrt-java-4.8.20100629/src/de/intarsys/tools/logging/ILogConfigurator.java0000644000175000017500000000360411173336064026524 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.logging; import java.util.logging.Logger; /** * Classes implementing this interface can be used in conjunction with the * singleton LogConfigurator to configure Logger instances created by the class * LogTools. * */ public interface ILogConfigurator { public void configure(Logger logger); } libisrt-java-4.8.20100629/src/de/intarsys/tools/logging/LogTools.java0000644000175000017500000001025611411055574025051 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.logging; import java.io.IOException; import java.util.List; import java.util.logging.FileHandler; import java.util.logging.Handler; import java.util.logging.Logger; /** * Tool methods to ease life with java.util.logging. * */ public class LogTools { private static IDumpObject DumpObject; public static final String INDENT = " "; //$NON-NLS-1$ static { DumpObject = new CommonDumpObject(); } /** * Closes a fileLogger. */ public static void closeFileLogger(Logger logger) { Handler[] handlers = logger.getHandlers(); for (int i = 0; i < handlers.length; i++) { handlers[i].close(); } } /** * Creates a fileLogger. * * @return A Logger named with 'id'. * @throws IOException * @throws SecurityException */ public static Logger createFileLogger(String id, String filePattern, boolean append) throws SecurityException, IOException { Logger logger = Logger.getLogger(id); Handler handler = new FileHandler(filePattern, append); logger.addHandler(handler); return logger; } static public List dumpObject(String prefix, Object object) { return dumpObject(prefix, object, DumpObject); } static public List dumpObject(String prefix, Object object, IDumpObject details) { return DumpObject.dump(prefix, object, details); } /** * Get a logger that corresponds to clazz. * * @param clazz * The class object we want a logger for. * * @return A Logger that corresponds to clazz. */ public static Logger getLogger(Class clazz) { Logger logger = Logger.getLogger(toLoggerName(clazz)); LogConfigurator.get().configure(logger); return logger; } /** * Get a logger for name name. * * @param name * The logger name/category * * @return Get a logger for name name. */ public static Logger getLogger(String name) { Logger logger = Logger.getLogger(name); LogConfigurator.get().configure(logger); return logger; } /** * The name we want to use for a logger used in clazz. This * implementation uses the package name. * * @param clazz * The class object we want a name for. * * @return The name we want to use for a logger used in clazz. */ public static String toLoggerName(Class clazz) { String result = clazz.getName(); int index = result.lastIndexOf('.'); if (index > -1) { result = result.substring(0, index); } return result; } /** * */ private LogTools() { // tool class } } libisrt-java-4.8.20100629/src/de/intarsys/tools/logging/SDC.java0000644000175000017500000000051511267270550023717 0ustar twernertwernerpackage de.intarsys.tools.logging; public class SDC { final static private ThreadLocal message = new ThreadLocal(); static public void clear() { message.remove(); } static public String get() { return message.get(); } static public void set(String value) { message.set(value); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/logging/LogConfigurator.java0000644000175000017500000000440611173336064026414 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.logging; import java.util.logging.Logger; /** * Singleton holding a ILogConfigurator instance. The ILogConfigurator instance * is used to configure all Logger instances created by the LogTools class. */ public class LogConfigurator { static class DefaultConfigurator implements ILogConfigurator { public void configure(Logger logger) { // } } private static ILogConfigurator INSTANCE; public static ILogConfigurator get() { if (INSTANCE == null) { INSTANCE = new DefaultConfigurator(); } return INSTANCE; } public static void set(ILogConfigurator configurator) { INSTANCE = configurator; } private LogConfigurator() { // } } libisrt-java-4.8.20100629/src/de/intarsys/tools/logging/SingleThreadFilter.java0000644000175000017500000000102211267270550027017 0ustar twernertwernerpackage de.intarsys.tools.logging; import java.util.logging.Filter; import java.util.logging.LogRecord; /** * Only accept log requests within a dedicated thread. * */ public class SingleThreadFilter implements Filter { final private Thread thread; public SingleThreadFilter() { this(Thread.currentThread()); } public SingleThreadFilter(Thread thread) { super(); this.thread = thread; } public boolean isLoggable(LogRecord record) { return thread == Thread.currentThread(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/logging/CommonDumpObject.java0000644000175000017500000000411611365617106026515 0ustar twernertwernerpackage de.intarsys.tools.logging; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import de.intarsys.tools.hex.HexTools; import de.intarsys.tools.string.StringTools; import de.intarsys.tools.valueholder.IValueHolder; public class CommonDumpObject implements IDumpObject { public List dump(String prefix, Object object, IDumpObject details) { List result = new ArrayList(); if (object instanceof byte[]) { String hex; byte[] array = (byte[]) object; if (array.length > 50) { // arbitrary hex = HexTools.bytesToHexString(array, 0, 49) + "..."; //$NON-NLS-1$ } else { hex = HexTools.bytesToHexString(array); } result.add(prefix + "byte[" + array.length + "] " + hex); //$NON-NLS-1$ //$NON-NLS-2$ } else if (object instanceof char[]) { result.add(prefix + "a character array"); //$NON-NLS-1$ } else if (object instanceof IValueHolder) { IValueHolder ref = (IValueHolder) object; List attrValue = details.dump("", ref.get(), details); //$NON-NLS-1$ Iterator it = attrValue.iterator(); result.add(prefix + "a reference to " + it.next()); //$NON-NLS-1$ while (it.hasNext()) { result.add(prefix + it.next()); } } else if (object instanceof Object[]) { Object[] array = (Object[]) object; result.add(prefix + "["); //$NON-NLS-1$ for (Object element : array) { result.addAll(details.dump(prefix + LogTools.INDENT, element, details)); } result.add(prefix + "]"); //$NON-NLS-1$ } else if (object instanceof int[]) { int[] array = (int[]) object; result.add(prefix + Arrays.toString(array)); } else if (object instanceof Integer) { int i = (Integer) object; result.add(prefix + i + " | 0x" + Integer.toHexString(i)); //$NON-NLS-1$ } else if (object instanceof Byte) { byte i = (Byte) object; result.add(prefix + i + " | 0x" + Integer.toHexString(i)); //$NON-NLS-1$ } else { result.add(prefix + StringTools.safeString(object)); } return result; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/logging/TaggedThreadFilter.java0000644000175000017500000000112511267270550026775 0ustar twernertwernerpackage de.intarsys.tools.logging; import java.util.logging.Filter; import java.util.logging.LogRecord; /** * Only accept log requests within threads that are tagged with the receiver * object. * */ public class TaggedThreadFilter implements Filter { final private ThreadLocal tag = new ThreadLocal(); public TaggedThreadFilter() { // } public void activate() { tag.set(this); } public void deactivate() { tag.remove(); } public boolean isLoggable(LogRecord record) { return this == tag.get(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/logging/MemoryLogRegistry.java0000644000175000017500000000136411175377374026766 0ustar twernertwernerpackage de.intarsys.tools.logging; import java.util.HashMap; import java.util.Map; public class MemoryLogRegistry { final private static MemoryLogRegistry ACTIVE = new MemoryLogRegistry(); public static MemoryLogRegistry get() { return ACTIVE; } final private Map handlers = new HashMap(); public MemoryLogHandler[] getHandlers() { return (MemoryLogHandler[]) handlers.values().toArray(); } public MemoryLogHandler lookup(String id) { return handlers.get(id); } public void register(MemoryLogHandler handler) { handlers.put(handler.getId(), handler); } public void unregister(MemoryLogHandler handler) { handlers.remove(handler.getId()); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/format/0000755000175000017500000000000011412336332022275 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/format/TrivialDateFormat.java0000644000175000017500000001066611216472212026532 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.format; import java.text.FieldPosition; import java.text.Format; import java.text.ParsePosition; import java.util.Calendar; import java.util.Date; /** * A thread safe, quite trivial formatter for date/calendar objects. */ public class TrivialDateFormat extends Format { /** * The default instance * * @return The default instance */ public static TrivialDateFormat getInstance() { return new TrivialDateFormat(); } /** * Thread specific calendar instances. * */ private ThreadLocal calendar = new ThreadLocal() { @Override protected Object initialValue() { return Calendar.getInstance(); } }; /** * Create a TrivialDateFormat */ public TrivialDateFormat() { super(); } /* * (non-Javadoc) * * @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, * java.text.FieldPosition) */ @Override public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { Calendar theCalendar; if (obj instanceof Date) { theCalendar = (Calendar) calendar.get(); theCalendar.setTime((Date) obj); } else if (obj instanceof Calendar) { theCalendar = (Calendar) obj; } else if (obj instanceof Long) { theCalendar = (Calendar) calendar.get(); theCalendar.setTime(new Date(((Long) obj).longValue())); } else if (obj instanceof Integer) { theCalendar = (Calendar) calendar.get(); theCalendar.setTime(new Date(((Integer) obj).longValue())); } else { return toAppendTo.append(""); } int value; value = theCalendar.get(Calendar.DAY_OF_MONTH); if (value < 10) { toAppendTo.append("0"); } toAppendTo.append(value); toAppendTo.append("."); value = theCalendar.get(Calendar.MONTH) + 1; if (value < 10) { toAppendTo.append("0"); } toAppendTo.append(value); toAppendTo.append("."); value = theCalendar.get(Calendar.YEAR); toAppendTo.append(value); toAppendTo.append("-"); value = theCalendar.get(Calendar.HOUR_OF_DAY); if (value < 10) { toAppendTo.append("0"); } toAppendTo.append(value); toAppendTo.append(":"); value = theCalendar.get(Calendar.MINUTE); if (value < 10) { toAppendTo.append("0"); } toAppendTo.append(value); toAppendTo.append(":"); value = theCalendar.get(Calendar.SECOND); if (value < 10) { toAppendTo.append("0"); } toAppendTo.append(value); toAppendTo.append(":"); value = theCalendar.get(Calendar.MILLISECOND); if (value < 10) { toAppendTo.append("0"); } if (value < 100) { toAppendTo.append("0"); } toAppendTo.append(value); return toAppendTo; } /* * (non-Javadoc) * * @see java.text.Format#parseObject(java.lang.String, * java.text.ParsePosition) */ @Override public Object parseObject(String source, ParsePosition status) { return null; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/format/TrivialIntegerFormat.java0000644000175000017500000000545110751651500027250 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.format; import java.text.FieldPosition; import java.text.Format; import java.text.ParsePosition; /** * A thread safe, quite trivial formatter for integer numbers */ public class TrivialIntegerFormat extends Format { /** * The default instance * * @return The default instance */ public static TrivialIntegerFormat getInstance() { return new TrivialIntegerFormat(); } /** * Create a TrivialIntegerFormat */ public TrivialIntegerFormat() { super(); } /* * (non-Javadoc) * * @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, * java.text.FieldPosition) */ @Override public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { if (obj instanceof Long) { toAppendTo.append(((Long) obj).longValue()); } else if (obj instanceof Integer) { toAppendTo.append(((Integer) obj).intValue()); } else { return toAppendTo.append(""); } return toAppendTo; } /* * (non-Javadoc) * * @see java.text.Format#parseObject(java.lang.String, * java.text.ParsePosition) */ @Override public Object parseObject(String source, ParsePosition status) { return null; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/format/ISO8601Format.java0000644000175000017500000000127311144006260025261 0ustar twernertwernerpackage de.intarsys.tools.format; import java.text.SimpleDateFormat; import java.util.Date; public class ISO8601Format { private final SimpleDateFormat formater; private static final ISO8601Format Instance = new ISO8601Format(); public static final ISO8601Format getInstance() { return Instance; } protected ISO8601Format() { formater = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //$NON-NLS-1$ } public String format(Date date) { String partial = formater.format(date); partial = partial.replaceAll("\\+0000$", "Z"); //$NON-NLS-1$//$NON-NLS-2$ partial = partial.replaceAll("(\\d\\d)$", ":$1"); //$NON-NLS-1$//$NON-NLS-2$ return partial; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/exception/0000755000175000017500000000000011412336332023003 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/exception/TunnelingException.java0000644000175000017500000000366510751651476027520 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.exception; /** * A message to enable tunneling through signatures that allow for runtime * exceptions only. */ public class TunnelingException extends RuntimeException { public TunnelingException(String message, Throwable cause) { super(message, cause); } public TunnelingException(Throwable cause) { super(cause.getMessage(), cause); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/exception/KnownReason.java0000644000175000017500000000443211174340230026112 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.exception; /** * An exception that may be used to indicate that an exceptional condition is * "expected" in the sense that you will need no further tools to investigate * the reason, such as a stack trace. *

* Such exceptions may be a timeout or a user initiated cancel. *

* In conjunction with {@link ExceptionTools} you can search an exception chain * for "known reasons". */ public class KnownReason extends RuntimeException { public KnownReason() { super(); } public KnownReason(String message) { super(message); } public KnownReason(String message, Throwable cause) { super(message, cause); } public KnownReason(Throwable cause) { super(cause); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/exception/ExceptionTools.java0000644000175000017500000000773411174340230026635 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.exception; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; /** * Tool class for dealing with Exceptions. */ public class ExceptionTools { static public IOException createIOException(String message, Throwable cause) { IOException ioe = new IOException(message); ioe.initCause(cause); return ioe; } /** * Simply fail with a {@link RuntimeException}. */ public static void fail() { throw new RuntimeException("failed"); //$NON-NLS-1$ } public static T futureSimpleGet(Future future) { try { return future.get(); } catch (InterruptedException e) { // TODO return null; } catch (ExecutionException ex) { if (ex.getCause() instanceof Error) { throw (Error) ex.getCause(); } if (ex.getCause() instanceof RuntimeException) { throw (RuntimeException) ex.getCause(); } throw new InternalError( "Program execution should not reach this point."); } } public static T futureSimpleGetNumber(Future future) { T result = futureSimpleGet(future); if (result == null) { result = (T) new Integer(-1); } return result; } static public Throwable getInChain(Throwable t, Class clazz) { if (clazz.isInstance(t)) { return t; } if (t.getCause() != null) { return getInChain(t.getCause(), clazz); } return null; } /** * The root cause of t. * * @param t * A {@link Throwable}. * @return The most inner cause of t. */ static public Throwable getRoot(Throwable t) { Throwable root = t; while (root.getCause() != null) { root = root.getCause(); } return root; } static public String getStackTraceString(Throwable t) { StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); return sw.toString(); } static public boolean isInChain(Throwable t, Class clazz) { if (clazz.isInstance(t)) { return true; } if (t.getCause() != null) { return isInChain(t.getCause(), clazz); } return false; } public static boolean isKnownReason(Throwable t) { if (t instanceof KnownReason) { return true; } Throwable cause = t.getCause(); if (cause != null) { return isKnownReason(cause); } return false; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/variable/0000755000175000017500000000000011412336332022572 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/variable/VariableNamespaces.java0000644000175000017500000000354011035463704027171 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.variable; public class VariableNamespaces { private static IVariableNamespaces ACTIVE = new StandardVariableNamespaces(); static public IVariableNamespaces get() { return ACTIVE; } static public void set(IVariableNamespaces active) { ACTIVE = active; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/variable/IVariableNamespace.java0000644000175000017500000000646411105015676027126 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.variable; import java.util.Iterator; import java.util.Map; /** * This defines the ability of a component to support generic key/value mappings * from string to string. *

* Variables are used most often for string replacements. You should not use * this feature for parameter or attribute passing between components. * */ public interface IVariableNamespace { /** * The string variable stored with key. * * @param key * The name of the string variable * * @return The string variable stored with key. */ public String getVariable(String key); /** * The string variable stored with key or * defaultValue if the result would be null. * * @param key * The name of the string variable * @param defaultValue * The value to use if result would be null * * @return The string variable stored with key or * defaultValue if the result would be * null. */ public String getVariable(String key, String defaultValue); /** * An iterator over the entries (Map.Entry) of the Map. * * @return An iterator over the entries (Map.Entry) of the Map. */ public Iterator getVariableIterator(); /** * The map holding the assoications from names to values. * * @return The map holding the assoications from names to values. */ public Map getVariables(); /** * Enter a name/value binding in the map. * * @param key * The name of the string variable * @param value * The value to use for the variable. */ public void putVariable(String key, String value); } libisrt-java-4.8.20100629/src/de/intarsys/tools/variable/StandardVariableNamespaces.java0000644000175000017500000000422611105015676030653 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.variable; import java.util.HashMap; import java.util.Map; public class StandardVariableNamespaces implements IVariableNamespaces { private Map namespaces = new HashMap(); synchronized public String[] getNames() { return namespaces.keySet().toArray(new String[namespaces.size()]); } synchronized public IVariableNamespace getNamespace(String id) { return namespaces.get(id); } synchronized public void setNamespace(String id, IVariableNamespace namespace) { namespaces.put(id, namespace); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/variable/IVariableNamespaces.java0000644000175000017500000000343411035463704027304 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.variable; public interface IVariableNamespaces { public String[] getNames(); public IVariableNamespace getNamespace(String id); public void setNamespace(String id, IVariableNamespace namespace); } libisrt-java-4.8.20100629/src/de/intarsys/tools/variable/VariableEnvironment.java0000644000175000017500000000457511035463704027427 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.variable; /** * A environment that allows per thread usage of IVariableSupport objects. * */ public class VariableEnvironment { protected static IVariableNamespace sharedEnvironment = null; protected static ThreadLocal environment = new ThreadLocal() { protected Object initialValue() { return getShared(); } }; public static IVariableNamespace get() { return (IVariableNamespace) environment.get(); } synchronized public static IVariableNamespace getShared() { if (sharedEnvironment == null) { sharedEnvironment = new StandardVariableNamespace(); } return sharedEnvironment; } public static void set(IVariableNamespace cc) { environment.set(cc); } synchronized public static void setShared(IVariableNamespace cc) { sharedEnvironment = cc; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/variable/StandardVariableNamespace.java0000644000175000017500000000610311105015676030464 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.variable; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import de.intarsys.tools.collection.EmptyIterator; /** * A general implementation for an object providing {@link IVariableNamespace}. * */ public class StandardVariableNamespace implements IVariableNamespace { private Map variables; /** * Create a VariableScope * */ public StandardVariableNamespace() { super(); } synchronized public String getVariable(String key) { if (variables == null) { return null; } return (String) variables.get(key); } synchronized public String getVariable(String key, String defaultValue) { if (variables == null) { return defaultValue; } String result = (String) variables.get(key); if (result == null) { return defaultValue; } else { return (String) variables.get(key); } } synchronized public Iterator getVariableIterator() { if (variables == null) { return EmptyIterator.UNIQUE; } return new HashMap(variables).entrySet().iterator(); } synchronized public Map getVariables() { if (variables == null) { variables = new HashMap(); } return new HashMap(variables); } synchronized public void putVariable(String key, String value) { if (variables == null) { variables = new HashMap(); } variables.put(key, value); } synchronized public void putVariables(Map v) { if (variables == null) { variables = new HashMap(); } variables.putAll(v); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/currency/0000755000175000017500000000000011412336332022637 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/currency/Iso4217.java0000644000175000017500000004002510751651502024557 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.currency; /** * http://www.iso.org/iso/en/prods-services/popstds/currencycodeslist.html * */ public class Iso4217 { public static final int COLUMN_ENTITY = 0; public static final int COLUMN_CURRENCY = 1; public static final int COLUMN_ALPHABETIC = 2; public static final int COLUMN_NUMERIC = 3; public static final String[][] table = new String[][] { // Entity, Currency, Alphabetic-Code, Numeric-Code { "AFGHANISTAN", "Afghani", "AFN", "971" }, { "ALBANIA", "Lek", "ALL", "008" }, { "ALGERIA", "Algerian Dinar", "DZD", "012" }, { "AMERICAN SAMOA", "US Dollar", "USD", "840" }, { "ANDORRA", "Euro", "EUR", "978" }, { "ANGOLA", "Kwanza", "AOA", "973" }, { "ANGUILLA", "East Caribbean Dollar", "XCD", "951" }, { "ANTIGUA AND BARBUDA", "East Caribbean Dollar", "XCD", "951" }, { "ARGENTINA", "Argentine Peso", "ARS", "032" }, { "ARMENIA", "Armenian Dram", "AMD", "051" }, { "ARUBA", "Aruban Guilder", "AWG", "533" }, { "AUSTRALIA", "Australian Dollar", "AUD", "036" }, { "AUSTRIA", "Euro", "EUR", "978" }, { "AZERBAIJAN", "Azerbaijanian Manat", "AZN", "944" }, { "BAHAMAS", "Bahamian Dollar", "BSD", "044" }, { "BAHRAIN", "Bahraini Dinar", "BHD", "048" }, { "BANGLADESH", "Taka", "BDT", "050" }, { "BARBADOS", "Barbados Dollar", "BBD", "052" }, { "BELARUS", "Belarussian Ruble", "BYR", "974" }, { "BELGIUM", "Euro", "EUR", "978" }, { "BELIZE", "Belize Dollar", "BZD", "084" }, { "BENIN", "CFA Franc BCEAO", "XOF", "952" }, { "BERMUDA", "Bermudian Dollar", "BMD", "060" }, { "BHUTAN", "Indian Rupee", "INR", "356" }, { "BHUTAN", "Ngultrum", "BTN", "064" }, { "BOLIVIA", "Boliviano", "BOB", "068" }, { "BOLIVIA", "Mvdol", "BOV", "984" }, { "BOSNIA & HERZEGOVINA", "Convertible Marks", "BAM", "977" }, { "BOTSWANA", "Pula", "BWP", "072" }, { "BOUVET ISLAND", "Norwegian Krone", "NOK", "578" }, { "BRAZIL", "Brazilian Real", "BRL", "986" }, { "BRITISH INDIAN OCEAN TERRITORY", "US Dollar", "USD", "840" }, { "BRUNEI DARUSSALAM", "Brunei Dollar", "BND", "096" }, { "BULGARIA", "Bulgarian Lev", "BGN", "975" }, { "BURKINA FASO", "CFA Franc BCEAO", "XOF", "952" }, { "BURUNDI", "Burundi Franc", "BIF", "108" }, { "CAMBODIA", "Riel", "KHR", "116" }, { "CAMEROON", "CFA Franc BEAC", "XAF", "950" }, { "CANADA", "Canadian Dollar", "CAD", "124" }, { "CAPE VERDE", "Cape Verde Escudo", "CVE", "132" }, { "CAYMAN ISLANDS", "Cayman Islands Dollar", "KYD", "136" }, { "CENTRAL AFRICAN REPUBLIC", "CFA Franc BEAC", "XAF", "950" }, { "CHAD", "CFA Franc BEAC", "XAF", "950" }, { "CHILE", "Chilean Peso", "CLP", "152" }, { "CHILE", "Unidades de formento", "CLF", "990" }, { "CHINA", "Yuan Renminbi", "CNY", "156" }, { "CHRISTMAS ISLAND", "Australian Dollar", "AUD", "036" }, { "COCOS (KEELING) ISLANDS", "Australian Dollar", "AUD", "036" }, { "COLOMBIA", "Colombian Peso", "COP", "170" }, { "COLOMBIA", "Unidad de Valor Real", "COU", "970" }, { "COMOROS", "Comoro Franc", "KMF", "174" }, { "CONGO", "CFA Franc BEAC", "XAF", "950" }, { "CONGO THE DEMOCRATIC REPUBLIC OF", "Franc Congolais", "CDF", "976" }, { "COOK ISLANDS", "New Zealand Dollar", "NZD", "554" }, { "COSTA RICA", "Costa Rican Colon", "CRC", "188" }, { "CÔTE D'IVOIRE", "CFA Franc BCEAO", "XOF", "952" }, { "CROATIA", "Croatian Kuna", "HRK", "191" }, { "CUBA", "Cuban Peso", "CUP", "192" }, { "CYPRUS", "Cyprus Pound", "CYP", "196" }, { "CZECH REPUBLIC", "Czech Koruna", "CZK", "203" }, { "DENMARK", "Danish Krone", "DKK", "208" }, { "DJIBOUTI", "Djibouti Franc", "DJF", "262" }, { "DOMINICA", "East Caribbean Dollar", "XCD", "951" }, { "DOMINICAN REPUBLIC", "Dominican Peso", "DOP", "214" }, { "ECUADOR", "US Dollar", "USD", "840" }, { "EGYPT", "Egyptian Pound", "EGP", "818" }, { "EL SALVADOR", "El Salvador Colon", "SVC", "222" }, { "EL SALVADOR", "US Dollar", "USD", "840" }, { "EQUATORIAL GUINEA", "CFA Franc BEAC", "XAF", "950" }, { "ERITREA", "Nakfa", "ERN", "232" }, { "ESTONIA", "Kroon", "EEK", "233" }, { "ETHIOPIA", "Ethiopian Birr", "ETB", "230" }, { "FALKLAND ISLANDS (MALVINAS)", "Falkland Islands Pound", "FKP", "238" }, { "FAROE ISLANDS", "Danish Krone", "DKK", "208" }, { "FIJI", "Fiji Dollar", "FJD", "242" }, { "FINLAND", "Euro", "EUR", "978" }, { "FRANCE", "Euro", "EUR", "978" }, { "FRENCH GUIANA", "Euro", "EUR", "978" }, { "FRENCH POLYNESIA", "CFP Franc", "XPF", "953" }, { "FRENCH SOUTHERN TERRITORIES", "Euro", "EUR", "978" }, { "GABON", "CFA Franc BEAC", "XAF", "950" }, { "GAMBIA", "Dalasi", "GMD", "270" }, { "GEORGIA", "Lari", "GEL", "981" }, { "GERMANY", "Euro", "EUR", "978" }, { "GHANA", "Cedi", "GHC", "288" }, { "GIBRALTAR", "Gibraltar Pound", "GIP", "292" }, { "GREECE", "Euro", "EUR", "978" }, { "GREENLAND", "Danish Krone", "DKK", "208" }, { "GRENADA", "East Caribbean Dollar", "XCD", "951" }, { "GUADELOUPE", "Euro", "EUR", "978" }, { "GUAM", "US Dollar", "USD", "840" }, { "GUATEMALA", "Quetzal", "GTQ", "320" }, { "GUINEA", "Guinea Franc", "GNF", "324" }, { "GUINEA-BISSAU", "Guinea-Bissau Peso", "GWP", "624" }, { "GUINEA-BISSAU", "CFA Franc BCEAO", "XOF", "952" }, { "GUYANA", "Guyana Dollar", "GYD", "328" }, { "HAITI", "Gourde", "HTG", "332" }, { "HAITI", "US Dollar", "USD", "840" }, { "HEARD ISLAND AND McDONALD ISLANDS", "Australian Dollar", "AUD", "036" }, { "HOLY SEE (VATICAN CITY STATE)", "Euro", "EUR", "978" }, { "HONDURAS", "Lempira", "HNL", "340" }, { "HONG KONG", "Hong Kong Dollar", "HKD", "344" }, { "HUNGARY", "Forint", "HUF", "348" }, { "ICELAND", "Iceland Krona", "ISK", "352" }, { "INDIA", "Indian Rupee", "INR", "356" }, { "INDONESIA", "Rupiah", "IDR", "360" }, { "INTERNATIONAL MONETARY FUND (I.M.F)", "SDR", "XDR", "960" }, { "IRAN (ISLAMIC REPUBLIC OF)", "Iranian Rial", "IRR", "364" }, { "IRAQ", "Iraqi Dinar", "IQD", "368" }, { "IRELAND", "Euro", "EUR", "978" }, { "ISRAEL", "New Israeli Sheqel", "ILS", "376" }, { "ITALY", "Euro", "EUR", "978" }, { "JAMAICA", "Jamaican Dollar", "JMD", "388" }, { "JAPAN", "Yen", "JPY", "392" }, { "JORDAN", "Jordanian Dinar", "JOD", "400" }, { "KAZAKHSTAN", "Tenge", "KZT", "398" }, { "KENYA", "Kenyan Shilling", "KES", "404" }, { "KIRIBATI", "Australian Dollar", "AUD", "036" }, { "KOREA DEMOCRATIC PEOPLE'S REPUBLIC OF", "North Korean Won", "KPW", "408" }, { "KOREA REPUBLIC OF", "Won", "KRW", "410" }, { "KUWAIT", "Kuwaiti Dinar", "KWD", "414" }, { "KYRGYZSTAN", "Som", "KGS", "417" }, { "LAO PEOPLE'S DEMOCRATIC REPUBLIC", "Kip", "LAK", "418" }, { "LATVIA", "Latvian Lats", "LVL", "428" }, { "LEBANON", "Lebanese Pound", "LBP", "422" }, { "LESOTHO", "Rand", "ZAR", "710" }, { "LESOTHO", "Loti", "LSL", "426" }, { "LIBERIA", "Liberian Dollar", "LRD", "430" }, { "LIBYAN ARAB JAMAHIRIYA", "Libyan Dinar", "LYD", "434" }, { "LIECHTENSTEIN", "Swiss Franc", "CHF", "756" }, { "LITHUANIA", "Lithuanian Litas", "LTL", "440" }, { "LUXEMBOURG", "Euro", "EUR", "978" }, { "MACAO", "Pataca", "MOP", "446" }, { "MACEDONIA THE FORMER YUGOSLAV REPUBLIC OF", "Denar", "MKD", "807" }, { "MADAGASCAR", "Malagascy Ariary", "MGA", "969" }, { "MALAWI", "Kwacha", "MWK", "454" }, { "MALAYSIA", "Malaysian Ringgit", "MYR", "458" }, { "MALDIVES", "Rufiyaa", "MVR", "462" }, { "MALI", "CFA Franc BCEAO", "XOF", "952" }, { "MALTA", "Maltese Lira", "MTL", "470" }, { "MARSHALL ISLANDS", "US Dollar", "USD", "840" }, { "MARTINIQUE", "Euro", "EUR", "978" }, { "MAURITANIA", "Ouguiya", "MRO", "478" }, { "MAURITIUS", "Mauritius Rupee", "MUR", "480" }, { "MAYOTTE", "Euro", "EUR", "978" }, { "MEXICO", "Mexican Peso", "MXN", "484" }, { "MEXICO", "Mexican Unidad de Inversion (UID)", "MXV", "979" }, { "MICRONESIA (FEDERATED STATES OF)", "US Dollar", "USD", "840" }, { "MOLDOVA REPUBLIC OF", "Moldovan Leu", "MDL", "498" }, { "MONACO", "Euro", "EUR", "978" }, { "MONGOLIA", "Tugrik", "MNT", "496" }, { "MONTENEGRO", "Euro", "EUR", "978" }, { "MONTSERRAT", "East Caribbean Dollar", "XCD", "951" }, { "MOROCCO", "Moroccan Dirham", "MAD", "504" }, { "MOZAMBIQUE", "Metical", "MZN", "943" }, { "MYANMAR", "Kyat", "MMK", "104" }, { "NAMIBIA", "Rand", "ZAR", "710" }, { "NAMIBIA", "Namibian Dollar", "NAD", "516" }, { "NAURU", "Australian Dollar", "AUD", "036" }, { "NEPAL", "Nepalese Rupee", "NPR", "524" }, { "NETHERLANDS", "Euro", "EUR", "978" }, { "NETHERLANDS ANTILLES", "Netherlands Antillian Guilder", "ANG", "532" }, { "NEW CALEDONIA", "CFP Franc", "XPF", "953" }, { "NEW ZEALAND", "New Zealand Dollar", "NZD", "554" }, { "NICARAGUA", "Cordoba Oro", "NIO", "558" }, { "NIGER", "CFA Franc BCEAO", "XOF", "952" }, { "NIGERIA", "Naira", "NGN", "566" }, { "NIUE", "New Zealand Dollar", "NZD", "554" }, { "NORFOLK ISLAND", "Australian Dollar", "AUD", "036" }, { "NORTHERN MARIANA ISLANDS", "US Dollar", "USD", "840" }, { "NORWAY", "Norwegian Krone", "NOK", "578" }, { "OMAN", "Rial Omani", "OMR", "512" }, { "PAKISTAN", "Pakistan Rupee", "PKR", "586" }, { "PALAU", "US Dollar", "USD", "840" }, { "PANAMA", "Balboa", "PAB", "590" }, { "PANAMA", "US Dollar", "USD", "840" }, { "PAPUA NEW GUINEA", "Kina", "PGK", "598" }, { "PARAGUAY", "Guarani", "PYG", "600" }, { "PERU", "Nuevo Sol", "PEN", "604" }, { "PHILIPPINES", "Philippine Peso", "PHP", "608" }, { "PITCAIRN", "New Zealand Dollar", "NZD", "554" }, { "POLAND", "Zloty", "PLN", "985" }, { "PORTUGAL", "Euro", "EUR", "978" }, { "PUERTO RICO", "US Dollar", "USD", "840" }, { "QATAR", "Qatari Rial", "QAR", "634" }, { "RÉUNION", "Euro", "EUR", "978" }, { "ROMANIA", "Old Leu", "ROL", "642" }, { "ROMANIA", "New Leu", "RON", "946" }, { "RUSSIAN FEDERATION", "Russian Ruble", "RUB", "643" }, { "RWANDA", "Rwanda Franc", "RWF", "646" }, { "SAINT HELENA", "Saint Helena Pound", "SHP", "654" }, { "SAINT KITTS AND NEVIS", "East Caribbean Dollar", "XCD", "951" }, { "SAINT LUCIA", "East Caribbean Dollar", "XCD", "951" }, { "SAINT PIERRE AND MIQUELON", "Euro", "EUR", "978" }, { "SAINT VINCENT AND THE GRENADINES", "East Caribbean Dollar", "XCD", "951" }, { "SAMOA", "Tala", "WST", "882" }, { "SAN MARINO", "Euro", "EUR", "978" }, { "SÃO TOME AND PRINCIPE", "Dobra", "STD", "678" }, { "SAUDI ARABIA", "Saudi Riyal", "SAR", "682" }, { "SENEGAL", "CFA Franc BCEAO", "XOF", "952" }, { "SERBIA", "Serbian Dinar", "RSD", "941" }, { "SEYCHELLES", "Seychelles Rupee", "SCR", "690" }, { "SIERRA LEONE", "Leone", "SLL", "694" }, { "SINGAPORE", "Singapore Dollar", "SGD", "702" }, { "SLOVAKIA", "Slovak Koruna", "SKK", "703" }, { "SLOVENIA", "Tolar", "SIT", "705" }, { "SOLOMON ISLANDS", "Solomon Islands Dollar", "SBD", "090" }, { "SOMALIA", "Somali Shilling", "SOS", "706" }, { "SOUTH AFRICA", "Rand", "ZAR", "710" }, { "SPAIN", "Euro", "EUR", "978" }, { "SRI LANKA", "Sri Lanka Rupee", "LKR", "144" }, { "SUDAN", "Sudanese Dinar", "SDG", "938" }, { "SURINAME", "Surinam Dollar", "SRD", "968" }, { "SVALBARD AND JAN MAYEN", "Norwegian Krone", "NOK", "578" }, { "SWAZILAND", "Lilangeni", "SZL", "748" }, { "SWEDEN", "Swedish Krona", "SEK", "752" }, { "SWITZERLAND", "Swiss Franc", "CHF", "756" }, { "SWITZERLAND", "WIR Franc", "CHW", "948" }, { "SWITZERLAND", "WIR Euro", "CHE", "947" }, { "SYRIAN ARAB REPUBLIC", "Syrian Pound", "SYP", "760" }, { "TAIWAN PROVINCE OF CHINA", "New Taiwan Dollar", "TWD", "901" }, { "TAJIKISTAN", "Somoni", "TJS", "972" }, { "TANZANIA UNITED REPUBLIC OF", "Tanzanian Shilling", "TZS", "834" }, { "THAILAND", "Baht", "THB", "764" }, { "TIMOR-LESTE", "US Dollar", "USD", "840" }, { "TOGO", "CFA Franc BCEAO", "XOF", "952" }, { "TOKELAU", "New Zealand Dollar", "NZD", "554" }, { "TONGA", "Pa'anga", "TOP", "776" }, { "TRINIDAD AND TOBAGO", "Trinidad and Tobago Dollar", "TTD", "780" }, { "TUNISIA", "Tunisian Dinar", "TND", "788" }, { "TURKEY", "New Turkish Lira", "TRY", "949" }, { "TURKMENISTAN", "Manat", "TMM", "795" }, { "TURKS AND CAICOS ISLANDS", "US Dollar", "USD", "840" }, { "TUVALU", "Australian Dollar", "AUD", "036" }, { "UGANDA", "Uganda Shilling", "UGX", "800" }, { "UKRAINE", "Hryvnia", "UAH", "980" }, { "UNITED ARAB EMIRATES", "UAE Dirham", "AED", "784" }, { "UNITED KINGDOM", "Pound Sterling", "GBP", "826" }, { "UNITED STATES", "US Dollar", "USD", "840" }, { "UNITED STATES", "US Dollar (Same day)", "USS", "998" }, { "UNITED STATES", "US Dollar(Next day)", "USN", "997" }, { "UNITED STATES MINOR OUTLYING ISLANDS", "US Dollar", "USD", "840" }, { "URUGUAY", "Peso Uruguayo", "UYU", "858" }, { "URUGUAY", "Uruguay Peso en Unidades Indexadas", "UYI", "940" }, { "UZBEKISTAN", "Uzbekistan Sum", "UZS", "860" }, { "VANUATU", "Vatu", "VUV", "548" }, { "VENEZUELA", "Bolivar", "VEB", "862" }, { "VIET NAM", "Dong", "VND", "704" }, { "VIRGIN ISLANDS (BRITISH)", "US Dollar", "USD", "840" }, { "VIRGIN ISLANDS (US)", "US Dollar", "USD", "840" }, { "WALLIS AND FUTUNA", "CFP Franc", "XPF", "953" }, { "WESTERN SAHARA", "Moroccan Dirham", "MAD", "504" }, { "YEMEN", "Yemeni Rial", "YER", "886" }, { "ZAMBIA", "Kwacha", "ZMK", "894" }, { "ZIMBABWE", "Zimbabwe Dollar", "ZWD", "716" }, { "-", "Gold", "XAU", "959" }, { "-", "Bond Markets Units European Composite Unit (EURCO)", "XBA", "955" }, { "-", "European Monetary Unit (E.M.U.-6)", "XBB", "956" }, { "-", "European Unit of Account 9(E.U.A.-9)", "XBC", "957" }, { "-", "European Unit of Account 17(E.U.A.-17)", "XBD", "958" }, { "-", "Palladium", "XPD", "964" }, { "-", "Platinum", "XPT", "962" }, { "-", "Silver", "XAG", "961" }, { "-", "UIC-Franc", "XFU", "-1" }, { "-", "Gold-Franc", "XFO", "-1" }, { "-", "Codes specifically reserved for testing purposes", "XTS", "963" }, { "-", "The codes assigned for transactions where no currency is involved are:", "XXX", "999" } }; public static String Numeric2Alphabetic(int numeric) { for (int row = 0; row < table.length; row++) { String numericStr = table[row][COLUMN_NUMERIC]; if (numeric == Integer.parseInt(numericStr)) { return table[row][COLUMN_ALPHABETIC]; } } return ""; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/resourcetracker/0000755000175000017500000000000011412336332024210 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/resourcetracker/ResourceFinalizer.java0000644000175000017500000000607011411055574030516 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.resourcetracker; import java.lang.ref.ReferenceQueue; /** * A thread for monitoring a reference queue. *

* This monitor is decoupled from the {@link ResourceTracker} instance to allow * for heterogenous resources to be tracked in a single thread. * */ public class ResourceFinalizer extends Thread { private static ResourceFinalizer DEFAULT; synchronized public static ResourceFinalizer get() { if (DEFAULT == null) { DEFAULT = new ResourceFinalizer(); } return DEFAULT; } final private ReferenceQueue queue = new ReferenceQueue(); private boolean started = false; public ResourceFinalizer() { super("resource finalizer"); // todo some resources must really be finalized // todo invent more intelligent shutdown setDaemon(true); } protected void drainQueue() { while (true) { IResourceReference ref = (IResourceReference) queue.poll(); if (ref == null) { return; } else { ref.dispose(); } } } synchronized protected void ensureStarted() { if (started) { return; } start(); } public ReferenceQueue getQueue() { return queue; } @Override public void run() { while (true) { try { PhantomResourceReference ref = (PhantomResourceReference) queue .remove(); if (ref != null) { ref.dispose(); } } catch (Exception e) { return; } } } @Override public synchronized void start() { started = true; super.start(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/resourcetracker/SoftResourceReference.java0000644000175000017500000000463711411055574031334 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.resourcetracker; import java.lang.ref.SoftReference; /** * A generic reference to some trackable resource. The resource finalization is * managed using a {@link SoftReference} to the container. When the container is * garbage collected, the reference is forwarded to the {@link ResourceTracker} * that created it for disposal. */ public class SoftResourceReference extends SoftReference implements IResourceReference { private ResourceTracker tracker; private Object resource; public SoftResourceReference(Object container, Object resource, ResourceTracker tracker) { super(container, tracker.getQueue()); this.tracker = tracker; this.resource = resource; } public void dispose() { tracker.dispose(this); resource = null; clear(); } public Object getResource() { return resource; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/resourcetracker/IResourceReference.java0000644000175000017500000000367711411055574030614 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.resourcetracker; import java.lang.ref.Reference; /** * An interface for accessing a generic resource associated with a tracked * {@link Reference} by the {@link ResourceTracker}. */ public interface IResourceReference { public void dispose(); /** * The resource tracked. * * @return The resource tracked. */ public Object getResource(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/resourcetracker/ResourceTracker.java0000644000175000017500000001030211411055574030157 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.resourcetracker; import java.lang.ref.ReferenceQueue; /** * An object to keep track of platform resources that should be disposed upon * garbage collection of some container object. *

* To use this create a subclass implementing the dispose strategy and add new * resources using "track". *

* The resources will be disposed automatically after garbage collection of the * container in a separate worker thread. */ abstract public class ResourceTracker { private IResourceReference[] references; private int next = 0; final private ResourceFinalizer finalizer; public ResourceTracker() { this(500); } public ResourceTracker(int size) { super(); this.references = new IResourceReference[size]; this.finalizer = ResourceFinalizer.get(); } public ResourceTracker(ResourceFinalizer finalizer) { this(finalizer, 500); } public ResourceTracker(ResourceFinalizer finalizer, int size) { super(); this.references = new IResourceReference[size]; this.finalizer = finalizer; } protected synchronized IResourceReference add(IResourceReference ref) { finalizer.ensureStarted(); if (next >= references.length) { // ooops - maybe finalizer thread is starving. help! System.gc(); finalizer.drainQueue(); if (next >= references.length) { IResourceReference[] newReferences = new IResourceReference[references.length << 1]; System.arraycopy(references, 0, newReferences, 0, references.length); references = newReferences; } } references[next++] = ref; return ref; } abstract protected void basicDispose(Object resource); protected void dispose(IResourceReference ref) { remove(ref); if (ref.getResource() != null) { basicDispose(ref.getResource()); } } protected ReferenceQueue getQueue() { return finalizer.getQueue(); } synchronized protected void remove(IResourceReference ref) { int length = next; for (int i = 0; i < length; i++) { if (references[i] == ref) { next--; references[i] = references[next]; references[next] = null; break; } } // System.out.println("tracker removed instance, now " + next); } public IResourceReference trackPhantom(Object container, Object resource) { return add(new PhantomResourceReference(container, resource, this)); } public IResourceReference trackSoft(Object container, Object resource) { return add(new SoftResourceReference(container, resource, this)); } public IResourceReference trackWeak(Object container, Object resource) { return add(new WeakResourceReference(container, resource, this)); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/resourcetracker/WeakResourceReference.java0000644000175000017500000000463711411055574031310 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.resourcetracker; import java.lang.ref.WeakReference; /** * A generic reference to some trackable resource. The resource finalization is * managed using a {@link WeakReference} to the container. When the container is * garbage collected, the reference is forwarded to the {@link ResourceTracker} * that created it for disposal. */ public class WeakResourceReference extends WeakReference implements IResourceReference { private ResourceTracker tracker; private Object resource; public WeakResourceReference(Object container, Object resource, ResourceTracker tracker) { super(container, tracker.getQueue()); this.tracker = tracker; this.resource = resource; } public void dispose() { tracker.dispose(this); resource = null; clear(); } public Object getResource() { return resource; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/resourcetracker/PhantomResourceReference.java0000644000175000017500000000465611411055574032030 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.resourcetracker; import java.lang.ref.PhantomReference; /** * A generic reference to some trackable resource. The resource finalization is * managed using a {@link PhantomReference} to the container. When the container * is garbage collected, the reference is forwarded to the * {@link ResourceTracker} that created it for disposal. */ public class PhantomResourceReference extends PhantomReference implements IResourceReference { private ResourceTracker tracker; private Object resource; public PhantomResourceReference(Object container, Object resource, ResourceTracker tracker) { super(container, tracker.getQueue()); this.tracker = tracker; this.resource = resource; } public void dispose() { tracker.dispose(this); resource = null; clear(); } public Object getResource() { return resource; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/stream/0000755000175000017500000000000011412336332022300 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/stream/ConsoleStream.java0000644000175000017500000000417311025664516025736 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.stream; import java.io.IOException; import java.io.OutputStream; /** * A stream object wrapping console output. * */ public class ConsoleStream extends OutputStream { /** * SplitStream - Konstruktorkommentar. */ public ConsoleStream() { super(); } @Override public void close() throws IOException { // you dont really want to close the console } @Override public void flush() throws IOException { System.out.flush(); } @Override public void write(int b) throws IOException { System.out.write(b); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/stream/NullOutputStream.java0000644000175000017500000000544311025664516026470 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.stream; import java.io.IOException; /** * An output stream killing its data. * */ public class NullOutputStream extends java.io.OutputStream { /** * NullOutputStream constructor comment. */ public NullOutputStream() { super(); } @Override public void write(byte[] b) throws IOException { // ignore character } @Override public void write(byte[] b, int off, int len) throws IOException { // ignore } /** * Writes the specified byte to this output stream. The general contract for * write is that one byte is written to the output stream. * The byte to be written is the eight low-order bits of the argument * b. The 24 high-order bits of b are * ignored. * *

* Subclasses of OutputStream must provide an implementation * for this method. *

* * @param b * the byte. * * @exception IOException * if an I/O error occurs. In particular, an * IOException may be thrown if the output * stream has been closed. */ @Override public void write(int b) throws IOException { // ignore } } libisrt-java-4.8.20100629/src/de/intarsys/tools/stream/LogInputStream.java0000644000175000017500000001071111025664516026070 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.stream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * An {@link InputStream} that logs any char read. *

* This stream is piped in the reading process, any characters read are written * to an associated {@link OutputStream} object. * *

 * Client -> LogInputStream -> InputStream -> Source
 *            |
 *            v
 *           OutputStream
 * 
*/ public class LogInputStream extends FilterInputStream { /** * */ private OutputStream log; /** * SplitStream - Konstruktorkommentar. * * @param newin * * @param newlog * */ public LogInputStream(InputStream newin, OutputStream newlog) { super(newin); setLog(newlog); } @Override public void close() throws IOException { super.close(); if ((log != null)) { log.close(); } } public java.io.OutputStream getLog() { return log; } /** * Reads the next byte of data from the input stream. The value byte is * returned as an int in the range 0 to * 255. If no byte is available because the end of the * stream has been reached, the value -1 is returned. This * method blocks until input data is available, the end of the stream is * detected, or an exception is thrown. * *

* A subclass must provide an implementation of this method. *

* * @return the next byte of data, or -1 if the end of the * stream is reached. * * @exception java.io.IOException * if an I/O error occurs. */ @Override public int read() throws java.io.IOException { int b = super.read(); if ((b > -1) && (log != null)) { log.write(b); } return b; } /** * Reads up to len bytes of data from this input stream into * an array of bytes. This method blocks until some input is available. * *

* This method simply performs in.read(b, off, len) and * returns the result. *

* * @param b * the buffer into which the data is read. * @param off * the start offset of the data. * @param len * the maximum number of bytes read. * * @return the total number of bytes read into the buffer, or * -1 if there is no more data because the end of the * stream has been reached. * * @exception IOException * if an I/O error occurs. * * @see java.io.FilterInputStream#in */ @Override public int read(byte[] b, int off, int len) throws IOException { int bytes = super.read(b, off, len); if ((bytes > -1) && (log != null)) { log.write(b, off, bytes); } return bytes; } public void setLog(java.io.OutputStream newLog) { log = newLog; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/stream/ConcatInputStream.java0000644000175000017500000000622310751651500026553 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.stream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * A stream that reads from all its inputs until all are empty. * */ public class ConcatInputStream extends InputStream { /** * The list of all input streams that are read in succession. */ final private List inputs = new ArrayList(); /** * The input stream we are currently reading from */ private InputStream current = null; /** * The currently active input stream. */ private int index = 0; /** * */ public ConcatInputStream() { super(); } public void addInput(InputStream input) { inputs.add(input); if (current == null) { current = input; } } /* * (non-Javadoc) * * @see java.io.InputStream#close() */ @Override public void close() throws IOException { IOException ex = null; for (Iterator it = inputs.iterator(); it.hasNext();) { InputStream is = (InputStream) it.next(); try { is.close(); } catch (IOException e) { ex = e; } } super.close(); if (ex != null) { throw ex; } } /* * (non-Javadoc) * * @see java.io.InputStream#read() */ @Override public int read() throws IOException { if (current == null) { return -1; } int result = current.read(); if (result == -1) { index++; if (index >= inputs.size()) { current = null; } else { current = (InputStream) inputs.get(index); } return read(); } else { return result; } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/stream/TempFileOutputStream.java0000644000175000017500000000722111025664516027257 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.stream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import de.intarsys.tools.file.FileTools; /** * A stream wrapper that deferrs writing to the final destination until the * stream is closed. The output is written to a temporary file in the * destinations directory. When the stream is closed, the temp file is copied to * the destination and deleted. * */ public class TempFileOutputStream extends OutputStream { /** The final destination for the output */ private File destination; /** The temporary file to use. */ private File tempFile; /** The temporary output stream */ private FileOutputStream tempOutput; public TempFileOutputStream(File destination) throws IOException { this(destination, "tmp", "tmp"); } public TempFileOutputStream(File destination, String prefix, String suffix) throws IOException { super(); this.destination = destination; tempFile = File.createTempFile(prefix, suffix, destination .getParentFile()); tempOutput = new FileOutputStream(tempFile); } /* * (non-Javadoc) * * @see java.io.OutputStream#close() */ @Override public void close() throws IOException { super.close(); try { tempOutput.close(); FileTools.copyBinaryFile(tempFile, destination); } finally { tempFile.delete(); } } /* * (non-Javadoc) * * @see java.io.OutputStream#flush() */ @Override public void flush() throws IOException { tempOutput.flush(); } /* * (non-Javadoc) * * @see java.io.OutputStream#write(byte[]) */ @Override public void write(byte[] b) throws IOException { tempOutput.write(b); } /* * (non-Javadoc) * * @see java.io.OutputStream#write(byte[], int, int) */ @Override public void write(byte[] b, int off, int len) throws IOException { tempOutput.write(b, off, len); } /* * (non-Javadoc) * * @see java.io.OutputStream#write(int) */ @Override public void write(int b) throws IOException { tempOutput.write(b); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/stream/StreamTools.java0000644000175000017500000001726611240532252025431 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.stream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.RandomAccessFile; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import de.intarsys.tools.exception.ExceptionTools; import de.intarsys.tools.randomaccess.IRandomAccess; /** * A tool class for the handling of streams. * */ public class StreamTools { // public static final int MAX_BUFFER = 100000; public static void close(InputStream is) { try { if (is != null) { is.close(); } } catch (IOException e) { // ignore } } public static void close(IRandomAccess ra) { try { if (ra != null) { ra.close(); } } catch (IOException e) { // ignore } } public static void close(OutputStream os) { try { if (os != null) { os.close(); } } catch (IOException e) { // ignore } } public static void close(RandomAccessFile ra) { try { if (ra != null) { ra.close(); } } catch (IOException e) { // ignore } } public static void close(Reader reader) { try { if (reader != null) { reader.close(); } } catch (IOException e) { // ignore } } public static void close(Writer writer) { try { if (writer != null) { writer.close(); } } catch (IOException e) { // ignore } } public static void copyEncoded(Reader reader, Writer writer) throws IOException { try { char[] c = new char[MAX_BUFFER]; for (int i = reader.read(c); i != -1;) { writer.write(c, 0, i); i = reader.read(c); } } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException("copying failed (" + e.getMessage() + ")"); } } public static void copyEncodedStream(InputStream source, String sourceEncoding, OutputStream destination, String destinationEncoding) throws IOException { if ((sourceEncoding == null) | (destinationEncoding == null) | sourceEncoding.equals(destinationEncoding)) { copyStream(source, false, destination, false); } InputStreamReader reader = null; OutputStreamWriter writer = null; try { reader = new InputStreamReader(source, sourceEncoding); writer = new OutputStreamWriter(destination, destinationEncoding); char[] c = new char[MAX_BUFFER]; for (int i = reader.read(c); i != -1;) { writer.write(c, 0, i); i = reader.read(c); } } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException("copying failed (" + e.getMessage() + ")"); } finally { /* * do not close try { reader.close(); } catch (Exception ignore) { } * try { writer.close(); } catch (Exception ignore) { } */ } } /** * Kopiert einen Eingabedatenstrom auf einen Ausgabedatenstrom. Anschließend * (finally) werden die Datenströme geschlossen(!), sofern dies in den * Parametern angegeben wurde. Fehler beim Schließen der Datenströme werden * ignoriert. * * @param source * Eingabedatenstrom * @param closeInput * Angabe ob der InputStream nach dem Kopieren geschlossen werden * soll. * @param destination * Ausgabedatenstrom * @param closeOutput * Angabe ob der OutputStream nach dem Kopieren geschlossen * werden soll. * * @throws IOException * Fehler allgemein oder beim Kopieren. */ public static void copyStream(InputStream source, boolean closeInput, OutputStream destination, boolean closeOutput) throws IOException { try { byte[] b = new byte[MAX_BUFFER]; for (int i = source.read(b); i != -1;) { destination.write(b, 0, i); i = source.read(b); } } catch (IOException e) { throw e; } catch (Exception e) { throw ExceptionTools.createIOException("copying failed (" + e.getMessage() + ")", e); } finally { if (closeInput) { StreamTools.close(source); } if (closeOutput) { StreamTools.close(destination); } } } /** * Kopiert einen Stream. Ruft copyStream(in, true, out, true) auf. * * @see StreamTools#copyStream(InputStream, boolean, OutputStream, boolean) * * @param source * Eingabedatenstrom, der kopiert werden soll. * @param destination * Ausgabestrom, auf den kopiert werden soll. * * @throws IOException * */ public static void copyStream(InputStream source, OutputStream destination) throws IOException { copyStream(source, true, destination, true); } /** * Kopiert einen Eingabedatenstrom auf einen Ausgabedatenstrom. * * @param source * Eingabedatenstrom * @param destination * Ausgabedatenstrom * @param length * Anzahl der zu lesenden bytes * * @throws IOException * */ public static void copyStream(InputStream source, OutputStream destination, long length) throws IOException { try { long toRead = length; byte[] b = new byte[(int) length]; while (toRead > 0) { int i = source.read(b, 0, (int) toRead); if (i == -1) { break; } destination.write(b, 0, i); toRead = toRead - i; } } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException("copying failed (" + e.getMessage() + ")"); } } public static byte[] toByteArray(InputStream is) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); copyStream(is, os); return os.toByteArray(); } public static String toString(InputStream is, String encoding) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); copyStream(is, os); if (encoding == null) { encoding = System.getProperty("file.encoding"); } return os.toString(encoding); } public static String toString(Reader r) throws IOException { StringWriter w = new StringWriter(); copyEncoded(r, w); return w.toString(); } private StreamTools() { super(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/stream/LogOutputStream.java0000644000175000017500000000555111025664516026277 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.stream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; /** * An output stream that logs any char written. *

* The output stream is piped in the writing process, any characters written are * copied to an associated output stream object. * *

 * Client -> LogOutputStream -> OutputStream -> Destination
 *            |
 *            v
 *           OutputStream (Copy)
 * 
*/ public class LogOutputStream extends FilterOutputStream { /** * */ private OutputStream log; /** * SplitStream - Konstruktorkommentar. * * @param newout * * @param newlog * */ public LogOutputStream(OutputStream newout, OutputStream newlog) { super(newout); setLog(newlog); } @Override public void close() throws IOException { super.close(); if ((log != null)) { log.close(); } } @Override public void flush() throws IOException { super.flush(); if (log != null) { log.flush(); } } public java.io.OutputStream getLog() { return log; } public void setLog(java.io.OutputStream newLog) { log = newLog; } @Override public void write(int b) throws IOException { super.write(b); if (log != null) { log.write(b); } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/stream/HexDumpStream.java0000644000175000017500000000664111025664516025710 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.stream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; /** * A stream object dumping its data in hex format. * */ public class HexDumpStream extends FilterOutputStream { private static final char[] hex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; private static int BYTES_PER_LINE = 16; private int tbc = 0; private int lbc = 0; private char[] line = new char[BYTES_PER_LINE]; /** * Creates a new HexOutputStream. * * @param out * The input stream. */ public HexDumpStream(OutputStream out) { super(out); } @Override public void flush() throws IOException { String tbcString = Long.toHexString(tbc); int i; for (i = tbcString.length(); i < 8;) { out.write('0'); i++; } out.write(tbcString.getBytes()); out.write(' '); for (i = 0; i < lbc;) { out.write(hex[((line[i] >> 4) & 0xF)]); out.write(hex[((line[i] >> 0) & 0xF)]); out.write(' '); i++; } for (; i < BYTES_PER_LINE;) { out.write(' '); out.write(' '); out.write(' '); i++; } out.write(' '); for (i = 0; i < lbc;) { if (Character.isISOControl(line[i])) { out.write('.'); } else { out.write(line[i]); } i++; } out.write(System.getProperty("line.separator").getBytes()); tbc += lbc; lbc = 0; super.flush(); } @Override public synchronized void write(byte[] b) throws IOException { write(b, 0, b.length); } @Override public synchronized void write(byte[] b, int off, int len) throws IOException { for (int i = 0; i < len; i++) { write(b[off + i]); } } @Override public synchronized void write(int b) throws IOException { line[lbc++] = (char) b; if (lbc >= BYTES_PER_LINE) { flush(); } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/stream/FastByteArrayOutputStream.java0000644000175000017500000000550510751651500030267 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.stream; import java.io.OutputStream; /** * */ public class FastByteArrayOutputStream extends OutputStream { /** The buffer where data is stored. */ protected byte[] buf; /** The number of valid bytes in the buffer. */ protected int count; /** * */ public FastByteArrayOutputStream() { this(32); } public FastByteArrayOutputStream(int size) { buf = new byte[size]; } public byte[] getBytes() { return buf; } public void reset() { count = 0; } public int size() { return count; } public byte[] toByteArray() { byte[] result = new byte[count]; System.arraycopy(buf, 0, result, 0, count); return result; } @Override public void write(byte[] b, int off, int len) { int newcount = count + len; if (newcount > buf.length) { byte[] newbuf = new byte[Math.max(buf.length << 1, newcount)]; System.arraycopy(buf, 0, newbuf, 0, buf.length); buf = newbuf; } System.arraycopy(b, off, buf, count, len); count = newcount; } @Override public void write(int b) { if (count >= buf.length) { byte[] newbuf = new byte[Math.max(buf.length << 1, 1)]; System.arraycopy(buf, 0, newbuf, 0, buf.length); buf = newbuf; } buf[count++] = (byte) b; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/valueholder/0000755000175000017500000000000011412336332023317 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/valueholder/IValueHolder.java0000644000175000017500000000370511412330336026510 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.valueholder; /** * Generic interface for objects holding references to others. */ public interface IValueHolder { /** * Dereference the {@link IValueHolder}. * * @return The referenced object. */ public T get(); /** * Assign a new value. * * @param newValue * @return The previous value (optional) */ public T set(T newValue); } libisrt-java-4.8.20100629/src/de/intarsys/tools/valueholder/ThreadLocalValueHolder.java0000644000175000017500000000054211272312772030506 0ustar twernertwernerpackage de.intarsys.tools.valueholder; public class ThreadLocalValueHolder implements IValueHolder { final private ThreadLocal threadLocal = new ThreadLocal(); public T get() { return threadLocal.get(); } public T set(T value) { T oldValue = threadLocal.get(); threadLocal.set(value); return oldValue; }; } libisrt-java-4.8.20100629/src/de/intarsys/tools/valueholder/NullValueHolder.java0000644000175000017500000000344711015027210027226 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.valueholder; public class NullValueHolder implements IValueHolder { public NullValueHolder() { // } public Object get() { return null; } public Object set(Object newValue) { return null; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/valueholder/ObjectValueHolder.java0000644000175000017500000000361411411055576027536 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.valueholder; public class ObjectValueHolder implements IValueHolder { private T value; public ObjectValueHolder(T value) { super(); this.value = value; } public T get() { return value; } public T set(T newValue) { T oldValue = value; value = newValue; return oldValue; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/proxy/0000755000175000017500000000000011412336332022166 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/proxy/IProxy.java0000644000175000017500000000370011325065004024261 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.proxy; /** * An object acting as a stand-in for another object. The other may be * "realized" or created at any point in time, at least it will be provided when * calling "getRealized". */ public interface IProxy { /** * The object represented by the receiver. * * @return The object represented by the receiver. */ public Object getRealized(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/0000755000175000017500000000000011412336332022431 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/IAccessSupport.java0000644000175000017500000000450211355101012026173 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; /** * An object supporting reflective calls to its fields. */ public interface IAccessSupport { /** * Make a reflective get access to the field name. * * @param name * The name of the field to get. * @return The field value * @throws FieldException */ public Object getValue(String name) throws FieldException; /** * Make a reflective set access to the field name. * * @param name * The name of the field to get. * @param value * The new value for the field * @return The previous field value. This is an optional feature. * @throws FieldException */ public Object setValue(String name, Object value) throws FieldException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/IAccessHandlerAccessibility.java0000644000175000017500000000447711355101012030617 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; /** * An object supporting handling reflective calls to fields of a delegate. */ public interface IAccessHandlerAccessibility { public static int NONE = 0; public static int READONLY = 1; public static int READWRITE = 3; public static int WRITEONLY = 2; /** * Query the access state of the property name within the * receiver. * * @param receiver * The object hosting the field. * @param name * The name of the field to get. * @return The current access state (one of NONE, READONLY, READWRITE or * WRITEONLY) * @throws FieldException */ public int getAccessMode(Object receiver, String name) throws FieldAccessException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/IMethodHandlerAccessibility.java0000644000175000017500000000430111355101012030620 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; import de.intarsys.tools.functor.IArgs; /** * An object able to access a method within a delegate */ public interface IMethodHandlerAccessibility { /** * Query the accessibility of the implementation associated with this method * in the context of the receiver. * * @param receiver * The object hosting the method. * @param args * The arguments for the invocation. * @return The accesibility of the implementation * @throws MethodException */ public boolean isInvokeEnabled(Object receiver, IArgs args) throws MethodInvocationException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/IClassLoaderAccess.java0000644000175000017500000000377011105016032026721 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; /** * An interface indicating support for complete access (get and set) to a * {@link ClassLoader}. */ public interface IClassLoaderAccess extends IClassLoaderSupport { /** * Assign the class loader suitable for use in the context of the generic * receiver object. * * @param classLoader * The class loader to be used. */ public void setClassLoader(ClassLoader classLoader); } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/IInvocationSupportAccessibility.java0000644000175000017500000000430211355101010031607 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; import de.intarsys.tools.functor.IArgs; /** * An object supporting reflective access to its methods. */ public interface IInvocationSupportAccessibility { /** * true if calling the method name within this is * currently enabled. * * @param name * The name of the method. * @param args * The arguments for the invocation. * @return true if calling the implementation is currently * enabled. * @throws MethodException */ public boolean isInvokeEnabled(String name, IArgs args) throws MethodException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/IClassLoaderSupport.java0000644000175000017500000000377111105016032027175 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; /** * An interface indicating support for getting a {@link ClassLoader}. */ public interface IClassLoaderSupport { /** * A {@link ClassLoader} instance suitable to load classes and resources in * the context of the receiver. * * @return A {@link ClassLoader} instance suitable to load classes and * resources in the context of the receiver. */ public ClassLoader getClassLoader(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/MethodNotFoundException.java0000644000175000017500000000411611412330322030043 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; /** * An exception in the lookup of method. */ public class MethodNotFoundException extends MethodException { private String name; /** * */ public MethodNotFoundException(String name) { super(); this.name = name; } @Override public String getMessage() { StringBuilder sb = new StringBuilder(); sb.append("method '"); sb.append(getName()); sb.append("' not found"); return sb.toString(); } @Override public String getName() { return name; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/FieldNotFoundException.java0000644000175000017500000000400411306004760027650 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; public class FieldNotFoundException extends FieldException { private String name; public FieldNotFoundException(String name) { super(); this.name = name; } @Override public String getMessage() { StringBuilder sb = new StringBuilder(); sb.append("field '"); sb.append(getName()); sb.append("' not found"); return sb.toString(); } @Override public String getName() { return name; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/ReflectionException.java0000644000175000017500000000370711306004760027253 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; /** * */ abstract public class ReflectionException extends Exception { public ReflectionException() { super(); } public ReflectionException(String message) { super(message); } public ReflectionException(String message, Throwable cause) { super(message, cause); } public ReflectionException(Throwable cause) { super(cause); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/IInvocationSupport.java0000644000175000017500000000411711355101012027105 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; import de.intarsys.tools.functor.IArgs; /** * An object supporting reflective access to its methods. */ public interface IInvocationSupport { /** * Make a reflective call to the method name. * * @param name * The name of the method to call. * @param args * The arguments for the invocation. * @return The result of the invocation. * @throws MethodException */ public Object invoke(String name, IArgs args) throws MethodException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/IMethodHandler.java0000644000175000017500000000425111355101010026112 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; import de.intarsys.tools.functor.IArgs; /** * An object able to access a method within a delegate */ public interface IMethodHandler { /** * Execute the implementation associated with this method in the context of * the receiver and return the result. * * @param receiver * The object implementing the method. * @param args * The arguments for the invocation. * @return The result of the invocation. * @throws MethodException */ public Object invoke(Object receiver, IArgs args) throws MethodInvocationException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/MethodInvocationException.java0000644000175000017500000000513511412330316030425 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; /** * An exception in the execution of a method. */ public class MethodInvocationException extends MethodException { private String name; public MethodInvocationException(String name) { super(); this.name = name; } public MethodInvocationException(String name, String message) { super(message); this.name = name; } public MethodInvocationException(String name, String message, Throwable cause) { super(message, cause); this.name = name; } public MethodInvocationException(String name, Throwable cause) { super(cause); this.name = name; } @Override public String getMessage() { StringBuilder sb = new StringBuilder(); sb.append("method '"); sb.append(getName()); sb.append("' invocation exception"); if (getCause() != null) { sb.append(" ("); sb.append(getCause()); sb.append(")"); } return sb.toString(); } @Override public String getName() { if (name == null) { return ""; } return name; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/IFieldHandlerAccessibility.java0000644000175000017500000000433011355101010030423 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; /** * An object able to access a field within a delegate */ public interface IFieldHandlerAccessibility { public static int NONE = 0; public static int READONLY = 1; public static int READWRITE = 3; public static int WRITEONLY = 2; /** * Query the access state of the field represented by this within the * receiver. * * @param receiver * The object hosting the field. * @return The current access state (one of NONE, READONLY, READWRITE or * WRITEONLY) * @throws FieldException */ public int getAccessMode(Object receiver) throws FieldAccessException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/ObjectCreationException.java0000644000175000017500000000420111411055574030050 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; /** * Failure while creating a new object via reflection. */ public class ObjectCreationException extends ReflectionException { /** * */ public ObjectCreationException() { } /** * @param message */ public ObjectCreationException(String message) { super(message); } /** * @param message * @param cause */ public ObjectCreationException(String message, Throwable cause) { super(message, cause); } /** * @param cause */ public ObjectCreationException(Throwable cause) { super(cause); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/IBasicInvocationSupport.java0000644000175000017500000000434411354636242030072 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; /** * An object supporting reflective method calls *

* This is a basic support interface used in {@link ObjectTools} to support * reflective operations. You MUST NOT implement this interface in terms of * {@link ObjectTools} methods! */ public interface IBasicInvocationSupport { /** * Make a reflective call to name. * * @param name * The name of the method to call. * @param values * The arguments for the invocation. * @return The result of the invocation. * @throws MethodException */ public Object basicInvoke(String name, Object... values) throws MethodException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/IAccessSupportAccessibility.java0000644000175000017500000000427011355101012030705 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; /** * An object supporting reflective calls to its fields. */ public interface IAccessSupportAccessibility { public static int NONE = 0; public static int READONLY = 1; public static int READWRITE = 3; public static int WRITEONLY = 2; /** * Query the access state of the property name within this. * * @param name * The name of the field to get. * @return The current access state (one of NONE, READONLY, READWRITE or * WRITEONLY) * @throws FieldException */ public int getAccessMode(String name) throws FieldAccessException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/MethodException.java0000644000175000017500000000402511306004760026373 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; /** * An exception while performing an object method. * */ public abstract class MethodException extends ReflectionException { public MethodException() { super(); } public MethodException(String message) { super(message); } public MethodException(String message, Throwable cause) { super(message, cause); } public MethodException(Throwable cause) { super(cause); } abstract public String getName(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/ClassLoaderTools.java0000644000175000017500000000553311277013266026526 0ustar twernertwernerpackage de.intarsys.tools.reflect; import java.io.File; import java.io.FileFilter; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import de.intarsys.tools.string.StringTools; /** * Tool methods for handling {@link ClassLoader} instances. */ public class ClassLoaderTools { public static ClassLoader createClassLoader(ClassLoader parent, File baseDir, String classpath, String classpathScan, String classpathScanExclude) { URL[] urlArray = createURLs(baseDir, classpath, classpathScan, classpathScanExclude); URLClassLoader classLoader = new URLClassLoader(urlArray, parent); return classLoader; } public static void createURL(List urls, File file) { if (file.isFile()) { try { urls.add(new URL("file", "", file.getAbsolutePath())); //$NON-NLS-1$ //$NON-NLS-2$ } catch (MalformedURLException e) { // couldn't possibly happen } } else { try { urls.add(new URL("file", "", file.getAbsolutePath() //$NON-NLS-1$ //$NON-NLS-2$ + "/")); //$NON-NLS-1$ } catch (MalformedURLException e) { // couldn't possibly happen } } } public static URL[] createURLs(File baseDir, String classpath, String classpathScan, String classpathScanExclude) { List urls = new ArrayList(); // if (!StringTools.isEmpty(classpath)) { String[] names = classpath.split(";"); for (String name : names) { File file = new File(name); if (!file.isAbsolute()) { file = new File(baseDir, name); } createURL(urls, file); } } // if (!StringTools.isEmpty(classpathScan)) { String[] names = classpathScan.split(";"); List exclude; if (StringTools.isEmpty(classpathScanExclude)) { exclude = new ArrayList(); } else { exclude = Arrays.asList(classpathScanExclude.split(";")); } for (String name : names) { File file = new File(name); if (!file.isAbsolute()) { file = new File(baseDir, name); } createURLScanJar(urls, file, exclude); } } // URL[] urlArray = urls.toArray(new URL[urls.size()]); return urlArray; } public static void createURLScanJar(List result, File directory, final List exclude) { File[] jarFiles = directory.listFiles(new FileFilter() { public boolean accept(File path) { return (path.isFile() && path.canRead() && path.getName().toLowerCase().endsWith(".jar") && !exclude .contains(path.getName())); } }); if (jarFiles != null) { for (File file : jarFiles) { try { result.add(new URL("file", "", file.getAbsolutePath())); //$NON-NLS-1$ //$NON-NLS-2$ } catch (MalformedURLException e) { // couldn't possibly happen } } } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/IBasicAccessSupport.java0000644000175000017500000000477511354636242027172 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; /** * An object supporting reflective get operations. *

* This is a basic support interface used in {@link ObjectTools} to support * reflective operations. You MUST NOT implement this interface in terms of * {@link ObjectTools} methods! */ public interface IBasicAccessSupport { /** * Make a reflective get access to name. * * @param name * The name of the field to get. * @return The field value * @throws FieldException */ public Object basicGetValue(String name) throws FieldException; /** * Make a reflective set access to name. * * @param name * The name of the field to get. * @param value * The new value for the field * @return The previous field value. This is an optional feature. * @throws FieldException */ public Object basicSetValue(String name, Object value) throws FieldException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/IInvocationHandler.java0000644000175000017500000000434611355101010027010 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; import de.intarsys.tools.functor.IArgs; /** * An object that supports handling reflective calls to the methods of a * delegate. */ public interface IInvocationHandler { /** * Make a reflective call to the method name within * receiver * * @param receiver * The object hosting the method. * @param name * The name of the method to call. * @param args * The arguments for the invocation. * @return The result of the invocation. * @throws MethodException */ public Object invoke(Object receiver, String name, IArgs args) throws MethodException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/FieldException.java0000644000175000017500000000402011306004760026171 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; /** * An exception while accessing an object field. * */ public abstract class FieldException extends ReflectionException { public FieldException() { super(); } public FieldException(String message) { super(message); } public FieldException(String message, Throwable cause) { super(message, cause); } public FieldException(Throwable cause) { super(cause); } abstract public String getName(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/FieldAccessException.java0000644000175000017500000000477111306004760027330 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; public class FieldAccessException extends FieldException { private String name; public FieldAccessException(String name) { super(); this.name = name; } public FieldAccessException(String name, String message) { super(message); this.name = name; } public FieldAccessException(String name, String message, Throwable cause) { super(message, cause); this.name = name; } public FieldAccessException(String name, Throwable cause) { super(cause); this.name = name; } @Override public String getMessage() { StringBuilder sb = new StringBuilder(); sb.append("field '"); sb.append(getName()); sb.append("' access exception"); if (getCause() != null) { sb.append(" ("); sb.append(getCause()); sb.append(")"); } return sb.toString(); } @Override public String getName() { if (name == null) { return ""; } return name; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/IInvocationHandlerAccessibility.java0000644000175000017500000000450111355101012031513 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; import de.intarsys.tools.functor.IArgs; /** * An object that supports handling reflective calls to the behavior of a * delegate. */ public interface IInvocationHandlerAccessibility { /** * true if calling the method name in * receiveris currently enabled. * * @param receiver * The object hosting the method. * @param name * The name of the method. * @param args * The arguments for the invocation. * @return true if calling the implementation is currently * enabled. * @throws MethodException */ public boolean isInvokeEnabled(Object receiver, String name, IArgs args) throws MethodException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/ObjectTools.java0000644000175000017500000004245211412330326025527 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import de.intarsys.tools.component.IInitializeable; /** * A tool class for convenient object related tasks. *

* This tool contains some simple reflection implementations. * */ public class ObjectTools { private static final Object[] EMPTY_PARAMETERS = new Object[0]; private static final Class[] EMPTY_PARAMETERTYPES = new Class[0]; public static final String GET_PREFIX = "get"; //$NON-NLS-1$ public static final String IS_PREFIX = "is"; //$NON-NLS-1$ protected static Object basicGet(Object object, String name) throws FieldException { if (object instanceof IBasicAccessSupport) { return ((IBasicAccessSupport) object).basicGetValue(name); } try { Method method = findGetter(object, name); return method.invoke(object, (Object[]) null); } catch (Exception e) { // } try { Field field = object.getClass().getField(name); return field.get(object); } catch (Exception e) { // } try { Method method = object.getClass().getMethod(name, (Class[]) null); return method.invoke(object, (Object[]) null); } catch (Exception e) { throw new FieldAccessException(name, e); } } protected static Object basicInsert(Object object, String name, Object value) throws FieldException { try { Method method = findInserter(object, name, value); return method.invoke(object, value); } catch (Exception e) { // } Object tempValue = get(object, name); if (tempValue instanceof Collection) { if (((Collection) tempValue).add(value)) { return value; } return null; } throw new IllegalAccessError("can't insert in " + name); } protected static Object basicInvoke(Object object, String name, Object... values) throws MethodException { if (object instanceof IBasicInvocationSupport) { return ((IBasicInvocationSupport) object).basicInvoke(name, values); } Method method = findMethod(object, name, values); try { return method.invoke(object, values); } catch (Exception e) { throw new MethodInvocationException(name, e); } } protected static Object basicRemove(Object object, String name, Object value) throws FieldException { try { Method method = findRemover(object, name, value); return method.invoke(object, value); } catch (Exception e) { // } Object tempValue = get(object, name); if (tempValue instanceof Collection) { if (((Collection) tempValue).remove(value)) { return value; } return null; } throw new IllegalAccessError("can't remove from " + name); } protected static Object basicSet(Object object, String name, Object value) throws FieldException { if (object instanceof IBasicAccessSupport) { return ((IBasicAccessSupport) object).basicSetValue(name, value); } try { Method method = findSetter(object, name, value); return method.invoke(object, value); } catch (InvocationTargetException e) { throw new FieldAccessException(name, e.getCause()); } catch (Exception e) { // } try { Field field = object.getClass().getField(name); Object oldValue = field.get(object); field.set(object, value); return oldValue; } catch (Exception e) { throw new FieldAccessException(name, e); } } protected static boolean checkCandidate(Method method, String methodName, Class[] pClasses) { if (!method.getName().equals(methodName)) { return false; } Class[] mClasses = method.getParameterTypes(); return checkCandidateClasses(mClasses, pClasses); } protected static boolean checkCandidateClass(Class mClass, Class pClass) { if (!mClass.isAssignableFrom(pClass)) { return false; } return true; } protected static boolean checkCandidateClasses(Class[] mClasses, Class[] pClasses) { if (mClasses.length != pClasses.length) { return false; } for (int i = 0; i < mClasses.length; i++) { if (!checkCandidateClass(mClasses[i], pClasses[i])) { return false; } } return true; } /** * Create a new instance of Class "class" * * @param clazz * @param expectedClass * @return The new instance * @throws ObjectCreationException */ public static T createObject(Class clazz, Class expectedClass) throws ObjectCreationException { return createObject(clazz, expectedClass, EMPTY_PARAMETERTYPES, EMPTY_PARAMETERS); } /** * Create a new instance of Class "class" * * @param className * @param expectedClass * @param parameterTypes * @param parameters * @return The new instance * @throws ObjectCreationException */ public static T createObject(Class clazz, Class expectedClass, Class[] parameterTypes, Object[] parameters) throws ObjectCreationException { if (clazz == null) { throw new ObjectCreationException("class missing"); //$NON-NLS-1$ } try { if (expectedClass != null && !expectedClass.isAssignableFrom(clazz)) { throw new ObjectCreationException( "class '" + clazz.getName() //$NON-NLS-1$ + "' not compatible with expected type '" + expectedClass + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } T object; if (parameters == EMPTY_PARAMETERS) { object = (T) clazz.newInstance(); } else { Constructor constructor = clazz.getConstructor(parameterTypes); object = (T) constructor.newInstance(parameters); } if (object instanceof IInitializeable) { ((IInitializeable) object).initialize(); } return object; } catch (NoClassDefFoundError e) { throw new ObjectCreationException("class '" + clazz.getName() //$NON-NLS-1$ + "' can't be instantiated", e); //$NON-NLS-1$ } catch (InstantiationException e) { throw new ObjectCreationException("class '" + clazz.getName() //$NON-NLS-1$ + "' can't be instantiated", e); //$NON-NLS-1$ } catch (IllegalAccessException e) { throw new ObjectCreationException("class '" + clazz.getName() //$NON-NLS-1$ + "' can't be instantiated", e); //$NON-NLS-1$ } catch (SecurityException e) { throw new ObjectCreationException("class '" + clazz.getName() //$NON-NLS-1$ + "' can't be instantiated", e); //$NON-NLS-1$ } catch (NoSuchMethodException e) { throw new ObjectCreationException("class '" + clazz.getName() //$NON-NLS-1$ + "' can't be instantiated", e); //$NON-NLS-1$ } catch (IllegalArgumentException e) { throw new ObjectCreationException("class '" + clazz.getName() //$NON-NLS-1$ + "' can't be instantiated", e); //$NON-NLS-1$ } catch (InvocationTargetException e) { throw new ObjectCreationException("class '" + clazz.getName() //$NON-NLS-1$ + "' can't be instantiated", e); //$NON-NLS-1$ } catch (Exception e) { throw new ObjectCreationException("class '" + clazz.getName() //$NON-NLS-1$ + "' can't be instantiated", e); //$NON-NLS-1$ } } /** * Create a new instance of Class "className" via "classLoader". * * @param className * @param expectedClass * @param classLoader * @return The new instance * @throws ObjectCreationException */ public static T createObject(String className, Class expectedClass, ClassLoader classLoader) throws ObjectCreationException { Class clazz = ClassTools.createClass(className, expectedClass, classLoader); return createObject(clazz, expectedClass); } protected static Method findAnyMethod(Class clazz, String name, Class... classes) throws MethodException { Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (!method.getName().equals(name)) { continue; } boolean found = true; Class[] parameterTypes = method.getParameterTypes(); for (int j = 0; j < parameterTypes.length; j++) { Class parameterType = parameterTypes[j]; if (!parameterType.isAssignableFrom(classes[j])) { found = false; break; } } if (found) { return method; } } throw new MethodNotFoundException(name); } public static Method findGetter(Object object, String name) throws MethodException { try { String methodName = GET_PREFIX + Character.toUpperCase(name.charAt(0)) + name.substring(1); return object.getClass().getMethod(methodName, (Class[]) null); } catch (Exception e) { // } String methodName = IS_PREFIX + Character.toUpperCase(name.charAt(0)) + name.substring(1); try { return object.getClass().getMethod(methodName, (Class[]) null); } catch (Exception e) { throw new MethodNotFoundException(name); } } public static Method findInserter(Object object, String attribute, Object value) throws MethodException { String methodName = "insert" + Character.toUpperCase(attribute.charAt(0)) + attribute.substring(1); return findMethod(object, methodName, new Object[] { value }); } protected static Method findMatchingMethod(Class clazz, String name, Class[] classes) throws MethodException { Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (checkCandidate(method, name, classes)) { // todo quick hack. lookup best match, not first. return method; } } try { return clazz.getMethod(name, classes); } catch (Exception e) { throw new MethodNotFoundException(name); } } public static Method findMethod(Object object, String methodName, Object... parameters) throws MethodException { Class clazz = object.getClass(); Class[] parameterClasses = new Class[parameters.length]; for (int i = 0; i < parameters.length; i++) { parameterClasses[i] = parameters[i].getClass(); } Method method = null; try { method = findSimpleMethod(clazz, methodName, parameterClasses); } catch (Exception e) { method = findAnyMethod(clazz, methodName, parameterClasses); } return method; } public static Method findRemover(Object object, String attribute, Object value) throws MethodException { String methodName = "remove" + Character.toUpperCase(attribute.charAt(0)) + attribute.substring(1); return findMethod(object, methodName, new Object[] { value }); } public static Method findSetter(Object object, String attribute, Object value) throws MethodException { String methodName = "set" + Character.toUpperCase(attribute.charAt(0)) + attribute.substring(1); return findMethod(object, methodName, new Object[] { value }); } protected static Method findSimpleMethod(Class clazz, String name, Class... classes) throws MethodException { try { return clazz.getMethod(name, classes); } catch (Exception e) { throw new MethodNotFoundException(name); } } /** * Get the value for field name in object. * * @param object * @param name * @return the value for field name in object. * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchFieldException */ static public Object get(Object object, String name) throws FieldException { // fix array syntax String tempExpr = name.replace('[', '.'); if (tempExpr != name) { tempExpr = tempExpr.replace(']', ' '); } int pos = tempExpr.indexOf('.'); if (pos == -1) { return basicGet(object, name); } else { String pathPrefix = tempExpr.substring(0, pos); String pathTrail = tempExpr.substring(pos + 1); Object result = basicGet(object, pathPrefix); return get(result, pathTrail); } } /** * Insert value in the relation field name in * object. The value that was really inserted is returned (if * supported by the underlying object implementation). To be exact, the * result of the insert method invoked is returned. * * @param object * @param name * @param value * @return the result of the insert method invoked is returned. * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchFieldException */ static public Object insert(Object object, String name, Object value) throws FieldException { // fix array syntax String tempExpr = name.replace('[', '.'); if (tempExpr != name) { tempExpr = tempExpr.replace(']', ' '); } int pos = tempExpr.indexOf('.'); if (pos == -1) { return basicInsert(object, name, value); } else { String pathPrefix = tempExpr.substring(0, pos); String pathTrail = tempExpr.substring(pos + 1); Object result = basicGet(object, pathPrefix); return insert(result, pathTrail, value); } } /** * Invoke method name in object. The result of the * invocation is returned. * * @param object * @param name * @param values * @return The result of the invocation is returned. * @throws MethodException */ static public Object invoke(Object object, String name, Object... values) throws MethodException { // fix array syntax String tempExpr = name.replace('[', '.'); if (tempExpr != name) { tempExpr = tempExpr.replace(']', ' '); } int pos = tempExpr.indexOf('.'); if (pos == -1) { return basicInvoke(object, name, values); } else { String pathPrefix = tempExpr.substring(0, pos); String pathTrail = tempExpr.substring(pos + 1); Object result; try { result = basicGet(object, pathPrefix); } catch (FieldException e) { throw new MethodInvocationException(name, e); } return invoke(result, pathTrail, values); } } /** * Remove value in the relation field name in * object. The value that was removed is returned (if supported * by the underlying object implementation). To be exact, the result of the * remove method invoked is returned. * * @param object * @param name * @param value * @return the result of the remove method invoked is returned. * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchFieldException */ static public Object remove(Object object, String name, Object value) throws FieldException { // fix array syntax String tempExpr = name.replace('[', '.'); if (tempExpr != name) { tempExpr = tempExpr.replace(']', ' '); } int pos = tempExpr.indexOf('.'); if (pos == -1) { return basicRemove(object, name, value); } else { String pathPrefix = tempExpr.substring(0, pos); String pathTrail = tempExpr.substring(pos + 1); Object result = basicGet(object, pathPrefix); return remove(result, pathTrail, value); } } /** * Set field name in object to value. * The old value is returned (if supported by the underlying object * implementation). To be exact, the result of the setter method invoked is * returned. * * @param object * @param name * @param value * @return the result of the setter method invoked is returned. * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchFieldException */ static public Object set(Object object, String name, Object value) throws FieldException { // fix array syntax String tempExpr = name.replace('[', '.'); if (tempExpr != name) { tempExpr = tempExpr.replace(']', ' '); } int pos = tempExpr.indexOf('.'); if (pos == -1) { return basicSet(object, name, value); } else { String pathPrefix = tempExpr.substring(0, pos); String pathTrail = tempExpr.substring(pos + 1); Object result = basicGet(object, pathPrefix); return set(result, pathTrail, value); } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/Predicates.java0000644000175000017500000000340211361073420025355 0ustar twernertwernerpackage de.intarsys.tools.reflect; import de.intarsys.tools.functor.IArgs; public class Predicates { public static class And implements IMethodHandler { private final IMethodHandler[] operators; public And(IMethodHandler[] operators) { super(); this.operators = operators; } public Object invoke(Object receiver, IArgs args) throws MethodInvocationException { for (IMethodHandler handler : operators) { if (handler.invoke(receiver, args) != Boolean.TRUE) { return false; } } return true; } } public static class Or implements IMethodHandler { private final IMethodHandler[] operators; public Or(IMethodHandler[] operators) { super(); this.operators = operators; } public Object invoke(Object receiver, IArgs args) throws MethodInvocationException { for (IMethodHandler handler : operators) { if (handler.invoke(receiver, args) == Boolean.TRUE) { return true; } } return false; } } public static final IMethodHandler FALSE = new IMethodHandler() { public Object invoke(Object receiver, IArgs args) throws MethodInvocationException { return false; } }; public static final IMethodHandler TRUE = new IMethodHandler() { public Object invoke(Object receiver, IArgs args) throws MethodInvocationException { return true; } }; public static IMethodHandler and(IMethodHandler... op) { if (op == null || op.length == 0) { return FALSE; } if (op.length == 1) { return op[0]; } return new And(op); } public static IMethodHandler or(IMethodHandler... op) { if (op == null || op.length == 0) { return TRUE; } if (op.length == 1) { return op[0]; } return new Or(op); } }libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/IFieldHandler.java0000644000175000017500000000466011355101012025723 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; /** * An object able to access a field within a delegate */ public interface IFieldHandler { /** * Make a reflective read access to the field represented by this within the * receiver. * * @param receiver * The object hosting the field. * @return The field value * @throws FieldException */ public Object getValue(Object receiver) throws FieldAccessException; /** * Make a reflective write access to the field represented by this within * receiver. * * @param receiver * The object hosting the field. * @param value * The new value for the field * @return The previous field value. This is an optional feature. * @throws FieldException */ public Object setValue(Object receiver, Object value) throws FieldAccessException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/ClassTools.java0000644000175000017500000002025311411055574025371 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * Tool class to enhance the reflective capabilities about classes. */ public class ClassTools { /** The string used to separate paths in a list of path definitions */ private static final String PATH_SEPARATOR = System .getProperty("path.separator"); /** * Create a list of all classes that are available from classPath. * *

* Be aware that the classes are loaded and so any static code is executed. *

* * @param classPath * The classpath to inspect * * @return A list of all classes that are available from classPath. * * @throws IOException */ public static List collectClasses(String classPath) throws IOException { List classNames = collectClassNames(classPath); ClassLoader loader = createClassLoader(classPath); List classes = new ArrayList(); for (Iterator it = classNames.iterator(); it.hasNext();) { String className = (String) it.next(); try { classes.add(loader.loadClass(className)); } catch (ClassNotFoundException e) { // ignore } } return classes; } /** * Create a list of class names in dot notation that can be found in the * classPath. * * @param classPath * The classpath to inspect * * @return A list of class names in dot notation that can be found in the * classPath. * * @throws IOException */ public static List collectClassNames(String classPath) throws IOException { List classnames = new ArrayList(); StringTokenizer path = new StringTokenizer(classPath, PATH_SEPARATOR); int pathCount = path.countTokens(); for (int ii = 0; ii < pathCount; ii++) { String currentName = path.nextToken(); File currentFile = new File(currentName); if (currentFile.isFile()) { extractClassNamesFromJar(classnames, currentFile); } else { extractClassNamesFromDir(classnames, currentFile, ""); } } return classnames; } public static Class createClass(String className, Class expectedClass, ClassLoader classLoader) throws ObjectCreationException { if (className == null) { throw new ObjectCreationException("class name missing"); } className = className.trim(); try { if (classLoader == null) { classLoader = Thread.currentThread().getContextClassLoader(); } if (classLoader == null) { // as good as any classLoader = expectedClass.getClassLoader(); } Class clazz = Class.forName(className, false, classLoader); if (expectedClass != null && !expectedClass.isAssignableFrom(clazz)) { throw new ObjectCreationException("class '" + clazz.getName() + "' not compatible with expected type '" + expectedClass + "'"); } return clazz; } catch (ClassNotFoundException e) { throw new ObjectCreationException("class '" + className + "' not found", e); } catch (Throwable e) { // Class.forName may throw Error when class name mismatched !! throw new ObjectCreationException("class '" + className + "' not found", e); } } /** * Create a new ClassLoader on the specified classpath * * @param classPath * The classpath we want to load from. * * @return A new ClassLoader on the specified classpath */ public static ClassLoader createClassLoader(String classPath) { URL[] allURLs = null; StringTokenizer path = new StringTokenizer(classPath, PATH_SEPARATOR); int i = path.countTokens(); allURLs = new URL[i + 1]; for (int ii = 0; ii < i; ii++) { String currentPath = path.nextToken(); try { URL url = new URL("file", "", currentPath); allURLs[ii] = url; } catch (MalformedURLException e) { // should not happen } } ClassLoader loader = URLClassLoader.newInstance(allURLs); return loader; } /** * Create a list of all classes "current" and its subdirectories. * * @param result * The collection that is filled with new classnames * @param currentFile * The directory/file under inspection * @param relativePath * The path extending from the initial root we are currently * inspecting. * * @throws IOException */ protected static void extractClassNamesFromDir(List result, File currentFile, String relativePath) throws IOException { if (currentFile.isFile()) { String filename = currentFile.getName(); if (filename.endsWith(".class")) { String className = filename.substring(0, filename.length() - 6); result.add(relativePath + className); } } else { String[] allFiles = currentFile.list(); if (allFiles == null) { throw new IOException("error creating directory listing for " + currentFile.getAbsolutePath()); } for (int i = 0; i < allFiles.length; i++) { File child = new File(currentFile, allFiles[i]); extractClassNamesFromDir(result, child, relativePath + allFiles[i] + "."); } } } /** * Create a list of all ".class" entries in the jar file. * * @param result * The collection that is filled with new classnames * @param file * The jar file we are inspecting. * * @throws IOException */ protected static void extractClassNamesFromJar(List result, File file) throws IOException { JarFile jar = null; try { jar = new JarFile(file); Enumeration entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); String entryName = entry.getName(); if (entryName.endsWith(".class")) { String className = entryName.substring(0, entryName .length() - 6); className = className.replace('/', '.'); result.add(className); } } } finally { if (jar != null) { jar.close(); } } } static public String getPackageName(Class clazz) { String name = clazz.getName(); int pos = name.lastIndexOf('.'); if (pos >= 0) { return name.substring(0, pos); } return name; } static public String getUnqualifiedName(Class clazz) { String name = clazz.getName(); int pos = name.lastIndexOf('.'); if (pos >= 0) { return name.substring(pos + 1); } return name; } /** * */ private ClassTools() { super(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reflect/IAccessHandler.java0000644000175000017500000000510411355101010026071 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reflect; /** * An object supporting handling reflective access to fields of a delegate. */ public interface IAccessHandler { /** * Make a reflective get access to the field name within * receiver * * @param receiver * The object hosting the field. * @param name * The name of the field to get. * @return The field value * @throws FieldException */ public Object getValue(Object receiver, String name) throws FieldException; /** * Make a reflective set access to the field name within * receiver * * @param receiver * The object hosting the field. * @param name * The name of the field to get. * @param value * The new value for the field * @return The previous field value. This is an optional feature. * @throws FieldException */ public Object setValue(Object receiver, String name, Object value) throws FieldException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/geometry/0000755000175000017500000000000011412336332022640 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/geometry/IShapeWrapper.java0000644000175000017500000000021111131667514026216 0ustar twernertwernerpackage de.intarsys.tools.geometry; import java.awt.Shape; public interface IShapeWrapper { public Shape getBaseShape(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/geometry/ApplyTransformationShape.java0000644000175000017500000000257011153475772030522 0ustar twernertwernerpackage de.intarsys.tools.geometry; import java.awt.Shape; import java.awt.geom.AffineTransform; /** * The transformation is defined explicitly. * */ public class ApplyTransformationShape extends TransformedShape { /** * Create a new {@link Shape} created from shape by applying * transform * * @param shape * The wrapped base shape * @param transform * The coordinate space where "shape" is defined. * * @return The new {@link TransformedShape} */ public static TransformedShape create(Shape shape, AffineTransform transform) { return new ApplyTransformationShape(shape, transform); } final private AffineTransform transform; protected ApplyTransformationShape(ApplyTransformationShape shape) { super(shape); this.transform = shape.transform; } protected ApplyTransformationShape(Shape shape, AffineTransform transform) { super(shape); this.transform = transform; } @Override protected Shape apply() { return getTransform().createTransformedShape(getBaseShape()); } /** * Returns an exact copy of this Area object. * * @return Created clone object */ @Override public Object clone() { return new ApplyTransformationShape(this); } @Override public AffineTransform getTransform() { return transform; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/geometry/GeometryTools.java0000644000175000017500000001356311411055572026332 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.geometry; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; /** * Tool class for common geometry tasks. */ public class GeometryTools { static public Point2D deltaTransformPoint(AffineTransform transform, float x, float y) { Point2D pt = new Point2D.Float(x, y); transform.deltaTransform(pt, pt); return pt; } static public void deltaTransformPoint(AffineTransform transform, float[] pts) { double[] dpts = new double[2]; dpts[0] = pts[0]; dpts[1] = pts[1]; transform.deltaTransform(dpts, 0, dpts, 0, 1); pts[0] = (float) dpts[0]; pts[1] = (float) dpts[1]; } static public void deltaTransformPoint(AffineTransform transform, Point2D pt) { transform.deltaTransform(pt, pt); } /** * Transform a rectangle in device space to user space. The rectangle is * modified. The coordinates of the result are normalized (lower left corner * has smallest coordinate values). * * @param transform * The transformation from user space to device space. * * @param rect * The rectangle whose coordinates are transformed, the rectangle * is modified. */ static public void inverseTransformRect(AffineTransform transform, Rectangle2D rect) { double[] pts = new double[4]; pts[0] = rect.getX(); pts[2] = rect.getMaxX(); pts[1] = rect.getY(); pts[3] = rect.getMaxY(); try { transform.inverseTransform(pts, 0, pts, 0, pts.length >> 1); } catch (NoninvertibleTransformException e) { // ? } rect.setRect(pts[0], pts[1], pts[2] - pts[0], pts[3] - pts[1]); normalizeRect(rect); } static public void normalizeRect(float[] pts) { float temp; if (pts[0] > pts[2]) { temp = pts[0]; pts[0] = pts[2]; pts[2] = temp; } if (pts[1] > pts[3]) { temp = pts[1]; pts[1] = pts[3]; pts[3] = temp; } } /** * Normalize the rectangle. The x and y value of the rectangle are updated * to have the smallest coordinates (lower left corner). * * @param rect * The rectangle whose coordinates are normalized, the rectangle * is modified. */ static public void normalizeRect(Rectangle2D rect) { double llx = rect.getMinX(); double lly = rect.getMinY(); double width = rect.getWidth(); double height = rect.getHeight(); if (width < 0) { llx = llx + width; width = -width; } if (height < 0) { lly = lly + height; height = -height; } rect.setRect(llx, lly, width, height); } static public float[] toFloatArray(Rectangle2D rect) { float[] pts = new float[4]; pts[0] = (float) rect.getX(); pts[1] = (float) rect.getY(); pts[2] = (float) (pts[0] + rect.getWidth()); pts[3] = (float) (pts[1] + rect.getHeight()); return pts; } static public Point2D transformPoint(AffineTransform transform, float x, float y) { Point2D pt = new Point2D.Float(x, y); transform.transform(pt, pt); return pt; } static public void transformPoint(AffineTransform transform, float[] pts) { transform.transform(pts, 0, pts, 0, 1); } static public void transformPoint(AffineTransform transform, Point2D pt) { transform.transform(pt, pt); } static public void transformRect(AffineTransform transform, float[] pts) { transform.transform(pts, 0, pts, 0, 2); GeometryTools.normalizeRect(pts); } /** * Transform a rectangle, the rectangle is modified. The coordinates of the * result are normalized (lower left corner has smallest coordinate values). * * @param transform * The transformation from user space to device space. * * @param rect * The rectangle whose coordinates are transformed, the rectangle * is modified. */ static public void transformRect(AffineTransform transform, Rectangle2D rect) { double[] pts = new double[4]; pts[0] = rect.getMinX(); pts[2] = rect.getMaxX(); pts[1] = rect.getMinY(); pts[3] = rect.getMaxY(); transform.transform(pts, 0, pts, 0, pts.length >> 1); rect.setRect(pts[0], pts[1], pts[2] - pts[0], pts[3] - pts[1]); GeometryTools.normalizeRect(rect); } /** * Tool class cannot be instantiated. */ private GeometryTools() { } } libisrt-java-4.8.20100629/src/de/intarsys/tools/geometry/TransformedShape.java0000644000175000017500000000725411153475772026776 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.geometry; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; /** * A shape that can be transformed with lazy access to the transformed shape. *

* baseShape -> transform -> shape * */ abstract public class TransformedShape implements Shape, IShapeWrapper, Cloneable { protected static final AffineTransform IDENTITY = new AffineTransform(); final private Shape baseShape; private Shape resultShape; protected TransformedShape(Shape shape) { this.baseShape = shape; this.resultShape = null; } protected TransformedShape(TransformedShape shape) { this.baseShape = shape.baseShape; this.resultShape = shape.resultShape; } abstract protected Shape apply(); @Override abstract public Object clone(); public boolean contains(double x, double y) { return getShape().contains(x, y); } public boolean contains(double x, double y, double w, double h) { return getShape().contains(x, y, w, h); } public boolean contains(Point2D p) { return getShape().contains(p); } public boolean contains(Rectangle2D r) { return getShape().contains(r); } public Shape getBaseShape() { return baseShape; } public java.awt.Rectangle getBounds() { return getShape().getBounds(); } public Rectangle2D getBounds2D() { return getShape().getBounds2D(); } public PathIterator getPathIterator(AffineTransform at) { return getShape().getPathIterator(at); } public PathIterator getPathIterator(AffineTransform at, double flatness) { return getShape().getPathIterator(at, flatness); } public Shape getShape() { if (resultShape == null) { resultShape = apply(); } return resultShape; } abstract public AffineTransform getTransform(); public boolean intersects(double x, double y, double w, double h) { return getShape().intersects(x, y, w, h); } public boolean intersects(Rectangle2D r) { return getShape().intersects(r); } public void invalidate() { resultShape = null; } }libisrt-java-4.8.20100629/src/de/intarsys/tools/geometry/ApplySpaceChangeShape.java0000644000175000017500000001000711411055572027634 0ustar twernertwernerpackage de.intarsys.tools.geometry; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.NoninvertibleTransformException; /** * The transformation is defined by two matrices, each defining a coordinate * system. The source transformation is the space the shape is defined in, the * target transformation is the space for the resulting shape. */ public class ApplySpaceChangeShape extends TransformedShape { /** * Create a new {@link Shape} whose coordinates are specified in the space * defined by "transform". * * @param shape * The wrapped base shape * @param transform * The coordinate space where "shape" is defined. * * @return The new {@link TransformedShape} */ public static TransformedShape create(Shape shape, AffineTransform transform) { if (shape instanceof ApplySpaceChangeShape) { ApplySpaceChangeShape ascShape; ascShape = (ApplySpaceChangeShape) shape; if (ascShape.getTargetTransform().equals(transform)) { return create(ascShape.getBaseShape(), ascShape .getSourceTransform(), transform); } } return create(shape, (AffineTransform) transform.clone(), transform); } public static TransformedShape create(Shape shape, AffineTransform sourceTransform, AffineTransform targetTransform) { return new ApplySpaceChangeShape(shape, sourceTransform, targetTransform); } /** * Create a new {@link Shape} that behaves like the base shape with its * coordinates relative to the new space defined by "newTransform". *

* You can use this to "view" on an already existing shape from another * coordinate system. * * @param shape * The base shape * @param targetTransform * The new coordinate space * * @return The transformed shape, showing "shape" from the space defined by * "newTransform" */ public static TransformedShape setTransform(Shape shape, AffineTransform targetTransform) { if (shape instanceof ApplySpaceChangeShape) { ApplySpaceChangeShape ts = (ApplySpaceChangeShape) shape; return new ApplySpaceChangeShape(ts.getBaseShape(), ts .getSourceTransform(), targetTransform); } return new ApplySpaceChangeShape(shape, IDENTITY, targetTransform); } final private AffineTransform sourceTransform; final private AffineTransform targetTransform; protected ApplySpaceChangeShape(ApplySpaceChangeShape shape) { super(shape); this.sourceTransform = shape.sourceTransform; this.targetTransform = (AffineTransform) shape.targetTransform.clone(); } protected ApplySpaceChangeShape(Shape shape, AffineTransform sourceTransform, AffineTransform targetTransform) { super(shape); this.sourceTransform = sourceTransform; this.targetTransform = targetTransform; } @Override protected Shape apply() { if (targetTransform.equals(sourceTransform)) { return getBaseShape(); } if (getBaseShape() instanceof Area) { return new Area(getTransform().createTransformedShape( getBaseShape())); } else { return getTransform().createTransformedShape(getBaseShape()); } } /** * Returns an exact copy of this Area object. * * @return Created clone object */ @Override public Object clone() { return new ApplySpaceChangeShape(this); } public AffineTransform getSourceTransform() { return sourceTransform; } public AffineTransform getTargetTransform() { return targetTransform; } @Override public AffineTransform getTransform() { try { if (targetTransform.equals(sourceTransform)) { return new AffineTransform(); } AffineTransform tempTransform = targetTransform.createInverse(); tempTransform.concatenate(sourceTransform); return tempTransform; } catch (NoninvertibleTransformException e) { // this happens indeed if some nerd scales down presentation // excessive.. return new AffineTransform(0, 0, 0, 0, 0, 0); } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/geometry/DeltaTransform.java0000644000175000017500000000316711031114214026425 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.geometry; public class DeltaTransform { } libisrt-java-4.8.20100629/src/de/intarsys/tools/geometry/ShapeTools.java0000644000175000017500000000175611412330272025572 0ustar twernertwernerpackage de.intarsys.tools.geometry; import java.awt.Shape; import java.awt.geom.Area; import java.awt.geom.GeneralPath; import java.awt.geom.PathIterator; public class ShapeTools { static public Area createArea(Shape shape, boolean copy) { if (shape == null) { return null; } if (shape instanceof TransformedShape) { shape = ((TransformedShape) shape).getShape(); } if (shape instanceof Area) { if (copy) { return (Area) ((Area) shape).clone(); } else { return (Area) shape; } } return new Area(shape); } /** * Returns the shapes fill style winding rule. * * @return an integer representing the shapes winding rule. */ static public int getWindingRule(Shape shape) { if (shape instanceof IShapeWrapper) { return getWindingRule(((IShapeWrapper) shape).getBaseShape()); } if (shape instanceof GeneralPath) { return ((GeneralPath) shape).getWindingRule(); } return PathIterator.WIND_NON_ZERO; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reporter/0000755000175000017500000000000011412336332022647 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/reporter/ReportDispatcher.java0000644000175000017500000001200411411055574026776 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reporter; /** * Helper object for implementing {@link IReporterSupport}. */ public class ReportDispatcher implements IReporterSupport, IReporter { private final Object owner; private IReporter[] reporters = new IReporter[2]; public ReportDispatcher(Object pOwner) { super(); owner = pOwner; } public synchronized void addReporter(IReporter newReporter) { if (newReporter == null) { throw new NullPointerException("reporter may not be null"); } int length = reporters.length; int i = 0; while (i < length) { if (reporters[i] == null) { break; } i++; } if (i >= length) { IReporter[] tempReporters = new IReporter[length + 4]; System.arraycopy(reporters, 0, tempReporters, 0, length); reporters = tempReporters; } reporters[i] = newReporter; } synchronized public void attach(IReporterSupport support) { int length = reporters.length; for (int i = 0; i < length; i++) { support.addReporter(reporters[i]); } } public synchronized void clear() { reporters = new IReporter[4]; } synchronized public void detach(IReporterSupport support) { int length = reporters.length; for (int i = 0; i < length; i++) { support.removeReporter(reporters[i]); } } public Object getOwner() { return owner; } public synchronized boolean isEmpty() { for (int i = 0; i < reporters.length; i++) { if (reporters[i] != null) { return false; } } return true; } synchronized public void removeReporter(IReporter newReporter) { int length = reporters.length; int i = 0; while (i < length) { if (reporters[i] == newReporter) { reporters[i] = null; break; } i++; } } public void reportActivityEnd() { int length = reporters.length; for (int i = 0; i < length; i++) { IReporter tempReporter = reporters[i]; if (tempReporter == null) { continue; } tempReporter.reportActivityEnd(); } } public void reportActivityStart(String message, int style) { int length = reporters.length; for (int i = 0; i < length; i++) { IReporter tempReporter = reporters[i]; if (tempReporter == null) { continue; } tempReporter.reportActivityStart(message, style); } } public void reportError(String title, String message, Throwable t, int style) { int length = reporters.length; for (int i = 0; i < length; i++) { IReporter tempReporter = reporters[i]; if (tempReporter == null) { continue; } tempReporter.reportError(title, message, t, style); } } public void reportMessage(String title, String message, int style) { int length = reporters.length; for (int i = 0; i < length; i++) { IReporter tempReporter = reporters[i]; if (tempReporter == null) { continue; } tempReporter.reportMessage(title, message, style); } } public void reportProgress(String message, int percent, int style) { int length = reporters.length; for (int i = 0; i < length; i++) { IReporter tempReporter = reporters[i]; if (tempReporter == null) { continue; } tempReporter.reportProgress(message, percent, style); } } public void reportStatus(String message, int style) { int length = reporters.length; for (int i = 0; i < length; i++) { IReporter tempReporter = reporters[i]; if (tempReporter == null) { continue; } tempReporter.reportStatus(message, style); } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reporter/Reporter.java0000644000175000017500000000413311044020124025303 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reporter; /** * */ abstract public class Reporter { private static IReporter ACTIVE = new DefaultReporter(); public static IReporter get() { return ACTIVE; } /** * returns the old active reporter */ public static IReporter set(IReporter newReporter) { if (newReporter == null) { throw new NullPointerException("reporter can't be null"); //$NON-NLS-1$ } IReporter old = ACTIVE; ACTIVE = newReporter; return old; } /** * */ private Reporter() { // singleton } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reporter/ReplayReporter.java0000644000175000017500000001122511411055574026477 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reporter; /** * An {@link IReporter} that may be used to intercept the reporting information * and "replay" them later on on another {@link IReporter} instance. *

* This is useful if an object receiving reporting information may be * dynamically multiplexed on many reporting events emitting instances, for * example a window showing a currently active object. */ public class ReplayReporter implements IReporter, IReporterSupport { private final Object owner; final private ReportDispatcher dispatcher; final private ReportMessage[] messages = new ReportMessage[10]; private int first = 0; public ReplayReporter(Object owner) { super(); this.owner = owner; this.dispatcher = new ReportDispatcher(owner); } protected void addMessage(ReportMessage message) { messages[first] = message; first = (first + 1) % messages.length; } public void addReporter(IReporter reporter) { dispatcher.addReporter(reporter); replay(reporter); } public Object getOwner() { return owner; } public void removeReporter(IReporter reporter) { dispatcher.removeReporter(reporter); } protected void replay(IReporter reporter) { for (int i = 0; i < messages.length; i++) { int index = (i + first) % messages.length; ReportMessage message = messages[index]; if (message == null) { continue; } if (message.isStatus()) { reporter.reportStatus(message.getMessage(), message.getStyle()); } else if (message.isMessage()) { reporter.reportMessage(message.getTitle(), message.getMessage(), message.getStyle()); } else if (message.isError()) { reporter.reportError(message.getTitle(), message.getMessage(), message.getThrowable(), message.getStyle()); } else { // ignore } } } public void reportActivityEnd() { addMessage(new ReportMessage(ReportMessage.TYPE_ACTIVITY_END, null, null, IReporter.STYLE_NONE, 0, null)); dispatcher.reportActivityEnd(); } public void reportActivityStart(String activity, int style) { addMessage(new ReportMessage(ReportMessage.TYPE_ACTIVITY_START, null, activity, style, 0, null)); dispatcher.reportActivityStart(activity, style); } public void reportError(String title, String message, Throwable t, int style) { addMessage(new ReportMessage(ReportMessage.TYPE_ERROR, title, message, style, 0, t)); dispatcher.reportError(title, message, t, style); } public void reportMessage(String title, String message, int style) { addMessage(new ReportMessage(ReportMessage.TYPE_MESSAGE, title, message, style, 0, null)); dispatcher.reportMessage(title, message, style); } public void reportProgress(String message, int percent, int style) { addMessage(new ReportMessage(ReportMessage.TYPE_PROGRESS, null, message, style, percent, null)); dispatcher.reportProgress(message, percent, style); } public void reportStatus(String message, int style) { addMessage(new ReportMessage(ReportMessage.TYPE_STATUS, null, message, style, 0, null)); dispatcher.reportStatus(message, style); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reporter/ReportMessage.java0000644000175000017500000000367711334524170026311 0ustar twernertwernerpackage de.intarsys.tools.reporter; public class ReportMessage { public static final int TYPE_PROGRESS = 0; public static final int TYPE_ACTIVITY_START = 1; public static final int TYPE_ACTIVITY_END = 2; public static final int TYPE_STATUS = 3; public static final int TYPE_MESSAGE = 4; public static final int TYPE_ERROR = 5; private String title; private String message; private int style; private int percent; private int type; private Throwable throwable; public ReportMessage(int type, String title, String message, int style, int percent, Throwable throwable) { super(); this.type = type; this.title = title; this.message = message; this.style = style; this.percent = percent; this.throwable = throwable; } public String getMessage() { return message; } public int getPercent() { return percent; } public int getStyle() { return style; } public Throwable getThrowable() { return throwable; } public String getTitle() { return title; } public int getType() { return type; } public boolean isActivityEnd() { return type == TYPE_ACTIVITY_END; } public boolean isActivityStart() { return type == TYPE_ACTIVITY_START; } public boolean isError() { return type == TYPE_ERROR; } public boolean isMessage() { return type == TYPE_MESSAGE; } public boolean isProgress() { return type == TYPE_PROGRESS; } public boolean isStatus() { return type == TYPE_STATUS; } public void setMessage(String message) { this.message = message; } public void setPercent(int percent) { this.percent = percent; } public void setStyle(int style) { this.style = style; } public void setThrowable(Throwable throwable) { this.throwable = throwable; } public void setTitle(String title) { this.title = title; } public void setType(int type) { this.type = type; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reporter/DefaultReporter.java0000644000175000017500000000605211207251442026624 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reporter; import java.util.logging.Level; import java.util.logging.Logger; import de.intarsys.tools.logging.LogTools; /** * The default reporting implementation for the Stage kernel. This one is just * logging to java standard logging. * */ public class DefaultReporter implements IReporter { final private Logger logger; public DefaultReporter() { this(LogTools.getLogger(DefaultReporter.class)); } public DefaultReporter(Logger logger) { super(); this.logger = logger; } protected Logger getLogger() { return logger; } public void reportActivityEnd() { if (getLogger().isLoggable(Level.FINEST)) { getLogger().log(Level.FINEST, "end activity "); //$NON-NLS-1$ } } public void reportActivityStart(String activity, int style) { if (getLogger().isLoggable(Level.FINEST)) { getLogger().log(Level.FINEST, "start activity " + activity); //$NON-NLS-1$ } } public void reportError(String title, String message, Throwable t, int style) { getLogger().log(Level.SEVERE, message, t); } public void reportMessage(String title, String message, int style) { getLogger().log(Level.INFO, message); } public void reportProgress(String text, int percent, int style) { if (getLogger().isLoggable(Level.FINEST)) { getLogger().log(Level.FINEST, text + " [" + percent + "%]"); //$NON-NLS-1$ //$NON-NLS-2$ } } public void reportStatus(String text, int style) { getLogger().log(Level.INFO, text); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reporter/IReporterSupport.java0000644000175000017500000000345011411055574027031 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reporter; /** * An object that supports state notifications. * */ public interface IReporterSupport { public void addReporter(IReporter newReporter); public void removeReporter(IReporter newReporter); } libisrt-java-4.8.20100629/src/de/intarsys/tools/reporter/IReporter.java0000644000175000017500000000655411207256066025446 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reporter; /** * An interface to report different types of information to the user. *

* This may be implemented for example as pure logging in a headless environment * or with message dialogs in a window system. * */ public interface IReporter { public static final int STYLE_NONE = 0; public static final int STYLE_STANDALONE = 1; public static final int STYLE_BEEP = 2; /** * Indicate the end of an activity. */ public void reportActivityEnd(); /** * Indicate the beginning of an activity, possibly blocking system * interaction. * * @param message * A label for reporting the activity. * @param style */ public void reportActivityStart(String message, int style); /** * Indicate an error condition. This method will return normally after a * possible user interaction, any error handling is still up to the caller. * * @param title * @param message * @param t * @param style */ public void reportError(final String title, final String message, final Throwable t, int style); /** * Report a message to the user. The message should be displayed in a * blocking way in an interactive system. * * @param title * @param message * @param style */ public void reportMessage(final String title, final String message, int style); /** * Indicate the progress of an ongoing activity. The activity will probably * run concurrently. * * @param message * @param percent * @param style */ public void reportProgress(String message, int percent, int style); /** * Report a simple state information. This should not block the system in * any way. * * @param message * @param style */ public void reportStatus(String message, int style); } libisrt-java-4.8.20100629/src/de/intarsys/tools/reporter/NullReporter.java0000644000175000017500000000413711207251442026154 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reporter; /** * A null implementation for {@link IReporter}. */ public class NullReporter implements IReporter { public void reportActivityEnd() { } public void reportActivityStart(String activity, int style) { } public void reportError(String title, String message, Throwable t, int style) { } public void reportMessage(String title, String message, int style) { } public void reportProgress(String text, int percent, int style) { } public void reportStatus(String text, int style) { } } libisrt-java-4.8.20100629/src/de/intarsys/tools/preferences/0000755000175000017500000000000011412336332023306 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/preferences/PreferencesFactory.java0000644000175000017500000000400011251000056027724 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.preferences; /** * A VM singleton for a {@link IPreferencesFactory} */ public class PreferencesFactory { /** * The VM wide IPreferencesFactory */ private static IPreferencesFactory ACTIVE = new NullPreferencesFactory(); public static IPreferencesFactory get() { return ACTIVE; } public static void set(IPreferencesFactory active) { ACTIVE = active; } private PreferencesFactory() { super(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/preferences/IntegerPrefValueHolder.java0000644000175000017500000000413011251000056030504 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.preferences; /** * A {@link PrefValueHolder} implementation for integer typed values. * */ public class IntegerPrefValueHolder extends PrefValueHolder { public IntegerPrefValueHolder(IPreferences preferences, String key, int defaultValue) { super(preferences, key, defaultValue); } public Object get() { return getPreferences().getInt(getKey(), (Integer) getDefaultValue()); } public Object set(Object newValue) { getPreferences().put(getKey(), (Integer) newValue); return null; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/preferences/NullPreferences.java0000644000175000017500000002242511411055574027257 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.preferences; import java.util.Collections; import java.util.Map; import java.util.prefs.BackingStoreException; import de.intarsys.tools.string.StringTools; /** * A "null" {@link IPreferences} implementation. */ public class NullPreferences implements IPreferences { public static final NullPreferences ACTIVE = new NullPreferences(); /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#absolutePath() */ public String absolutePath() { return StringTools.EMPTY; } public IPreferences[] children() { return new IPreferences[0]; } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#childrenNames() */ public String[] childrenNames() throws BackingStoreException { return new String[0]; } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#clear() */ public void clear() throws BackingStoreException { // do nothing } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#flush() */ public void flush() throws BackingStoreException { // do nothing } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#get(java.lang.String) */ public String get(String name) { return null; } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#get(java.lang.String, * java.lang.String) */ public String get(String key, String def) { return def; } /* * (non-Javadoc) * * @see * de.intarsys.tools.preferences.IPreferences#getBoolean(java.lang.String) */ public boolean getBoolean(String name) { return false; } /* * (non-Javadoc) * * @see * de.intarsys.tools.preferences.IPreferences#getBoolean(java.lang.String, * boolean) */ public boolean getBoolean(String key, boolean def) { return def; } /* * (non-Javadoc) * * @see * de.intarsys.tools.preferences.IPreferences#getByteArray(java.lang.String, * byte[]) */ public byte[] getByteArray(String key, byte[] def) { return def; } /* * (non-Javadoc) * * @see * de.intarsys.tools.preferences.IPreferences#getDouble(java.lang.String) */ public double getDouble(String name) { return 0; } /* * (non-Javadoc) * * @see * de.intarsys.tools.preferences.IPreferences#getDouble(java.lang.String, * double) */ public double getDouble(String key, double def) { return def; } /* * (non-Javadoc) * * @see * de.intarsys.tools.preferences.IPreferences#getFloat(java.lang.String) */ public float getFloat(String name) { return 0; } /* * (non-Javadoc) * * @see * de.intarsys.tools.preferences.IPreferences#getFloat(java.lang.String, * float) */ public float getFloat(String key, float def) { return def; } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#getInt(java.lang.String) */ public int getInt(String name) { return 0; } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#getInt(java.lang.String, * int) */ public int getInt(String key, int def) { return def; } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#getLong(java.lang.String) */ public long getLong(String name) { return 0; } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#getLong(java.lang.String, * long) */ public long getLong(String key, long def) { return def; } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#keys() */ public String[] keys() { return new String[0]; } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#name() */ public String name() { return StringTools.EMPTY; } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#node(java.lang.String) */ public IPreferences node(String pathName) { return this; } /* * (non-Javadoc) * * @see * de.intarsys.tools.preferences.IPreferences#nodeExists(java.lang.String) */ public boolean nodeExists(String pathName) throws BackingStoreException { return false; } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#parent() */ public IPreferences parent() { return null; } public Map properties() { return Collections.EMPTY_MAP; } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#put(java.lang.String, * boolean) */ public void put(String name, boolean value) { // do nothing } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#put(java.lang.String, * byte[]) */ public void put(String key, byte[] value) { // do nothing } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#put(java.lang.String, * double) */ public void put(String name, double value) { // do nothing } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#put(java.lang.String, * float) */ public void put(String name, float value) { // do nothing } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#put(java.lang.String, * int) */ public void put(String name, int value) { // do nothing } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#put(java.lang.String, * long) */ public void put(String name, long value) { // do nothing } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#put(java.lang.String, * java.lang.String) */ public void put(String name, String value) { // do nothing } /* * (non-Javadoc) * * @see * de.intarsys.tools.preferences.IPreferences#putBoolean(java.lang.String, * boolean) */ public void putBoolean(String key, boolean value) { // do nothing } /* * (non-Javadoc) * * @see * de.intarsys.tools.preferences.IPreferences#putByteArray(java.lang.String, * byte[]) */ public void putByteArray(String key, byte[] value) { // do nothing } /* * (non-Javadoc) * * @see * de.intarsys.tools.preferences.IPreferences#putDouble(java.lang.String, * double) */ public void putDouble(String key, double value) { // do nothing } /* * (non-Javadoc) * * @see * de.intarsys.tools.preferences.IPreferences#putFloat(java.lang.String, * float) */ public void putFloat(String key, float value) { // do nothing } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#putInt(java.lang.String, * int) */ public void putInt(String key, int value) { // do nothing } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#putLong(java.lang.String, * long) */ public void putLong(String key, long value) { // do nothing } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#remove(java.lang.String) */ public void remove(String key) { // do nothing } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#removeNode() */ public void removeNode() throws BackingStoreException { // do nothing } /* * (non-Javadoc) * * @see * de.intarsys.tools.preferences.IPreferences#restrict(java.lang.String) */ public IPreferences restrict(String scopeName) { return this; } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferences#sync() */ public void sync() throws BackingStoreException { // do nothing } } libisrt-java-4.8.20100629/src/de/intarsys/tools/preferences/PreferencesTools.java0000644000175000017500000002351011251000056027424 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.preferences; import java.awt.Rectangle; import java.io.StringReader; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import de.intarsys.tools.enumeration.EnumItem; import de.intarsys.tools.enumeration.EnumMeta; import de.intarsys.tools.string.CharacterTools; import de.intarsys.tools.string.Converter; import de.intarsys.tools.string.ConverterException; /** * A tool class for some common tasks when dealing with {@link IPreferences}. * */ public class PreferencesTools { public static final String ELEMENT_SEPARATOR = ";"; //$NON-NLS-1$ public static final String KEY_VALUE_SEPARATOR = "="; //$NON-NLS-1$ static public String fitKey(String name) { int length = name.length(); if (length <= Preferences.MAX_KEY_LENGTH) { return name; } StringBuilder sb = new StringBuilder(); char[] chars = new char[length]; name.getChars(0, length, chars, 0); boolean start = true; for (int i = 0; i < length; i++) { char c = chars[i]; if (c == '.' || c == '/' || c == '\\' || c == '_') { start = true; continue; } if (Character.isUpperCase(c) || c == '.') { start = true; sb.append(c); continue; } if (CharacterTools.isVowel(c)) { if (start) { start = false; sb.append(c); } continue; } sb.append(c); } name = sb.toString(); length = name.length(); if (length <= Preferences.MAX_KEY_LENGTH) { return name; } return name.substring(length - Preferences.MAX_KEY_LENGTH, length); } public static T getEnumItem(IPreferences preferences, EnumMeta meta, String name) { if (preferences == null) { return meta.getDefault(); } String optionValue = preferences.get(name); return meta.getItemOrDefault(optionValue); } public static T getEnumItem(IPreferences preferences, EnumMeta meta, String name, String defaultValue) { if (preferences == null) { return meta.getItemOrDefault(defaultValue); } String optionValue = preferences.get(name, defaultValue); return meta.getItemOrDefault(optionValue); } public static String getLarge(IPreferences preferences, String key, String defaultValue) { if (preferences == null) { return null; } IPreferences childNode = preferences.node(key); int i = 0; String subKey = "part" + i++; //$NON-NLS-1$ String subValue = childNode.get(subKey, null); if (subValue == null) { return null; } StringBuilder sb = new StringBuilder(); while ((subValue != null) && (subValue.length() == Preferences.MAX_VALUE_LENGTH)) { sb.append(subValue); subKey = "part" + i++; //$NON-NLS-1$ subValue = childNode.get(subKey, null); } // read terminator if (subValue != null) { sb.append(subValue); } return sb.toString(); } public static void importPreferences(IPreferences root, IPreferences source) throws BackingStoreException { String[] childrenNames = source.childrenNames(); for (int i = 0; i < childrenNames.length; i++) { String childName = childrenNames[i]; IPreferences rootChild = root.node(childName); IPreferences sourceChild = source.node(childName); importPreferences(rootChild, sourceChild); } String[] keys = source.keys(); for (int i = 0; i < keys.length; i++) { String key = keys[i]; root.put(key, source.get(key)); } } public static void putEnumItem(IPreferences preferences, String name, EnumItem item) { preferences.put(name, item.getId()); } public static void putLarge(IPreferences preferences, String key, String longValue) { try { preferences.remove(key); IPreferences childNode = preferences.node(key); childNode.clear(); StringReader reader = new StringReader(longValue); char[] buffer = new char[Preferences.MAX_VALUE_LENGTH]; int i = 0; String subKey; String subValue = null; int length = reader.read(buffer); while (length != -1) { subKey = "part" + i++; //$NON-NLS-1$ subValue = new String(buffer, 0, length); childNode.put(subKey, subValue); length = reader.read(buffer); } // write terminator if ((subValue != null) && (subValue.length() == Preferences.MAX_VALUE_LENGTH)) { subKey = "part" + i++; //$NON-NLS-1$ subValue = ""; //$NON-NLS-1$ childNode.put(subKey, subValue); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Rectangle toRect(String value) { if (value == null) { return null; } int[] rectDef = Converter.asIntArray(value); if ((rectDef == null) || (rectDef.length < 4)) { return null; } return new Rectangle(rectDef[0], rectDef[1], rectDef[2], rectDef[3]); } public static Rectangle toRect(String value, int[] ranges) { if (value == null) { return null; } String[] rectDefs = Converter.asStringArray(value); if ((rectDefs == null) || (rectDefs.length != 4)) { return null; } int[] rectValues = new int[4]; for (int i = 0; i < rectDefs.length; i++) { String rectDef = rectDefs[i]; if (rectDef.indexOf("%") >= 0) { rectDef = rectDef.replaceAll("%", ""); try { rectValues[i] = (int) ((float) Converter.asInteger(rectDef) * (float) ranges[i] / 100f); } catch (ConverterException e) { rectValues[i] = 0; } } else { try { rectValues[i] = Converter.asInteger(rectDef); } catch (ConverterException e) { rectValues[i] = 0; } } } return new Rectangle(rectValues[0], rectValues[1], rectValues[2], rectValues[3]); } public static String toString(float[] value) { if (value == null) { return ""; //$NON-NLS-1$ } StringBuilder sb = new StringBuilder(); if (value != null) { for (int i = 0; i < value.length; i++) { if (i != 0) { sb.append(ELEMENT_SEPARATOR); } sb.append(value[i]); } } return sb.toString(); } public static String toString(int[] value) { if (value == null) { return ""; //$NON-NLS-1$ } StringBuilder sb = new StringBuilder(); for (int i = 0; i < value.length; i++) { if (i != 0) { sb.append(ELEMENT_SEPARATOR); } sb.append(value[i]); } return sb.toString(); } public static String toString(List value) { if (value == null) { return ""; //$NON-NLS-1$ } StringBuilder sb = new StringBuilder(); for (Iterator it = value.iterator(); it.hasNext();) { Object element = it.next(); sb.append(String.valueOf(element)); if (it.hasNext()) { sb.append(ELEMENT_SEPARATOR); } } return sb.toString(); } public static String toString(Map map) { if (map == null) { return ""; //$NON-NLS-1$ } StringBuilder sb = new StringBuilder(); for (Iterator i = map.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); sb.append(String.valueOf(entry.getKey())); sb.append(KEY_VALUE_SEPARATOR); Object value = (entry.getValue() == null) ? "" : String .valueOf(entry.getValue()); //$NON-NLS-1$ sb.append(value); if (i.hasNext()) { sb.append(ELEMENT_SEPARATOR); } } return sb.toString(); } public static String toString(Rectangle rect) { if (rect == null) { return ""; //$NON-NLS-1$ } int[] rectDef = new int[] { rect.x, rect.y, rect.width, rect.height }; return PreferencesTools.toString(rectDef); } public static String toString(String[] value) { if (value == null) { return ""; //$NON-NLS-1$ } StringBuilder sb = new StringBuilder(); for (int i = 0; i < value.length; i++) { if (i != 0) { sb.append(ELEMENT_SEPARATOR); } sb.append(value[i]); } return sb.toString(); } public static String[] toStringArray(String value) { if (value == null) { return null; } StringTokenizer tk = new StringTokenizer(value, ELEMENT_SEPARATOR, false); String[] result = new String[tk.countTokens()]; int i = 0; while (tk.hasMoreTokens()) { String token = tk.nextToken(); result[i] = token.trim(); i++; } return result; } /** * */ private PreferencesTools() { // tool class } } libisrt-java-4.8.20100629/src/de/intarsys/tools/preferences/StringPrefValueHolder.java0000644000175000017500000000412311251000056030357 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.preferences; /** * A {@link PrefValueHolder} implementation for String typed values. * */ public class StringPrefValueHolder extends PrefValueHolder { public StringPrefValueHolder(IPreferences preferences, String key, String defaultValue) { super(preferences, key, defaultValue); } public Object get() { return getPreferences().get(getKey(), (String) getDefaultValue()); } public Object set(Object newValue) { getPreferences().put(getKey(), (String) newValue); return null; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/preferences/IPreferences.java0000644000175000017500000010044211412330302026513 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.preferences; import java.util.Map; import java.util.prefs.BackingStoreException; /** * Yet another preferences abstraction. *

* This is very close to the native Java preferences with the additional feature * of "scoping" (and some other minor deviations). */ public interface IPreferences { /** * The non - persistent default settings */ public static final String SCOPE_DEFAULT = "DEFAULT"; //$NON-NLS-1$ /** * The preferences provided with the instrument installation */ public static final String SCOPE_INSTALLATION = "INSTALLATION"; //$NON-NLS-1$ /** * Preferences for all users */ public static final String SCOPE_GLOBAL = "GLOBAL"; //$NON-NLS-1$ /** * Preferences for a dedicated team of users */ public static final String SCOPE_TEAM = "TEAM"; //$NON-NLS-1$ /** * Preferences for a specific user */ public static final String SCOPE_USER = "USER"; //$NON-NLS-1$ /** * Returns this preference node's absolute path name. * * @return this preference node's absolute path name. */ public String absolutePath(); /** * The array of all child preferences. * * @return The array of all child preferences. */ public IPreferences[] children(); /** * Returns the names of the children of this preference node, relative to * this node. (The returned array will be of size zero if this node has no * children.) * * @return the names of the children of this preference node. * @throws BackingStoreException * if this operation cannot be completed due to a failure in the * backing store, or inability to communicate with it. */ public String[] childrenNames() throws BackingStoreException; /** * Removes all of the preferences (key-value associations) in this * preference node. This call has no effect on any descendants of this node. * *

* If this implementation supports stored defaults, and this node in * the preferences hierarchy contains any such defaults, the stored defaults * will be "exposed" by this call, in the sense that they will be returned * by succeeding calls to get. * * @throws BackingStoreException * if this operation cannot be completed due to a failure in the * backing store, or inability to communicate with it. * @throws IllegalStateException * if this node (or an ancestor) has been removed with the * {@link #removeNode()} method. * @see #removeNode() */ public void clear() throws BackingStoreException; /** * Forces any changes in the contents of this preference node and its * descendants to the persistent store. Once this method returns * successfully, it is safe to assume that all changes made in the subtree * rooted at this node prior to the method invocation have become permanent. * *

* Implementations are free to flush changes into the persistent store at * any time. They do not need to wait for this method to be called. * *

* When a flush occurs on a newly created node, it is made persistent, as * are any ancestors (and descendants) that have yet to be made persistent. * Note however that any preference value changes in ancestors are * not guaranteed to be made persistent. * *

* If this method is invoked on a node that has been removed with the * {@link #removeNode()} method, flushSpi() is invoked on this node, but not * on others. * * @throws BackingStoreException * if this operation cannot be completed due to a failure in the * backing store, or inability to communicate with it. * @see #sync() */ public void flush() throws BackingStoreException; /** * Returns the current value of the string-valued preference with the given * name. Returns the default-default value (the empty string "" * ) if there is no preference with the given name, or if the current value * cannot be treated as a string. * * @param name * the name of the preference * * @return the string-valued preference */ public String get(String name); /** * Returns the value associated with the specified key in this preference * node. Returns the specified default if there is no value associated with * the key, or the backing store is inaccessible. * *

* Some implementations may store default values in their backing stores. If * there is no value associated with the specified key but there is such a * stored default, it is returned in preference to the specified * default. * * @param key * key whose associated value is to be returned. * @param def * the value to be returned in the event that this preference * node has no value associated with key. * @return the value associated with key, or def if no * value is associated with key, or the backing store is * inaccessible. * @throws IllegalStateException * if this node (or an ancestor) has been removed with the * {@link #removeNode()} method. * @throws NullPointerException * if key is null. (A null value for * def is permitted.) */ public String get(String key, String def); /** * Returns the current value of the boolean-valued preference with the given * name. Returns the default-default value (false) if there is * no preference with the given name, or if the current value cannot be * treated as a boolean. * * @param name * the name of the preference * * @return the boolean-valued preference */ public boolean getBoolean(String name); /** * Returns the boolean value represented by the string associated with the * specified key in this preference node. Valid strings are "true", * which represents true, and "false", which represents false. Case * is ignored, so, for example, "TRUE" and "False" are * also valid. This method is intended for use in conjunction with * {@link #putBoolean}. * *

* Returns the specified default if there is no value associated with the * key, the backing store is inaccessible, or if the associated value is * something other than "true" or "false", ignoring case. * *

* If the implementation supports stored defaults and such a default * exists and is accessible, it is used in preference to the specified * default, unless the stored default is something other than * "true" or "false", ignoring case, in which case the * specified default is used. * * @param key * key whose associated value is to be returned as a boolean. * @param def * the value to be returned in the event that this preference * node has no value associated with key or the * associated value cannot be interpreted as a boolean, or the * backing store is inaccessible. * @return the boolean value represented by the string associated with * key in this preference node, or def if the * associated value does not exist or cannot be interpreted as a * boolean. * @throws IllegalStateException * if this node (or an ancestor) has been removed with the * {@link #removeNode()} method. * @throws NullPointerException * if key is null. * @see #get(String,String) * @see #putBoolean(String,boolean) */ public boolean getBoolean(String key, boolean def); /** * Returns the byte array value represented by the string associated with * the specified key in this preference node. Valid strings are * Base64 encoded binary data, as defined in RFC 2045, Section 6.8, with * one minor change: the string must consist solely of characters from the * Base64 Alphabet; no newline characters or extraneous characters * are permitted. This method is intended for use in conjunction with * {@link #putByteArray}. * *

* Returns the specified default if there is no value associated with the * key, the backing store is inaccessible, or if the associated value is not * a valid Base64 encoded byte array (as defined above). * *

* If the implementation supports stored defaults and such a default * exists and is accessible, it is used in preference to the specified * default, unless the stored default is not a valid Base64 encoded byte * array (as defined above), in which case the specified default is used. * * @param key * key whose associated value is to be returned as a byte array. * @param def * the value to be returned in the event that this preference * node has no value associated with key or the * associated value cannot be interpreted as a byte array, or the * backing store is inaccessible. * @return the byte array value represented by the string associated with * key in this preference node, or def if the * associated value does not exist or cannot be interpreted as a * byte array. * @throws IllegalStateException * if this node (or an ancestor) has been removed with the * {@link #removeNode()} method. * @throws NullPointerException * if key is null. (A null value for * def is permitted.) * @see #get(String,String) * @see #putByteArray(String,byte[]) */ public byte[] getByteArray(String key, byte[] def); /** * Returns the current value of the double-valued preference with the given * name. Returns the default-default value (0.0) if there is no * preference with the given name, or if the current value cannot be treated * as a double. * * @param name * the name of the preference * * @return the double-valued preference */ public double getDouble(String name); /** * Returns the double value represented by the string associated with the * specified key in this preference node. The string is converted to an * integer as by {@link Double#parseDouble(String)}. Returns the specified * default if there is no value associated with the key, the backing store * is inaccessible, or if Double.parseDouble(String) would throw a * {@link NumberFormatException} if the associated value were passed. This * method is intended for use in conjunction with {@link #putDouble}. * *

* If the implementation supports stored defaults and such a default * exists, is accessible, and could be converted to a double with * Double.parseDouble, this double is returned in preference to the * specified default. * * @param key * key whose associated value is to be returned as a double. * @param def * the value to be returned in the event that this preference * node has no value associated with key or the * associated value cannot be interpreted as a double, or the * backing store is inaccessible. * @return the double value represented by the string associated with * key in this preference node, or def if the * associated value does not exist or cannot be interpreted as a * double. * @throws IllegalStateException * if this node (or an ancestor) has been removed with the * {@link #removeNode()} method. * @throws NullPointerException * if key is null. * @see #putDouble(String,double) * @see #get(String,String) */ public double getDouble(String key, double def); /** * Returns the current value of the float-valued preference with the given * name. Returns the default-default value (0.0f) if there is * no preference with the given name, or if the current value cannot be * treated as a float. * * @param name * the name of the preference * * @return the float-valued preference */ public float getFloat(String name); /** * Returns the float value represented by the string associated with the * specified key in this preference node. The string is converted to an * integer as by {@link Float#parseFloat(String)}. Returns the specified * default if there is no value associated with the key, the backing store * is inaccessible, or if Float.parseFloat(String) would throw a * {@link NumberFormatException} if the associated value were passed. This * method is intended for use in conjunction with {@link #putFloat}. * *

* If the implementation supports stored defaults and such a default * exists, is accessible, and could be converted to a float with * Float.parseFloat, this float is returned in preference to the * specified default. * * @param key * key whose associated value is to be returned as a float. * @param def * the value to be returned in the event that this preference * node has no value associated with key or the * associated value cannot be interpreted as a float, or the * backing store is inaccessible. * @return the float value represented by the string associated with * key in this preference node, or def if the * associated value does not exist or cannot be interpreted as a * float. * @throws IllegalStateException * if this node (or an ancestor) has been removed with the * {@link #removeNode()} method. * @throws NullPointerException * if key is null. * @see #putFloat(String,float) * @see #get(String,String) */ public float getFloat(String key, float def); /** * Returns the current value of the integer-valued preference with the given * name. Returns the default-default value (0) if there is no * preference with the given name, or if the current value cannot be treated * as an integer. * * @param name * the name of the preference * * @return the int-valued preference */ public int getInt(String name); /** * Returns the int value represented by the string associated with the * specified key in this preference node. The string is converted to an * integer as by {@link Integer#parseInt(String)}. Returns the specified * default if there is no value associated with the key, the backing store * is inaccessible, or if Integer.parseInt(String) would throw a * {@link NumberFormatException} if the associated value were passed. This * method is intended for use in conjunction with {@link #putInt}. * *

* If the implementation supports stored defaults and such a default * exists, is accessible, and could be converted to an int with * Integer.parseInt, this int is returned in preference to the * specified default. * * @param key * key whose associated value is to be returned as an int. * @param def * the value to be returned in the event that this preference * node has no value associated with key or the * associated value cannot be interpreted as an int, or the * backing store is inaccessible. * @return the int value represented by the string associated with * key in this preference node, or def if the * associated value does not exist or cannot be interpreted as an * int. * @throws IllegalStateException * if this node (or an ancestor) has been removed with the * {@link #removeNode()} method. * @throws NullPointerException * if key is null. * @see #putInt(String,int) * @see #get(String,String) */ public int getInt(String key, int def); /** * Returns the current value of the long-valued preference with the given * name. Returns the default-default value (0L) if there is no * preference with the given name, or if the current value cannot be treated * as a long. * * @param name * the name of the preference * * @return the long-valued preference */ public long getLong(String name); /** * Returns the long value represented by the string associated with the * specified key in this preference node. The string is converted to a long * as by {@link Long#parseLong(String)}. Returns the specified default if * there is no value associated with the key, the backing store is * inaccessible, or if Long.parseLong(String) would throw a * {@link NumberFormatException} if the associated value were passed. This * method is intended for use in conjunction with {@link #putLong}. * *

* If the implementation supports stored defaults and such a default * exists, is accessible, and could be converted to a long with * Long.parseLong, this long is returned in preference to the * specified default. * * @param key * key whose associated value is to be returned as a long. * @param def * the value to be returned in the event that this preference * node has no value associated with key or the * associated value cannot be interpreted as a long, or the * backing store is inaccessible. * @return the long value represented by the string associated with * key in this preference node, or def if the * associated value does not exist or cannot be interpreted as a * long. * @throws IllegalStateException * if this node (or an ancestor) has been removed with the * {@link #removeNode()} method. * @throws NullPointerException * if key is null. * @see #putLong(String,long) * @see #get(String,String) */ public long getLong(String key, long def); /** * Returns all of the keys that have an associated value in this preference * node. (The returned array will be of size zero if this node has no * preferences.) * *

* If the implementation supports stored defaults and there are any * such defaults at this node that have not been overridden, by explicit * preferences, the defaults are returned in the array in addition to any * explicit preferences. * * @return an array of the keys that have an associated value in this * preference node. * @throws BackingStoreException * if this operation cannot be completed due to a failure in the * backing store, or inability to communicate with it. * @throws IllegalStateException * if this node (or an ancestor) has been removed with the * {@link #removeNode()} method. */ public String[] keys() throws BackingStoreException; /** * Returns this preference node's name, relative to its parent. * * @return this preference node's name, relative to its parent. */ public abstract String name(); /** * Returns the named preference node in the same tree as this node, creating * it and any of its ancestors if they do not already exist. Accepts a * relative or absolute path name. Relative path names (which do not begin * with the slash character ('/')) are interpreted relative to this * preference node. * *

* If the returned node did not exist prior to this call, this node and any * ancestors that were created by this call are not guaranteed to become * permanent until the flush method is called on the returned node * (or one of its ancestors or descendants). * * @param pathName * the path name of the preference node to return. * @return the specified preference node. * @throws IllegalArgumentException * if the path name is invalid (i.e., it contains multiple * consecutive slash characters, or ends with a slash character * and is more than one character long). * @throws NullPointerException * if path name is null. * @throws IllegalStateException * if this node (or an ancestor) has been removed with the * {@link #removeNode()} method. * @see #flush() */ public abstract IPreferences node(String pathName); /** * Returns true if the named preference node exists in the same tree as this * node. Relative path names (which do not begin with the slash character * ('/')) are interpreted relative to this preference node. * *

* If this node (or an ancestor) has already been removed with the * {@link #removeNode()} method, it is legal to invoke this method, * but only with the path name ""; the invocation will return * false. Thus, the idiom p.nodeExists("") may be used to * test whether p has been removed. * * @param pathName * the path name of the node whose existence is to be checked. * @return true if the specified node exists. * @throws BackingStoreException * if this operation cannot be completed due to a failure in the * backing store, or inability to communicate with it. * @throws IllegalArgumentException * if the path name is invalid (i.e., it contains multiple * consecutive slash characters, or ends with a slash character * and is more than one character long). * @throws NullPointerException * if path name is null. s * * @throws IllegalStateException * if this node (or an ancestor) has been removed with the * {@link #removeNode()} method and pathName is not the * empty string (""). */ public abstract boolean nodeExists(String pathName) throws BackingStoreException; /** * Returns the parent of this preference node, or null if this is * the root. * * @return the parent of this preference node. * @throws IllegalStateException * if this node (or an ancestor) has been removed with the * {@link #removeNode()} method. */ public abstract IPreferences parent(); /** * A map of all property mappings in this {@link IPreferences} node. * * @return A map of all property mappings in this {@link IPreferences} node. */ public Map properties(); /** * Sets the current value of the boolean-valued preference with the given * name. * * @param name * the name of the preference * @param value * the new current value of the preference */ public void put(String name, boolean value); /** * Associates a string representing the specified byte array with the * specified key in this preference node. The associated string is the * Base64 encoding of the byte array, as defined in RFC 2045, Section 6.8, with * one minor change: the string will consist solely of characters from the * Base64 Alphabet; it will not contain any newline characters. Note * that the maximum length of the byte array is limited to three quarters of * MAX_VALUE_LENGTH so that the length of the Base64 encoded String * does not exceed MAX_VALUE_LENGTH. This method is intended for * use in conjunction with {@link #getByteArray}. * * @param key * key with which the string form of value is to be associated. * @param value * value whose string form is to be associated with key. * @throws NullPointerException * if key or value is null. * @throws IllegalArgumentException * if key.length() exceeds MAX_KEY_LENGTH or if value.length * exceeds MAX_VALUE_LENGTH*3/4. * @throws IllegalStateException * if this node (or an ancestor) has been removed with the * {@link #removeNode()} method. * @see #getByteArray(String,byte[]) * @see #get(String,String) */ public void put(String key, byte[] value); /** * Sets the current value of the double-valued preference with the given * name. * * @param name * the name of the preference * @param value * the new current value of the preference */ public void put(String name, double value); /** * Sets the current value of the float-valued preference with the given * name. * * @param name * the name of the preference * @param value * the new current value of the preference */ public void put(String name, float value); /** * Sets the current value of the integer-valued preference with the given * name. * * @param name * the name of the preference * @param value * the new current value of the preference */ public void put(String name, int value); /** * Sets the current value of the long-valued preference with the given name. * * @param name * the name of the preference * @param value * the new current value of the preference */ public void put(String name, long value); /** * Sets the current value of the string-valued preference with the given * name. * * @param name * the name of the preference * @param value * the new current value of the preference */ public void put(String name, String value); /** * Set the current value. This is for drop in compatibility to Java platform * preferences. * * @param key * @param value */ public void putBoolean(String key, boolean value); /** * Set the current value. This is for drop in compatibility to Java platform * preferences. * * @param key * @param value */ public void putByteArray(String key, byte[] value); /** * Set the current value. This is for drop in compatibility to Java platform * preferences. * * @param key * @param value */ public void putDouble(String key, double value); /** * Set the current value. This is for drop in compatibility to Java platform * preferences. * * @param key * @param value */ public void putFloat(String key, float value); /** * Set the current value. This is for drop in compatibility to Java platform * preferences. * * @param key * @param value */ public void putInt(String key, int value); /** * Set the current value. This is for drop in compatibility to Java platform * preferences. * * @param key * @param value */ public void putLong(String key, long value); /** * Removes the value associated with the specified key in this preference * node, if any. * *

* If this implementation supports stored defaults, and there is such * a default for the specified preference, the stored default will be * "exposed" by this call, in the sense that it will be returned by a * succeeding call to get. * * @param key * key whose mapping is to be removed from the preference node. * @throws NullPointerException * if key is null. * @throws IllegalStateException * if this node (or an ancestor) has been removed with the * {@link #removeNode()} method. */ public void remove(String key); /** * Removes this preference node and all of its descendants, invalidating any * preferences contained in the removed nodes. Once a node has been removed, * attempting any method other than {@link #name()}, {@link #absolutePath()} * , {@link #flush()} or {@link #node(String) nodeExists("")} on the * corresponding Preferences instance will fail with an * IllegalStateException. (The methods defined on {@link Object} * can still be invoked on a node after it has been removed; they will not * throw IllegalStateException.) * *

* The removal is not guaranteed to be persistent until the flush * method is called on this node (or an ancestor). * *

* If this implementation supports stored defaults, removing a node * exposes any stored defaults at or below this node. Thus, a subsequent * call to nodeExists on this node's path name may return * true, and a subsequent call to node on this path name * may may return a (different) Preferences instance representing a * non-empty collection of preferences and/or children. * * @throws BackingStoreException * if this operation cannot be completed due to a failure in the * backing store, or inability to communicate with it. * @throws IllegalStateException * if this node (or an ancestor) has already been removed with * the {@link #removeNode()} method. * @throws UnsupportedOperationException * if this method is invoked on the root node. * @see #flush() */ public void removeNode() throws BackingStoreException; /** * Create a new IPreferences object whose scopes include all scopes from the * receiver before and including "scopeName". * * @param scopeName * @return a new IPreferences object whose scopes include all scopes from * the receiver before and including "scopeName". */ public IPreferences restrict(String scopeName); /** * Ensures that future reads from this preference node and its descendants * reflect any changes that were committed to the persistent store (from any * VM) prior to the sync invocation. As a side-effect, forces any * changes in the contents of this preference node and its descendants to * the persistent store, as if the flush method had been invoked on * this node. * * @throws BackingStoreException * if this operation cannot be completed due to a failure in the * backing store, or inability to communicate with it. * @throws IllegalStateException * if this node (or an ancestor) has been removed with the * {@link #removeNode()} method. * @see #flush() */ public void sync() throws BackingStoreException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/preferences/IPreferencesFactory.java0000644000175000017500000000420111411055574030055 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.preferences; /** * A factory for {@link IPreferences} root objects. * */ public interface IPreferencesFactory { /** * The standard root to be used by a "main" component. * * @return The standard root to be used by a "main" component. */ public IPreferences getMain(); /** * The global root where all {@link IPreferences} are mounted. Most often * this is the parent of the "main" {@link IPreferences} object. * * @return The global root where all {@link IPreferences} are mounted. */ public IPreferences getRoot(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/preferences/IPreferencesSyncher.java0000644000175000017500000000363411251000056030055 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.preferences; /** * An object that can be synched with its preferences. * */ public interface IPreferencesSyncher { /** * Load the object state from the {@link IPreferences}. */ public void preferencesRestore(); /** * Save the object state to the {@link IPreferences}. */ public void preferencesStore(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/preferences/IScopedPlatformPreferences.java0000644000175000017500000000354511251000056031365 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.preferences; import java.util.prefs.Preferences; /** * A interface that indicates the availability of "scoping" for a standard Java * {@link Preferences} implementation. * */ public interface IScopedPlatformPreferences { Preferences restrict(String scopeName); } libisrt-java-4.8.20100629/src/de/intarsys/tools/preferences/PreferencesChangeEvent.java0000644000175000017500000000437311251000056030521 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.preferences; import de.intarsys.tools.event.Event; import de.intarsys.tools.event.EventType; public class PreferencesChangeEvent extends Event { public static final EventType ID = new EventType( PreferencesChangeEvent.class.getName()); private String key; private String newValue; public PreferencesChangeEvent(Object source) { super(source); } public String getKey() { return key; } public String getNewValue() { return newValue; } @Override public EventType getEventType() { return ID; } public void setKey(String key) { this.key = key; } public void setNewValue(String newValue) { this.newValue = newValue; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/preferences/IPreferencesSupport.java0000644000175000017500000000352111251000056030111 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.preferences; /** * An object that has preferences. */ public interface IPreferencesSupport { /** * The {@link IPreferences} for this object. * * @return The {@link IPreferences} for this object. */ public IPreferences getPreferences(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/preferences/NullPreferencesFactory.java0000644000175000017500000000360711251000056030573 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.preferences; /** * A factory for {@link NullPreferences} */ public class NullPreferencesFactory implements IPreferencesFactory { private static NullPreferences prefs = new NullPreferences(); public IPreferences getMain() { return prefs; } public IPreferences getRoot() { return prefs; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/preferences/PrefValueHolder.java0000644000175000017500000000443611251000056027177 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.preferences; import de.intarsys.tools.valueholder.IValueHolder; /** * An {@link IValueHolder} implementation that is backed up by preferences. * */ public abstract class PrefValueHolder implements IValueHolder { final private IPreferences preferences; final private String key; final private Object defaultValue; public PrefValueHolder(IPreferences preferences, String key, Object defaultValue) { super(); this.preferences = preferences; this.key = key; this.defaultValue = defaultValue; } public Object getDefaultValue() { return defaultValue; } public String getKey() { return key; } public IPreferences getPreferences() { return preferences; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/preferences/BooleanPrefValueHolder.java0000644000175000017500000000414511251000056030474 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.preferences; /** * A {@link PrefValueHolder} implementation for boolean typed values. * */ public class BooleanPrefValueHolder extends PrefValueHolder { public BooleanPrefValueHolder(IPreferences preferences, String key, boolean defaultValue) { super(preferences, key, defaultValue); } public Object get() { return getPreferences().getBoolean(getKey(), (Boolean) getDefaultValue()); } public Object set(Object newValue) { getPreferences().put(getKey(), (Boolean) newValue); return null; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/preferences/PreferencesAdapter.java0000644000175000017500000002635611256665504027743 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.preferences; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.prefs.BackingStoreException; import java.util.prefs.PreferenceChangeListener; import java.util.prefs.Preferences; import de.intarsys.tools.event.Event; import de.intarsys.tools.event.EventDispatcher; import de.intarsys.tools.event.EventType; import de.intarsys.tools.event.INotificationListener; import de.intarsys.tools.event.INotificationSupport; /** * Adapt {@link Preferences} to {@link IPreferences}. */ public class PreferencesAdapter implements IPreferences, INotificationSupport, PreferenceChangeListener { private final Map children = new HashMap(); /** The wrapped java properties */ private final Preferences jPrefs; private final PreferencesAdapter parent; private EventDispatcher dispatcher; private final Object lock = new Object(); private final PreferencesAdapter root; /** * */ public PreferencesAdapter(PreferencesAdapter parent, Preferences jPrefs) { super(); this.parent = parent; this.jPrefs = jPrefs; if (parent != null) { this.root = parent.root; } else { this.root = this; } } public String absolutePath() { return jPrefs.absolutePath(); } synchronized public void addNotificationListener(EventType type, INotificationListener listener) { if (dispatcher == null) { dispatcher = new EventDispatcher(this); jPrefs.addPreferenceChangeListener(this); } dispatcher.addNotificationListener(type, listener); } public IPreferences[] children() { List children = new ArrayList(); String[] names = childrenNames(); for (int i = 0; i < names.length; i++) { children.add(node(names[i])); } return children.toArray(new IPreferences[children.size()]); } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferenceStore#childrenNames() */ public String[] childrenNames() { try { return jPrefs.childrenNames(); } catch (BackingStoreException e) { return new String[0]; } } public void clear() throws BackingStoreException { jPrefs.clear(); } protected PreferencesAdapter createPreferencesNode(String pathName) { return new PreferencesAdapter(this, jPrefs.node(pathName)); } public void flush() { try { jPrefs.flush(); } catch (BackingStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* * (non-Javadoc) * * @see org.eclipse.jface.preference.IPreferenceStore#getString(java.lang.String) */ public String get(String name) { return jPrefs.get(name, null); } public String get(String key, String def) { return jPrefs.get(key, def); } /* * (non-Javadoc) * * @see org.eclipse.jface.preference.IPreferenceStore#getBoolean(java.lang.String) */ public boolean getBoolean(String name) { return jPrefs.getBoolean(name, false); } public boolean getBoolean(String key, boolean def) { return jPrefs.getBoolean(key, def); } public byte[] getByteArray(String key, byte[] def) { return jPrefs.getByteArray(key, def); } /* * (non-Javadoc) * * @see org.eclipse.jface.preference.IPreferenceStore#getDouble(java.lang.String) */ public double getDouble(String name) { return jPrefs.getDouble(name, 0); } public double getDouble(String key, double def) { return jPrefs.getDouble(key, def); } /* * (non-Javadoc) * * @see org.eclipse.jface.preference.IPreferenceStore#getFloat(java.lang.String) */ public float getFloat(String name) { return jPrefs.getFloat(name, 0); } public float getFloat(String key, float def) { return jPrefs.getFloat(key, def); } /* * (non-Javadoc) * * @see org.eclipse.jface.preference.IPreferenceStore#getInt(java.lang.String) */ public int getInt(String name) { return jPrefs.getInt(name, 0); } public int getInt(String key, int def) { return jPrefs.getInt(key, def); } /* * (non-Javadoc) * * @see org.eclipse.jface.preference.IPreferenceStore#getLong(java.lang.String) */ public long getLong(String name) { return jPrefs.getLong(name, 0); } public long getLong(String key, long def) { return jPrefs.getLong(key, def); } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferenceStore#keys() */ public String[] keys() { try { return jPrefs.keys(); } catch (BackingStoreException e) { return new String[0]; } } public String name() { return jPrefs.name(); } synchronized public IPreferences node(String pathName) { synchronized (lock) { if (pathName.equals("")) return this; if (pathName.equals("/")) return root; if (pathName.charAt(0) != '/') return node(new StringTokenizer(pathName, "/", true)); } return root.node(new StringTokenizer(pathName.substring(1), "/", true)); } protected IPreferences node(StringTokenizer path) { String token = path.nextToken(); if (token.equals("/")) // Check for consecutive slashes throw new IllegalArgumentException("Consecutive slashes in path"); synchronized (lock) { PreferencesAdapter child = children.get(token); if (child == null) { child = createPreferencesNode(token); children.put(token, child); } if (!path.hasMoreTokens()) return child; path.nextToken(); // Consume slash if (!path.hasMoreTokens()) throw new IllegalArgumentException("Path ends with slash"); return child.node(path); } } public boolean nodeExists(String pathName) throws BackingStoreException { return jPrefs.nodeExists(pathName); } public IPreferences parent() { return parent; } public void preferenceChange(java.util.prefs.PreferenceChangeEvent evt) { triggerChange(evt); } public Map properties() { Map properties = new HashMap(); String[] keys = keys(); for (int i = 0; i < keys.length; i++) { properties.put(keys[i], get(keys[i])); } return properties; } /* * (non-Javadoc) * * @see org.eclipse.jface.preference.IPreferenceStore#put(java.lang.String, * boolean) */ public void put(String name, boolean value) { jPrefs.putBoolean(name, value); } public void put(String name, byte[] value) { if (value == null) { jPrefs.remove(name); } else { jPrefs.putByteArray(name, value); } } /* * (non-Javadoc) * * @see org.eclipse.jface.preference.IPreferenceStore#put(java.lang.String, * double) */ public void put(String name, double value) { jPrefs.putDouble(name, value); } /* * (non-Javadoc) * * @see org.eclipse.jface.preference.IPreferenceStore#put(java.lang.String, * float) */ public void put(String name, float value) { jPrefs.putFloat(name, value); } /* * (non-Javadoc) * * @see org.eclipse.jface.preference.IPreferenceStore#put(java.lang.String, * int) */ public void put(String name, int value) { jPrefs.putInt(name, value); } /* * (non-Javadoc) * * @see org.eclipse.jface.preference.IPreferenceStore#put(java.lang.String, * long) */ public void put(String name, long value) { jPrefs.putLong(name, value); } /* * (non-Javadoc) * * @see org.eclipse.jface.preference.IPreferenceStore#put(java.lang.String, * java.lang.String) */ public void put(String name, String value) { if (value == null) { jPrefs.remove(name); } else { jPrefs.put(name, value); } } public void putBoolean(String key, boolean value) { jPrefs.putBoolean(key, value); } public void putByteArray(String name, byte[] value) { if (value == null) { jPrefs.remove(name); } else { jPrefs.putByteArray(name, value); } } public void putDouble(String key, double value) { jPrefs.putDouble(key, value); } public void putFloat(String key, float value) { jPrefs.putFloat(key, value); } public void putInt(String key, int value) { jPrefs.putInt(key, value); } public void putLong(String key, long value) { jPrefs.putLong(key, value); } /* * (non-Javadoc) * * @see de.intarsys.tools.preferences.IPreferenceStore#remove(java.lang.String) */ public void remove(String name) { jPrefs.remove(name); } public void removeNode() throws BackingStoreException { if (parent == null) { throw new UnsupportedOperationException("Can't remove the root!"); } synchronized (parent.lock) { jPrefs.removeNode(); parent.children.remove(jPrefs.name()); } } synchronized public void removeNotificationListener(EventType type, INotificationListener listener) { if (dispatcher == null) { return; } dispatcher.removeNotificationListener(type, listener); if (dispatcher.isEmpty()) { jPrefs.removePreferenceChangeListener(this); } } public IPreferences restrict(String scopeName) { if (jPrefs instanceof IScopedPlatformPreferences) { return new PreferencesAdapter(null, ((IScopedPlatformPreferences) jPrefs).restrict(scopeName)); } else { return this; } } public void sync() throws BackingStoreException { jPrefs.sync(); } protected void triggerChange(java.util.prefs.PreferenceChangeEvent jEvent) { PreferencesChangeEvent event = new PreferencesChangeEvent(this); event.setKey(jEvent.getKey()); event.setNewValue(jEvent.getNewValue()); triggerEvent(event); } protected void triggerEvent(Event event) { if (dispatcher == null) { return; } dispatcher.triggerEvent(event); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/concurrent/0000755000175000017500000000000011412336332023167 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/concurrent/TaskStep.java0000644000175000017500000000246711217731572025611 0ustar twernertwerner/* * intarsys consulting GmbH * all rights reserved * */ package de.intarsys.tools.concurrent; import de.intarsys.tools.event.Event; import de.intarsys.tools.event.INotificationListener; /** * experimental */ public class TaskStep extends AbstractFutureTask { final private TaskSequence sequence; final private Runnable task; final private int percent; private INotificationListener listenSubTask = new INotificationListener() { public void handleEvent(Event event) { onSubTaskChanged(event.getSource()); } }; private int start; public TaskStep(TaskSequence sequence, Runnable task, int percent) { super(); this.sequence = sequence; this.task = task; this.percent = percent; // task.addNotificationListener(AttributeChangedEvent.ID, // listenSubTask); } @Override protected R compute() throws Exception { // start = sequence.getWorkCurrent(); task.run(); return null; // return task.get(); } public int getPercent() { return percent; } public TaskSequence getSequence() { return sequence; } protected void onSubTaskChanged(Object task) { // int taskPart = (int) (task.getProgress() * ((float) getPercent() / // 100)); // sequence.setWorkCurrent(task.getWorkMessage(), start + taskPart); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/concurrent/AbstractFutureTask.java0000644000175000017500000002031311411055572027615 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.concurrent; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.logging.Level; import java.util.logging.Logger; /** * This is an alternate implementation for {@link FutureTask}, which is in some * cases not flexible enough. * * @param */ abstract public class AbstractFutureTask implements Runnable, Future { protected final static Logger Log = PACKAGE.Log; static private int COUNTER = 0; final private Object lockTask = new Object(); private Throwable exception; private R result; private boolean cancelled = false; private boolean computed = false; final private int id = COUNTER++; private boolean active = false; protected AbstractFutureTask() { super(); } protected Throwable basicGetException() { synchronized (lockTask) { return exception; } } protected R basicGetResult() { return result; } public boolean cancel(boolean interrupt) { synchronized (lockTask) { if (cancelled) { if (Log.isLoggable(Level.FINEST)) { Log.finest("" + this + " can't cancel, already canceled"); //$NON-NLS-1$ } return false; } if (computed) { if (Log.isLoggable(Level.FINEST)) { Log.finest("" + this + " can't cancel, already computed"); //$NON-NLS-1$ } return false; } if (Log.isLoggable(Level.FINEST)) { Log .finest("" + this + " cancel " + (active ? "active" : "inactive") + " task"); //$NON-NLS-1$ } cancelled = true; active = false; lockTask.notifyAll(); return true; } } protected abstract R compute() throws Exception; protected void computeAsync() { new Thread(this, "Task computation " + id).start(); } public R get() throws InterruptedException, ExecutionException { try { return get(0, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { throw new InterruptedException(); } } public R get(final long pMillisecTimeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { long millisecTimeout = pMillisecTimeout; long lastTime = System.currentTimeMillis(); synchronized (lockTask) { while (true) { if (cancelled) { // TODO 2 throw an exception instead of null? return null; } if (computed) { if (exception != null) { throw new ExecutionException(exception); } // may be null! return result; } if (pMillisecTimeout >= 0) { lockTask.wait(millisecTimeout); if (pMillisecTimeout != 0) { long now = System.currentTimeMillis(); millisecTimeout -= now - lastTime; lastTime = now; if (millisecTimeout <= 0) { throw new TimeoutException(); } } } else { // support a unblocked "get current value" return null; } } } } public Throwable getException() { synchronized (lockTask) { return exception; } } final protected void handleException() { try { if (cancelled) { if (Log.isLoggable(Level.FINEST)) { Log.finest("" + this + " exception after cancel"); //$NON-NLS-1$ } undo(); taskCancelled(); } else { if (Log.isLoggable(Level.FINEST)) { Log.finest("" + this + " exception, propagate"); //$NON-NLS-1$ } taskFailed(); } } catch (Exception e) { Log.log(Level.SEVERE, "" + this + " exception in exception handling", e); //$NON-NLS-1$ } } final protected void handleFinally() { try { if (Log.isLoggable(Level.FINEST)) { Log.finest("" + this + " finally, propagate"); //$NON-NLS-1$ } taskFinally(); } catch (Exception e) { Log.log(Level.SEVERE, "" + this + " exception in finally handling", e); //$NON-NLS-1$ } } final protected void handleResult() { try { if (cancelled) { if (Log.isLoggable(Level.FINEST)) { Log.finest("" + this + " computed after cancel, undo"); //$NON-NLS-1$ } undo(); taskCancelled(); } else { if (Log.isLoggable(Level.FINEST)) { Log.finest("" + this + " computed, propagate"); //$NON-NLS-1$ } taskFinished(); } } catch (Exception e) { Log.log(Level.SEVERE, "" + this + " exception in result handling", e); //$NON-NLS-1$ } } public boolean isActive() { synchronized (lockTask) { return active; } } public boolean isCancelled() { synchronized (lockTask) { return cancelled; } } public boolean isDone() { synchronized (lockTask) { return computed || cancelled; } } public boolean isFailed() { synchronized (lockTask) { return exception != null; } } public void reset() { synchronized (lockTask) { active = false; computed = false; exception = null; result = null; } } final public void run() { synchronized (lockTask) { if (active || cancelled || computed) { if (Log.isLoggable(Level.FINEST)) { Log .finest("" + this + " will not run" + (cancelled ? " (canceled)" : "")); //$NON-NLS-1$ } return; } active = true; } taskStarted(); try { setResult(compute()); } catch (Throwable e) { setException(e); } finally { handleFinally(); } } public void runAsync() { synchronized (this) { if (active || cancelled || computed) { if (Log.isLoggable(Level.FINEST)) { Log .finest("" + this + " will not run" + (cancelled ? " (canceled)" : "")); //$NON-NLS-1$ } return; } active = true; } computeAsync(); } protected void setException(Throwable e) { synchronized (lockTask) { computed = true; active = false; exception = e; lockTask.notifyAll(); } if (Log.isLoggable(Level.FINEST)) { Log.finest("" + this + " computation failed"); //$NON-NLS-1$ } handleException(); } protected void setResult(R object) { synchronized (lockTask) { computed = true; active = false; result = object; lockTask.notifyAll(); } if (Log.isLoggable(Level.FINEST)) { Log.finest("" + this + " computation ready"); //$NON-NLS-1$ } handleResult(); } protected void taskCancelled() { // redefine } protected void taskFailed() { // redefine } protected void taskFinally() { // redefine } protected void taskFinished() { // redefine } protected void taskStarted() { // redefine } @Override public String toString() { return getClass().getName() + " - " + id; } protected void undo() { // redefine } } libisrt-java-4.8.20100629/src/de/intarsys/tools/concurrent/CallbackFutureTask.java0000644000175000017500000000422511217731572027557 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.concurrent; import java.util.concurrent.ExecutionException; abstract public class CallbackFutureTask extends AbstractFutureTask { final private ITaskListener callback; protected CallbackFutureTask(ITaskListener callback) { super(); this.callback = callback; } @Override protected void taskFailed() { if (callback != null) { callback.taskFailed(this, new ExecutionException( basicGetException())); } } @Override protected void taskFinished() { if (callback != null) { callback.taskFinished(this, basicGetResult()); } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/concurrent/PACKAGE.java0000644000175000017500000000373111207517540025075 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.concurrent; import java.util.logging.Logger; import de.intarsys.tools.logging.LogTools; import de.intarsys.tools.message.MessageBundle; import de.intarsys.tools.message.MessageBundleTools; public class PACKAGE { public final static Logger Log = LogTools.getLogger(PACKAGE.class); public final static MessageBundle Messages = MessageBundleTools .getMessageBundle(PACKAGE.class); } libisrt-java-4.8.20100629/src/de/intarsys/tools/concurrent/ITaskListener.java0000644000175000017500000000360611207517540026564 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.concurrent; import java.util.concurrent.ExecutionException; public interface ITaskListener { public void taskCancelled(Object task); public void taskFailed(Object task, ExecutionException exception); public void taskFinished(Object task, Object result); public void taskStarted(Object task); } libisrt-java-4.8.20100629/src/de/intarsys/tools/concurrent/ITaskListenerSupport.java0000644000175000017500000000337011207517540030157 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.concurrent; public interface ITaskListenerSupport { public void addTaskListener(ITaskListener listener); public void removeTaskListener(ITaskListener listener); } libisrt-java-4.8.20100629/src/de/intarsys/tools/concurrent/TaskCallbackDispatcher.java0000644000175000017500000001072211207517540030366 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.concurrent; import java.util.concurrent.ExecutionException; /** * Helper object for implementing {@link ITaskListenerSupport}. */ public class TaskCallbackDispatcher implements ITaskListenerSupport, ITaskListener { private final Object owner; private ITaskListener[] listeners = new ITaskListener[2]; public TaskCallbackDispatcher(Object pOwner) { super(); owner = pOwner; } public void addTaskListener(ITaskListener listener) { if (listener == null) { throw new NullPointerException("listener may not be null"); } int length = listeners.length; int i = 0; while (i < length) { if (listeners[i] == null) { break; } i++; } if (i >= length) { ITaskListener[] templisteners = new ITaskListener[length + 4]; System.arraycopy(listeners, 0, templisteners, 0, length); listeners = templisteners; } listeners[i] = listener; } synchronized public void attach(ITaskListenerSupport support) { int length = listeners.length; for (int i = 0; i < length; i++) { support.addTaskListener(listeners[i]); } } public synchronized void clear() { listeners = new ITaskListener[4]; } synchronized public void detach(ITaskListenerSupport support) { int length = listeners.length; for (int i = 0; i < length; i++) { support.removeTaskListener(listeners[i]); } } public Object getOwner() { return owner; } public synchronized boolean isEmpty() { for (int i = 0; i < listeners.length; i++) { if (listeners[i] != null) { return false; } } return true; } public void removeTaskListener(ITaskListener listener) { int length = listeners.length; int i = 0; while (i < length) { if (listeners[i] == listener) { listeners[i] = null; break; } i++; } } public void taskCancelled(Object task) { int length = listeners.length; for (int i = 0; i < length; i++) { ITaskListener templistener = listeners[i]; if (templistener == null) { continue; } templistener.taskCancelled(task); } } public void taskFailed(Object task, ExecutionException exception) { int length = listeners.length; for (int i = 0; i < length; i++) { ITaskListener templistener = listeners[i]; if (templistener == null) { continue; } templistener.taskFailed(task, exception); } } public void taskFinished(Object task, Object result) { int length = listeners.length; for (int i = 0; i < length; i++) { ITaskListener templistener = listeners[i]; if (templistener == null) { continue; } templistener.taskFinished(task, result); } } public void taskStarted(Object task) { int length = listeners.length; for (int i = 0; i < length; i++) { ITaskListener templistener = listeners[i]; if (templistener == null) { continue; } templistener.taskStarted(task); } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/concurrent/GenericFutureTask.java0000644000175000017500000000533711207517540027440 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.concurrent; import java.util.concurrent.Callable; public class GenericFutureTask extends CallbackFutureTask { final private Callable computeFunctor; final private Runnable undoFunctor; public GenericFutureTask(Callable computeFunctor) { super(null); this.computeFunctor = computeFunctor; this.undoFunctor = null; } public GenericFutureTask(Callable computeFunctor, ITaskListener callback) { super(callback); this.computeFunctor = computeFunctor; this.undoFunctor = null; } public GenericFutureTask(Callable computeFunctor, Runnable undoFunctor) { super(null); this.computeFunctor = computeFunctor; this.undoFunctor = undoFunctor; } public GenericFutureTask(Callable computeFunctor, Runnable undoFunctor, ITaskListener callback) { super(callback); this.computeFunctor = computeFunctor; this.undoFunctor = undoFunctor; } @Override protected Object compute() throws Exception { if (computeFunctor != null) { return computeFunctor.call(); } return null; } @Override protected void undo() { if (undoFunctor != null) { undoFunctor.run(); } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/concurrent/TaskSequence.java0000644000175000017500000000244511217731572026442 0ustar twernertwerner/* * intarsys consulting GmbH * all rights reserved * */ package de.intarsys.tools.concurrent; import java.util.ArrayList; import java.util.List; /** * experimental */ public class TaskSequence extends AbstractFutureTask { private List tasks = new ArrayList(); private String labelPrefix; private Runnable currentTask = null; public TaskSequence(String labelPrefix) { super(); // setWorkTotal(0); this.labelPrefix = labelPrefix; } public void addTask(Runnable task, int percent) { tasks.add(new TaskStep(this, task, percent)); // setWorkTotal(getWorkTotal() + percent); } @Override protected R compute() throws Exception { try { R result = null; for (Runnable task : tasks) { synchronized (this) { currentTask = task; } task.run(); if (isCancelled()) { return null; } } return result; } finally { synchronized (this) { currentTask = null; } } } protected String getLabelPrefix() { return labelPrefix; } protected String getLabelSuffix() { Runnable tempTask; synchronized (this) { tempTask = currentTask; } return ""; } public void setLabelPrefix(String labelPrefix) { this.labelPrefix = labelPrefix; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/concurrent/SynchronousExecutorService.java0000644000175000017500000000617611226561362031444 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.concurrent; import java.util.Collections; import java.util.List; import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.TimeUnit; /** * A simple ExecutorService running all commands synchronously. */ public class SynchronousExecutorService extends AbstractExecutorService { volatile private boolean shutdown = false; volatile private boolean terminated = false; /* * (non-Javadoc) * * @see java.util.concurrent.ExecutorService#awaitTermination(long, * java.util.concurrent.TimeUnit) */ public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return true; } /* * (non-Javadoc) * * @see java.util.concurrent.Executor#execute(java.lang.Runnable) */ public void execute(Runnable command) { if (shutdown || terminated) { return; } command.run(); } /* * (non-Javadoc) * * @see java.util.concurrent.ExecutorService#isShutdown() */ public boolean isShutdown() { return shutdown; } /* * (non-Javadoc) * * @see java.util.concurrent.ExecutorService#isTerminated() */ public boolean isTerminated() { return terminated; } /* * (non-Javadoc) * * @see java.util.concurrent.ExecutorService#shutdown() */ public void shutdown() { shutdown = true; terminated = true; } /* * (non-Javadoc) * * @see java.util.concurrent.ExecutorService#shutdownNow() */ public List shutdownNow() { shutdown = true; terminated = true; return Collections.EMPTY_LIST; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/concurrent/SynchronousQueuedExecutorService.java0000644000175000017500000000722011325330434032576 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.concurrent; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.TimeUnit; /** * A simple ExecutorService running all commands synchronously. */ public class SynchronousQueuedExecutorService extends AbstractExecutorService { volatile private boolean shutdown = false; volatile private boolean terminated = false; private LinkedList queue = new LinkedList(); private Object lock = new Object(); /* * (non-Javadoc) * * @see java.util.concurrent.ExecutorService#awaitTermination(long, * java.util.concurrent.TimeUnit) */ public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return true; } public void drain() { synchronized (lock) { for (Iterator it = queue.iterator(); it.hasNext();) { Runnable command = (Runnable) it.next(); command.run(); } } } /* * (non-Javadoc) * * @see java.util.concurrent.Executor#execute(java.lang.Runnable) */ public void execute(Runnable command) { synchronized (lock) { if (shutdown || terminated) { return; } queue.add(command); } } /* * (non-Javadoc) * * @see java.util.concurrent.ExecutorService#isShutdown() */ public boolean isShutdown() { synchronized (lock) { return shutdown; } } /* * (non-Javadoc) * * @see java.util.concurrent.ExecutorService#isTerminated() */ public boolean isTerminated() { synchronized (lock) { return terminated; } } /* * (non-Javadoc) * * @see java.util.concurrent.ExecutorService#shutdown() */ public void shutdown() { synchronized (lock) { shutdown = true; terminated = true; } } /* * (non-Javadoc) * * @see java.util.concurrent.ExecutorService#shutdownNow() */ public List shutdownNow() { synchronized (lock) { shutdown = true; terminated = true; return new ArrayList(queue); } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/factory/0000755000175000017500000000000011412336332022454 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/factory/PACKAGE.java0000644000175000017500000000065611327620076024367 0ustar twernertwernerpackage de.intarsys.tools.factory; import java.util.logging.Logger; import de.intarsys.tools.logging.LogTools; import de.intarsys.tools.message.MessageBundle; import de.intarsys.tools.message.MessageBundleTools; public class PACKAGE { public final static MessageBundle Messages = MessageBundleTools .getMessageBundle(PACKAGE.class); public final static Logger Log = LogTools.getLogger(PACKAGE.class); } libisrt-java-4.8.20100629/src/de/intarsys/tools/factory/FactoryTools.java0000644000175000017500000000625711412330244025755 0ustar twernertwernerpackage de.intarsys.tools.factory; import java.util.logging.Level; import java.util.logging.Logger; import de.intarsys.tools.reflect.ObjectTools; public class FactoryTools { private static final Logger Log = PACKAGE.Log; /** * Lookup the {@link IFactory} instance for a factory class. This tool * method assumes the {@link IFactory} instance is registered with its class * name. *

* If no such {@link IFactory} is registered, this method tries to create * and register a new one. *

* If no {@link IFactory} is registered and can't be created, null is * returned. * * @param clazz * @return the {@link IFactory} instance for a factory class */ static public IFactory lookupFactory(Class clazz) { String id = clazz.getName(); IFactory factory = Outlet.get().lookupFactory(id); if (factory == null) { try { factory = ObjectTools.createObject(clazz, IFactory.class); Outlet.get().registerFactory(factory); Log.log(Level.INFO, "created default factory '" + id + "'"); } catch (Exception e) { // ... } } return factory; } /** * Lookup the {@link IFactory} instance for an id. *

* If no such {@link IFactory} is registered, this method tries to create * and register a new one by interpreting the id as a class name. *

* If no {@link IFactory} is registered and can't be created, null is * returned. * * * @param id * @param classLoader * @return the {@link IFactory} instance for an id. */ static public IFactory lookupFactory(String id, ClassLoader classLoader) { IFactory factory = Outlet.get().lookupFactory(id); if (factory == null) { try { factory = ObjectTools.createObject(id, IFactory.class, classLoader); Outlet.get().registerFactory(factory); Log.log(Level.INFO, "created default factory '" + id + "'"); } catch (Exception e) { // ... } } return factory; } /** * Lookup the {@link IFactory} instance for target object class. This method * tries to derive the factory by searching the {@link IFactory} with * appropriate types. If not available it tries to lookup an * {@link IFactory} by appending "Factory" to the clazz name and using it as * an id. *

* If no such {@link IFactory} is registered, this method tries to create * and register a new one by interpreting the id as a class name. *

* If no {@link IFactory} is registered and can't be created, null is * returned. * * * @param clazz * @return the {@link IFactory} instance for target object class */ static public IFactory lookupFactoryFor(Class clazz) { IFactory[] factories = Outlet.get().lookupFactories(clazz); if (factories.length > 0) { return factories[0]; } String id = clazz.getName() + "Factory"; IFactory factory = Outlet.get().lookupFactory(id); if (factory == null) { try { factory = ObjectTools.createObject(id, IFactory.class, clazz .getClassLoader()); Outlet.get().registerFactory(factory); Log.log(Level.INFO, "created default factory '" + id + "'"); } catch (Exception e) { // ... } } return factory; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/factory/IOutlet.java0000644000175000017500000000046611325065022024710 0ustar twernertwernerpackage de.intarsys.tools.factory; public interface IOutlet { public IFactory[] getFactories(); public IFactory[] lookupFactories(Class type); public IFactory lookupFactory(String id); public void registerFactory(IFactory factory); public void unregisterFactory(IFactory factory); } libisrt-java-4.8.20100629/src/de/intarsys/tools/factory/StandardOutlet.java0000644000175000017500000000200211325065022026244 0ustar twernertwernerpackage de.intarsys.tools.factory; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class StandardOutlet implements IOutlet { private Map factories = new HashMap(); public IFactory[] getFactories() { return factories.values().toArray(new IFactory[factories.size()]); } public IFactory[] lookupFactories(Class type) { Set result = new HashSet(); for (IFactory factory : factories.values()) { Class resultType = factory.getResultType(); if (resultType != null && type.isAssignableFrom(resultType)) { result.add(factory); } } return result.toArray(new IFactory[result.size()]); } public IFactory lookupFactory(String id) { return factories.get(id); } public void registerFactory(IFactory factory) { factories.put(factory.getId(), factory); } public void unregisterFactory(IFactory factory) { factories.remove(factory.getId()); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/factory/Outlet.java0000644000175000017500000000036711325065022024577 0ustar twernertwernerpackage de.intarsys.tools.factory; public class Outlet { private static IOutlet ACTIVE = new StandardOutlet(); static public IOutlet get() { return ACTIVE; } static public void set(IOutlet active) { ACTIVE = active; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/factory/IFactorySupport.java0000644000175000017500000000016111325065022026430 0ustar twernertwernerpackage de.intarsys.tools.factory; public interface IFactorySupport { public IFactory getFactory(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/factory/IFactory.java0000644000175000017500000000033711325065022025040 0ustar twernertwernerpackage de.intarsys.tools.factory; import de.intarsys.tools.functor.IArgs; public interface IFactory { public T createInstance(IArgs args); public String getId(); public Class getResultType(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/oid/0000755000175000017500000000000011412336332021560 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/oid/StringOIDGenerator.java0000644000175000017500000000465410751651502026111 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.oid; /** * Create an OID unique to the running VM. Multiple {@link StringOIDGenerator} * instances create different OIDs. * */ public class StringOIDGenerator extends CommonOIDGenerator { private static int COUNTER = 0; final private int myId = COUNTER++; private long lastMillis = 0; final private String prefix; final private String suffix; /** * */ public StringOIDGenerator(String prefix, String suffix) { super(); this.prefix = prefix; this.suffix = suffix; } /* * (non-Javadoc) * * @see de.intarsys.tools.oid.OIDGenerator#createOID() */ public Object createOID() { long millis = System.currentTimeMillis(); synchronized (this) { while (millis <= lastMillis) { millis++; } lastMillis = millis; } return prefix + "_" + myId + "_" + millis + "_" + suffix; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/oid/IOIDGenerator.java0000644000175000017500000000322210751651502025021 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.oid; public interface IOIDGenerator { public Object createOID(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/oid/CommonOIDGenerator.java0000644000175000017500000000335210751651502026065 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.oid; /** * */ public abstract class CommonOIDGenerator implements IOIDGenerator { /** * */ protected CommonOIDGenerator() { super(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/math/0000755000175000017500000000000011412336332021736 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/math/BigIntegerTools.java0000644000175000017500000000064211037642204025644 0ustar twernertwernerpackage de.intarsys.tools.math; import java.math.BigInteger; public class BigIntegerTools { public static BigInteger getPositiveBigInt(final byte[] data) { // byte[] temp = data; // if (data[0] < 0) { // temp = new byte[data.length + 1]; // System.arraycopy(data, 0, temp, 1, data.length); // } return new BigInteger(1, data); } private BigIntegerTools() { // tool class } } libisrt-java-4.8.20100629/src/de/intarsys/tools/math/MathTools.java0000644000175000017500000000365311025664516024532 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.math; /** * Tool class for math related functions */ public class MathTools { public static boolean equalsNearly(double a, double b, double range) { return Math.abs(a - b) <= range; } public static boolean equalsNearly(float a, float b, float range) { return Math.abs(a - b) <= range; } private MathTools() { super(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locking/0000755000175000017500000000000011412336332022433 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/locking/NullLock.java0000644000175000017500000000347511222634276025041 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locking; public class NullLock extends AbstractLock { public NullLock(Object object) { super(object); } public boolean acquire(Object owner, ILockLevel level) { return true; } public void release(Object owner) { } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locking/LockStrategy.java0000644000175000017500000000347711222634276025733 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locking; public class LockStrategy { private static ILockStrategy ACTIVE = new NullLockStrategy(); static public ILockStrategy get() { return ACTIVE; } static public void set(ILockStrategy active) { ACTIVE = active; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locking/AbstractLockStrategy.java0000644000175000017500000000342511222634276027410 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locking; /** * Abstract {@link ILockStrategy} implementation. * */ abstract public class AbstractLockStrategy implements ILockStrategy { protected AbstractLockStrategy() { super(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locking/ILock.java0000644000175000017500000000334311222634276024311 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locking; /** * */ public interface ILock { public boolean acquire(Object owner, ILockLevel level); public void release(Object owner); } libisrt-java-4.8.20100629/src/de/intarsys/tools/locking/ILockSupport.java0000644000175000017500000000322411222634276025704 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locking; public interface ILockSupport { public ILock getLock(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/locking/AbstractLock.java0000644000175000017500000000462411222634276025667 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locking; /** * Abstract {@link ILock} implementation. * */ abstract public class AbstractLock implements ILock { /** * The object that is guarded by this lock. */ final private Object object; public AbstractLock(Object object) { super(); this.object = object; } /** * The object that is guarded by this lock. * * @return The object that is locked. */ protected Object getObject() { return object; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); //$NON-NLS-1$ toStringFlags(sb); sb.append("]-"); //$NON-NLS-1$ sb.append(getObject()); return sb.toString(); } /** * provide some detail information for this * * @param sb */ protected void toStringFlags(StringBuilder sb) { // do nothing } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locking/NullLockStrategy.java0000644000175000017500000000353211222634276026556 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locking; public class NullLockStrategy extends AbstractLockStrategy { public NullLockStrategy() { super(); } public boolean lock(Object object, Object owner, ILockLevel level) { return true; } public void unlock(Object object, Object owner) { } } libisrt-java-4.8.20100629/src/de/intarsys/tools/locking/ILockLevel.java0000644000175000017500000000340111222634276025274 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locking; public interface ILockLevel { public static final ILockLevel EXCLUSIVE = new ILockLevel() { }; public static final ILockLevel SHARED = new ILockLevel() { }; } libisrt-java-4.8.20100629/src/de/intarsys/tools/locking/ILockStrategy.java0000644000175000017500000000336611222634276026041 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.locking; public interface ILockStrategy { public boolean lock(Object object, Object owner, ILockLevel level); public void unlock(Object object, Object owner); } libisrt-java-4.8.20100629/src/de/intarsys/tools/adapter/0000755000175000017500000000000011412336332022425 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/adapter/StandardAdapterOutlet.java0000644000175000017500000000466711213475700027545 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.adapter; import java.util.ArrayList; import java.util.List; /** * The standard implementation for {@link IAdapterOutlet}. */ public class StandardAdapterOutlet implements IAdapterOutlet { private List factories = new ArrayList(); public T getAdapter(Object object, Class clazz) { T result = null; for (IAdapterFactory factory : factories) { if (factory.getBaseType().isInstance(object)) { result = factory.getAdapter(object, clazz); if (result != null) { break; } } } return result; } public Class getBaseType() { return Object.class; } synchronized public void registerAdapterFactory(IAdapterFactory factory) { factories.add(factory); } synchronized public void unregisterAdapterFactory(IAdapterFactory factory) { factories.remove(factory); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/adapter/IAdapterOutlet.java0000644000175000017500000000412311412330174026154 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.adapter; /** * The outlet, supporting multiple {@link IAdapterFactory} instances. */ public interface IAdapterOutlet extends IAdapterFactory { /** * Register a new {@link IAdapterFactory} * * @param factory */ public void registerAdapterFactory(IAdapterFactory factory); /** * Unregister an {@link IAdapterFactory}. Nothing happens if * factory was not registered before. * * @param factory */ public void unregisterAdapterFactory(IAdapterFactory factory); } libisrt-java-4.8.20100629/src/de/intarsys/tools/adapter/AdapterTools.java0000644000175000017500000000456111412330160025670 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.adapter; /** * A tool class for handling adapter objects. */ public class AdapterTools { /** * An object of type clazz that represents object. *

* This method should return null if adaption is not possible. * * @param * @param object * @param clazz * @return An object of type clazz that represents * object. */ static public T getAdapter(Object object, Class clazz) { T result = null; if (clazz.isInstance(object)) { result = (T) object; } if (object instanceof IAdapterSupport) { result = ((IAdapterSupport) object).getAdapter(clazz); } if (result == null) { result = AdapterOutlet.get().getAdapter(object, clazz); } return result; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/adapter/IAdapterSupport.java0000644000175000017500000000522311412330200026344 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.adapter; /** * An object that is able to be adapted to another type. *

* This can be interpreted as a "dynamic" cast to a type that is not statically * declared for the receiver. This pattern allows more freedom in layered / * component oriented architectures, as the receiver object is not forced to * implement a certain interface at compile time. *

* A generic implementation of this method could use the {@link IAdapterOutlet} * singleton to delegate adapter creation to a registered * {@link IAdapterFactory}. * *

 * public <T> T getAdapter(Class<T> clazz) {
 * 	return AdapterOutlet.get().getAdapter(this, clazz);
 * }
 * 
*/ public interface IAdapterSupport { /** * Return an object of type clazz that represents the receiver. *

* This method should return null if adaption is not possible. * * @param * @param clazz * @return Return an object of type clazz that represents the * receiver. */ public T getAdapter(Class clazz); } libisrt-java-4.8.20100629/src/de/intarsys/tools/adapter/IAdapterFactory.java0000644000175000017500000000454011412330166026313 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.adapter; /** * A factory instance that can create an adapter object of type * clazz on behalf of the object object. */ public interface IAdapterFactory { /** * Return an object of type clazz that represents * object. *

* This method should return null if adaption is not possible. * * @param * @param object * @param clazz * @return Return an object of type clazz that represents * object. */ public T getAdapter(Object object, Class clazz); /** * The type of objects that can be adapted by this factory. * * @return The type of objects that can be adapted by this factory. */ public Class getBaseType(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/adapter/AdapterOutlet.java0000644000175000017500000000417011412330154026043 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.adapter; /** * A VM wide singleton for the {@link IAdapterOutlet}. */ public class AdapterOutlet { private static IAdapterOutlet ACTIVE = new StandardAdapterOutlet(); /** * A VM wide singleton for the {@link IAdapterOutlet}. * * @return A VM wide singleton for the {@link IAdapterOutlet}. */ static public IAdapterOutlet get() { return ACTIVE; } /** * Set the VM wide singleton for the {@link IAdapterOutlet}. * * @param active */ static public void set(IAdapterOutlet active) { ACTIVE = active; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/component/0000755000175000017500000000000011412336332023007 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/component/IMetaInfoSupport.java0000644000175000017500000000404511025664520027070 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.component; /** * This interface declares the components ability to provide meta information. * */ public interface IMetaInfoSupport extends IInstantiable { public static final String META_ID = "id"; //$NON-NLS-1$ public static final String META_NAME = "name"; //$NON-NLS-1$ public static final String META_VERSION = "version"; //$NON-NLS-1$ public static final String META_VENDOR = "vendor"; //$NON-NLS-1$ public String getMetaInfo(String name); } libisrt-java-4.8.20100629/src/de/intarsys/tools/component/IReferenceCounter.java0000644000175000017500000000620411207726766027243 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.component; import de.intarsys.tools.attribute.Attribute; import de.intarsys.tools.event.AttributeChangedEvent; import de.intarsys.tools.event.DestroyedEvent; import de.intarsys.tools.event.INotificationSupport; /** * An object that is aware of its referents. *

* The object implements a reference counting mechanism that should behave like * this: * *

    *
  • the object should keep a counter that increments when acquired and * decrements when released
  • *
  • upon creation the object should be acquired by the constructor or * factory method.
  • *
  • if the client code is not aware if a new object is created (or taken * from a registry for example), the object published by the factory method * should always be acquired.
  • *
  • the object should not accept method calls before it is acquired
  • *
  • when the counter is zero after release, the object should no longer * accept any calls
  • *
*

* If combined with the {@link INotificationSupport}, the object MAY trigger an * {@link AttributeChangedEvent} upon acquire/release. In this case the * ATTR_REFERENCECOUNT should be used to indicate the attribute. *

* If combined with the {@link INotificationSupport}, the object MAY trigger a * {@link DestroyedEvent} when the reference count reaches 0. */ public interface IReferenceCounter { public static final Attribute ATTR_REFERENCECOUNT = new Attribute( "referenceCount"); public void acquire(); public int getReferenceCount(); public void release(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/component/ContextConfigurationException.java0000644000175000017500000000065311306005210031677 0ustar twernertwernerpackage de.intarsys.tools.component; public class ContextConfigurationException extends Exception { public ContextConfigurationException() { } public ContextConfigurationException(String message) { super(message); } public ContextConfigurationException(Throwable cause) { super(cause); } public ContextConfigurationException(String message, Throwable cause) { super(message, cause); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/component/IContextSupport.java0000644000175000017500000000401711321667642027020 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.component; /** * Component lifecycle feature. *

* The component supports configuration in a context. The context features * itself are intentionally not modeled. The implementor should check and narrow * the type according to the requested features (e.g. * de.intarsys.tools.reflect.IClassLoaderSupport). * */ public interface IContextSupport { public void setContext(Object context) throws ContextConfigurationException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/component/ComponentException.java0000644000175000017500000000366311052336464027511 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.component; public class ComponentException extends RuntimeException { public ComponentException() { super(); } public ComponentException(String message) { super(message); } public ComponentException(String message, Throwable cause) { super(message, cause); } public ComponentException(Throwable cause) { super(cause); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/component/IActivateDeactivate.java0000644000175000017500000000350011025441734027516 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.component; /** * Component lifecycle feature. The component supports activation and * deactivation. * */ public interface IActivateDeactivate { public void activate(); public void deactivate(); public boolean isActive(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/component/ISaveStateSupport.java0000644000175000017500000000371011025441734027263 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.component; /** * An object supporting state dumps. A "save state" is created and restored * transparently by the component. * * */ public interface ISaveStateSupport { /** * Restore a previously saved state. * */ public void restoreState(Object saveState); /** * Create a restorable dump of the objects state. */ public Object saveState(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/component/CommonStartStop.java0000644000175000017500000000575111411055572027001 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.component; import java.util.Set; /** * A common implementation of IStartStop. This abstract class * ensures that start and stop procedures are executed only once. * */ public abstract class CommonStartStop implements IStartStop { private boolean started = false; public CommonStartStop() { super(); } /** * Start the component lifecycle. This method is called once at most. * */ protected void basicStart() { // redefine } /** * Stop the component lifecycle. This method is called once at most. * */ protected void basicStop() { // redefine } /* * (non-Javadoc) * * @see de.intarsys.tools.component.IStartStop#isStarted() */ synchronized public final boolean isStarted() { return started; } /* * (non-Javadoc) * * @see de.intarsys.tools.component.IStartStop#start() */ public final void start() { synchronized (this) { if (started) { return; } basicStart(); started = true; } } /* * (non-Javadoc) * * @see de.intarsys.tools.component.IStartStop#stop() */ public final void stop() { synchronized (this) { if (!started) { return; } basicStop(); started = false; } } /* * (non-Javadoc) * * @see de.intarsys.tools.component.IStartStop#stopRequested() */ public boolean stopRequested(Set visited) { return true; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/component/IStartStop.java0000644000175000017500000000531611411055572025736 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.component; import java.util.Set; /** * This describes the components ability to explicitly start or stop its * lifecycle. This is an alternative and more detailed description than * supported by IStartable and should be preferred. * */ public interface IStartStop extends IInstantiable { /** * Answer true if this object is started * * @return Answer true if this object is started. */ public boolean isStarted(); /** * Start the component lifecycle. A RuntimeException is expected when * starting the component fails. * */ public void start(); /** * Stop the component lifecycle. All resources should be freed. A * RuntimeException is expected when stopping the component fails. */ public void stop(); /** * Ask the component if it agrees to end its lifecycle at the very moment. * The component may deny this request, but it must be prepared anyway to be * stopped. * * @param visited * The optional set of already visited objects in the stop * request cycle. */ public boolean stopRequested(Set visited); } libisrt-java-4.8.20100629/src/de/intarsys/tools/component/IExceptionHandler.java0000644000175000017500000000364610751651476027246 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.component; /** * An object that handles exceptions. This is useful for generic implementation * like IAction objects, that want to encapsulate exception handling along with * the action implementation without knowing anything about their context. * */ public interface IExceptionHandler { public void handleException(Exception e); } libisrt-java-4.8.20100629/src/de/intarsys/tools/component/IInitializeable.java0000644000175000017500000000344411025441734026720 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.component; /** * Component lifecycle feature. The component supports initialization. * */ public interface IInitializeable { /** * Initialize the components state. */ public void initialize(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/component/MetaInfoSupportAdapter.java0000644000175000017500000000117511327617122030262 0ustar twernertwernerpackage de.intarsys.tools.component; import java.util.HashMap; import java.util.Map; public class MetaInfoSupportAdapter implements IMetaInfoSupport { private Map info = new HashMap(); public MetaInfoSupportAdapter(String id, String name, String version, String vendor) { putMetaInfo(META_ID, id); putMetaInfo(META_NAME, name); putMetaInfo(META_VERSION, version); putMetaInfo(META_VENDOR, vendor); } public String getMetaInfo(String name) { return info.get(name); }; protected void putMetaInfo(String name, String value) { info.put(name, name); }; } libisrt-java-4.8.20100629/src/de/intarsys/tools/component/ISuspendResume.java0000644000175000017500000000352111411055572026571 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.component; import de.intarsys.tools.attribute.Attribute; public interface ISuspendResume { public static final Attribute ATTR_SUSPENDED = new Attribute("suspended"); public boolean isSuspended(); public void resume(); public void suspend(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/component/IInstantiable.java0000644000175000017500000000355010751651476026421 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.component; /** * This interface declares the ability of a dynamically loaded component to be * instantiated. * *

* This is the base interface for all instance based component interfaces. *

*/ public interface IInstantiable { // this is a tagging interface } libisrt-java-4.8.20100629/src/de/intarsys/tools/component/ISynchronizable.java0000644000175000017500000000420410774140304026757 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.component; /** * This describes a components ability to check its consistency with any * physical representation, for example a file system. */ public interface ISynchronizable { /** * true if the component is out of synch. * * @return true if the component is out of synch. */ public boolean isOutOfSynch(); /** * Perform a synchronization with the components physical resources. *

* In case of a scheduled synchronization this may be called by an external * daemon. */ public void synch(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/system/0000755000175000017500000000000011412336332022331 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/system/SystemTools.java0000644000175000017500000000473511411055574025517 0ustar twernertwernerpackage de.intarsys.tools.system; import de.intarsys.tools.string.StringTools; public class SystemTools { private static final String Bindir; private static final String Basedir; private static final String Libdir; private final static String osName; private final static String osArch; private static boolean citrix = false; private static boolean windows = false; private static boolean windowsxp = false; private static boolean linux = false; private static boolean mac = false; static { String tempName = System.getProperty("de.intarsys.platform.os.name"); String tempArch = System.getProperty("de.intarsys.platform.os.arch", "x86"); if (tempName == null) { tempName = System.getProperty("os.name"); //$NON-NLS-1$ tempArch = System.getProperty("os.arch"); //$NON-NLS-1$ } osName = tempName; osArch = tempArch; String osNameLowerCase = osName.toLowerCase(); // directory names are relative to some common root if (osNameLowerCase.startsWith("win")) { //$NON-NLS-1$ windows = true; if (osNameLowerCase.equals("windows xp")) { //$NON-NLS-1$ windowsxp = true; } Bindir = Libdir = "bin"; //$NON-NLS-1$ Basedir = StringTools.EMPTY; } else if (osNameLowerCase.startsWith("linux")) { //$NON-NLS-1$ linux = true; if ("amd64".equals(osArch)) { Bindir = "bin"; //$NON-NLS-1$ Libdir = "lib/amd64"; //$NON-NLS-1$ } else { Bindir = "bin"; //$NON-NLS-1$ Libdir = "lib/i386"; //$NON-NLS-1$ } Basedir = StringTools.EMPTY; } else if (osNameLowerCase.startsWith("mac")) { //$NON-NLS-1$ mac = true; Bindir = Libdir = "MacOS"; //$NON-NLS-1$ Basedir = "Resources"; //$NON-NLS-1$ } else { Bindir = Libdir = Basedir = StringTools.EMPTY; } citrix = Boolean.getBoolean("de.intarsys.platform.citrix"); } public static String getBasedir() { return Basedir; } public static String getBindir() { return Bindir; } public static String getLibdir() { return Libdir; } public static String getOSArch() { return osArch; } public static String getOSName() { return osName; } public static boolean isCitrix() { return citrix; } public static boolean isLinux() { return linux; } public static boolean isMac() { return mac; } public static boolean isWindows() { return windows; } public static boolean isWindowsXP() { return windowsxp; } private SystemTools() { // tools class } } libisrt-java-4.8.20100629/src/de/intarsys/tools/number/0000755000175000017500000000000011412336332022275 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/number/NumberWrapper.java0000644000175000017500000000612210751651500025734 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.number; import java.util.Collection; import java.util.Iterator; import java.util.Set; /** * An abstract class for the implementation of objects that may occur in the * definition of a number string. * */ public abstract class NumberWrapper implements Iterable, Set { /** * NumberWrapper constructor comment. */ public NumberWrapper() { super(); } /* * (non-Javadoc) * * @see java.util.Collection#remove(java.lang.Object) */ public boolean remove(Object o) { throw new UnsupportedOperationException( "Remove operation not supported!"); } public boolean removeAll(Collection arg0) { throw new UnsupportedOperationException( "RemoveAll operation not supported!"); } public boolean retainAll(Collection arg0) { throw new UnsupportedOperationException( "RetainAll operation not supported!"); } public void clear() { throw new UnsupportedOperationException( "Clear operation not supported!"); } public Object[] toArray(Object[] arg0) { return toArray(); } protected abstract double getMin(); protected abstract double getMax(); protected Number getFirst() { if (!isEmpty()) { return (Number) iterator().next(); } return null; } public boolean containsAll(Collection arg0) { Iterator iter = arg0.iterator(); while (iter.hasNext()) { Object element = (Object) iter.next(); if (!contains(element)) { return false; } } return true; } abstract public void increment(int i); } libisrt-java-4.8.20100629/src/de/intarsys/tools/number/NumberParser.java0000644000175000017500000001226011411055574025553 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.number; import java.io.IOException; import java.io.StringReader; /** * A parser able to read a definition of numbers. *

* The parser supports single numbers, enumeration of numbers and intervals. *

* *
 * S ::= NumberString
 * NumberString ::= ( Number | Interval) [ ";" (Number | Interval) ]*
 * Interval ::= Number "-" Number
 * Number ::= a valid number literal
 * 
* */ public class NumberParser { public static NumberWrapper parse(String numberstring) throws IOException { if (numberstring == null) { return null; } return new NumberParser(numberstring).parse(); } private StringReader r; protected NumberParser(String numberstring) { super(); r = new StringReader(numberstring); } public int getChar() throws IOException { int i = r.read(); return i; } private NumberWrapper makeWrapperObject(String numberValueInString) { int trenner = numberValueInString.indexOf(NumberInterval.SEPARATOR, 1); if (trenner == -1) { // no 'intervaltrenner' means NumberInstance Object double zahl = Double.parseDouble(numberValueInString); NumberInstance instance = new NumberInstance(zahl); return instance; } else { if (trenner == 0) { // 'intervaltrenner' is first character in string throw new NumberFormatException( "Missing parameter FROM in interval"); } else { if (trenner == (numberValueInString.length() - 1)) { // 'intervaltrenner' is last character in string throw new NumberFormatException( "Missing parameter TO in interval"); } else { // 'intervaltrenner' leads to NumberInterval Object NumberInterval interval = new NumberInterval(); String stringFrom = numberValueInString.substring(0, trenner); String stringTo = numberValueInString .substring(trenner + 1); Number from = new Double(Double.parseDouble(stringFrom)); Number to = new Double(Double.parseDouble(stringTo)); interval.setFrom(from); interval.setTo(to); return interval; } } } } private NumberWrapper parse() throws IOException { NumberList numberList = new NumberList(); numberList = parseNumberString(numberList); return numberList; } private NumberList parseNumberString(NumberList numberList) throws IOException { StringBuilder sb = new StringBuilder(); boolean spaceFoundInNumber = false; for (int i = getChar(); i > -1; i = getChar()) { char c = (char) i; if (Character.isWhitespace(c)) { if (sb.length() == 0) { continue; } else { if (sb.charAt(sb.length() - 1) != '-') { // space allowed after 'intervaltrenner' spaceFoundInNumber = true; } continue; } } else { if (c == NumberList.SEPARATOR) { if (sb.length() == 0) { // SEPARATOR is first sign in string // throw new NumberFormatException("Missing parameter"); } else { numberList.add(makeWrapperObject(sb.toString())); sb.setLength(0); spaceFoundInNumber = false; } } else { if (spaceFoundInNumber == true) { if (c != NumberInterval.SEPARATOR) { throw new NumberFormatException( "Space found in between number"); } else { // space allowed before 'intervaltrenner' sb.append(c); spaceFoundInNumber = false; } } else { sb.append(c); } } } } if (sb.length() > 0) { numberList.add(makeWrapperObject(sb.toString())); } else { // throw new IOException("Missing parameter"); } return numberList; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/number/NumberInstance.java0000644000175000017500000001042410751651500026060 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.number; import java.util.Collection; import java.util.Iterator; import de.intarsys.tools.collection.SingleObjectIterator; /** * An implementation of NumberWrapper that represents a single number object. * */ public class NumberInstance extends NumberWrapper { private Number n; /** * NumberInstance constructor for double. * * @param i * A primitive double to be wrapped */ public NumberInstance(double i) { super(); n = new Double(i); } /** * NumberInstance constructor for int. * * @param i * A primitive int tobe wrapped */ public NumberInstance(int i) { super(); n = new Integer(i); } /** * NumberInstance constructor for {@link Number}. * * @param number * A {@link Number} instance to be wrapped */ public NumberInstance(Number number) { super(); n = number; } /** * NumberInstance constructor for integer value formatted in a String. * * @param numberValueInString * The string containing the integer value. */ public NumberInstance(String numberValueInString) { super(); int zahl = Integer.parseInt(numberValueInString); n = new Integer(zahl); } public java.lang.Number getN() { return n; } public Iterator iterator() { return new SingleObjectIterator(getN()); } public String toString() { return java.text.NumberFormat.getInstance().format(getN()); } public int size() { return 1; } public boolean isEmpty() { return false; } public boolean contains(Object o) { if (o instanceof Number) { return ((Number) o).doubleValue() == n.doubleValue(); } else if (o instanceof NumberWrapper && !((NumberWrapper) o).isEmpty()) { return ((NumberWrapper) o).getFirst().doubleValue() == n .doubleValue(); } return false; } public Object[] toArray() { return new Number[] { n }; } public boolean add(Object arg0) { if (arg0 instanceof Number) { n = (Number) arg0; return true; } else if (arg0 instanceof NumberWrapper && !((NumberWrapper) arg0).isEmpty()) { n = ((NumberWrapper) arg0).getFirst(); return true; } throw new IllegalArgumentException( "Only objects of type Number or NumberWrapper are supported."); } public boolean addAll(Collection arg0) { if (arg0.size() == 0) { return false; } Object o = arg0.iterator().next(); if (o instanceof Number) { n = (Number) arg0; return true; } return false; } protected double getMin() { return n.doubleValue(); } protected double getMax() { return n.doubleValue(); } public void increment(int i) { n = new Integer(getN().intValue() + i); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/number/NumberInterval.java0000644000175000017500000001110710751651500026077 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.number; import java.util.Collection; import java.util.Iterator; import de.intarsys.tools.collection.IntervalIterator; /** * An implementation of NumberWrapper that represents an interval of numbers. * */ public class NumberInterval extends NumberWrapper { public static char SEPARATOR = '-'; private Number from; private Number to; private double step = 1; /** * NumberInterval constructor comment. */ public NumberInterval() { super(); } public void setFrom(java.lang.Number newFrom) { from = newFrom; } public java.lang.Number getFrom() { return from; } public void setTo(java.lang.Number newTo) { to = newTo; } public java.lang.Number getTo() { return to; } public java.util.Iterator iterator() { return new IntervalIterator(from, to); } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getFrom()); sb.append(SEPARATOR); sb.append(getTo()); return sb.toString(); } public int size() { return (int) Math.round((to.doubleValue() - from.doubleValue()) / step) + 1; } public boolean isEmpty() { if ((to == null) || (from == null)) { return true; } return from.intValue() > to.intValue(); } public boolean contains(Object o) { if (o instanceof Number) { Number n = (Number) o; return (n.doubleValue() >= from.doubleValue()) && (n.doubleValue() <= to.doubleValue()); } else if (o instanceof NumberWrapper) { NumberWrapper wrapper = (NumberWrapper) o; return (wrapper.getMin() >= this.getMin()) && (wrapper.getMax() <= this.getMax()); } return false; } public Object[] toArray() { Number[] numbers = new Number[size()]; for (int i = 0; i < numbers.length; i++) { numbers[i] = new Double(from.doubleValue() + (i * step)); } return numbers; } public boolean add(Object arg0) { if (arg0 instanceof Number) { Number n = (Number) arg0; if (n.doubleValue() < from.doubleValue()) { from = new Double(n.doubleValue()); } else if (n.doubleValue() > to.doubleValue()) { to = new Double(n.doubleValue()); } return true; } else if (arg0 instanceof NumberWrapper) { NumberWrapper wrapper = (NumberWrapper) arg0; if (wrapper.getMin() < this.getMin()) { from = new Double(wrapper.getMin()); } if (wrapper.getMax() > this.getMax()) { to = new Double(wrapper.getMax()); } } throw new IllegalArgumentException( "Only objects of type Number or NumberWrapper are supported."); } public boolean addAll(Collection arg0) { Iterator iter = arg0.iterator(); while (iter.hasNext()) { Object element = (Object) iter.next(); if (!add(element)) { return false; } } return true; } protected double getMin() { return from.doubleValue(); } protected double getMax() { return to.doubleValue(); } public void increment(int i) { from = new Integer(getFrom().intValue() + i); to = new Integer(getTo().intValue() + i); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/number/NumberList.java0000644000175000017500000001163210751651500025231 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.number; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import de.intarsys.tools.collection.NestedIterator; /** * An implementation of NumberWrapper that represents an enumeration of single * number objects. * */ public class NumberList extends NumberWrapper { public static char SEPARATOR = ';'; private List list = new ArrayList(); /** * NumberList constructor comment. */ public NumberList() { super(); } public void setList(java.util.List newList) { list = newList; } public java.util.List getList() { return list; } public boolean add(Object arg0) { if (arg0 instanceof NumberWrapper) { getList().add(arg0); return true; } else if (arg0 instanceof Number) { getList().add(new NumberInstance((Number) arg0)); return true; } return false; } public java.util.Iterator iterator() { return new NestedIterator(getList().iterator()); } public String toString() { StringBuilder sb = new StringBuilder(); for (Iterator i = getList().iterator(); i.hasNext();) { sb.append(i.next().toString()); if (i.hasNext()) { sb.append(SEPARATOR); } } return sb.toString(); } public void increment(int i) { for (Iterator it = getList().iterator(); it.hasNext();) { NumberWrapper wrapper = (NumberWrapper) it.next(); wrapper.increment(i); } } public int size() { int size = 0; Iterator iter = getList().iterator(); while (iter.hasNext()) { NumberWrapper element = (NumberWrapper) iter.next(); size = size + element.size(); } return size; } public boolean isEmpty() { if (getList().isEmpty()) { return true; } Iterator iter = getList().iterator(); while (iter.hasNext()) { NumberWrapper element = (NumberWrapper) iter.next(); if (!element.isEmpty()) { return false; } } return true; } public boolean contains(Object o) { Iterator iter = getList().iterator(); while (iter.hasNext()) { NumberWrapper element = (NumberWrapper) iter.next(); if (element.contains(o)) { return true; } } return false; } public Object[] toArray() { Number[] numbers = new Number[size()]; Iterator iter = getList().iterator(); int i = 0; while (iter.hasNext()) { NumberWrapper element = (NumberWrapper) iter.next(); Number[] elementArray = (Number[]) element.toArray(); for (int j = 0; j < elementArray.length; j++) { numbers[i] = elementArray[j]; i++; } } return numbers; } public boolean addAll(Collection arg0) { Iterator iter = arg0.iterator(); while (iter.hasNext()) { Object element = (Object) iter.next(); if (!add(element)) { return false; } } return true; } protected double getMin() { double min = Double.MAX_VALUE; Iterator iter = getList().iterator(); while (iter.hasNext()) { NumberWrapper wrapper = (NumberWrapper) iter.next(); if (wrapper.getMin() < min) { min = wrapper.getMin(); } } return min; } protected double getMax() { double max = Double.MIN_VALUE; Iterator iter = getList().iterator(); while (iter.hasNext()) { NumberWrapper wrapper = (NumberWrapper) iter.next(); if (wrapper.getMax() < max) { max = wrapper.getMax(); } } return max; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reader/0000755000175000017500000000000011412336332022247 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/reader/IDirectTagHandler.java0000644000175000017500000000351510751651476026411 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reader; import java.io.IOException; public interface IDirectTagHandler { public void setLocationProvider(ILocationProvider locationProvider); public void startTag(); public String process(String tagContent, Object context) throws IOException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/reader/LogReader.java0000644000175000017500000000657711025664516025005 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reader; import java.io.FilterReader; import java.io.IOException; import java.io.Reader; import java.io.Writer; /** * A reader that logs any char read. *

* The reader is piped in the reading process, any characters read are written * to an associated writer object. * *

 * Client -> LogReader -> Reader -> Source
 *            |
 *            v
 *           Writer
 * 
* * todo make closing of associated writer configurable */ public class LogReader extends FilterReader { Writer log; public LogReader(Reader in, Writer w) { super(in); setLog(w); } @Override public void close() throws IOException { super.close(); if (getLog() != null) { getLog().close(); } } public java.io.Writer getLog() { return log; } @Override public int read() throws java.io.IOException { int b = super.read(); if ((b > -1) && (log != null)) { log.write(b); } return b; } /** * Read characters into a portion of an array. This method will block until * some input is available, an I/O error occurs, or the end of the stream is * reached. * * @param cbuf * Destination buffer * @param off * Offset at which to start storing characters * @param len * Maximum number of characters to read * * @return The number of characters read, or -1 if the end of the stream has * been reached * * @exception IOException * If an I/O error occurs */ @Override public int read(char[] cbuf, int off, int len) throws IOException { int bytes = super.read(cbuf, off, len); if ((bytes > -1) && (log != null)) { log.write(cbuf, off, bytes); } return bytes; } public void setLog(java.io.Writer newLog) { log = newLog; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reader/LocationAwareReader.java0000644000175000017500000001065711025664516027006 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reader; import java.io.FilterReader; import java.io.IOException; import java.io.Reader; /** * An implementation of ILocationProvider. This class can be "piped" in a reader * stream to access the current "pointer" into the data. * *

* A common pitfall is to read the ILocationProvider via a BufferedReader - this * will certainly not provide with a correct character location! *

*/ public class LocationAwareReader extends FilterReader implements ILocationProvider { private boolean open = true; private int line = 1; private int column = 1; private int position = 0; public LocationAwareReader(Reader in) { super(in); } @Override public void close() throws IOException { open = false; in.close(); } public void ensureOpen() throws IOException { if (!open) { throw new IOException("Stream closed"); } } public int getColumn() { return column; } public int getLine() { return line; } public int getPosition() { return position; } @Override public int read() throws IOException { synchronized (lock) { ensureOpen(); int i = in.read(); if (i != -1) { position++; if (i == '\n') { line++; column = 1; } else { column++; } } return i; } } @Override public int read(char[] cbuf, int off, int len) throws IOException { ensureOpen(); if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else { if (len == 0) { return 0; } } int pos = off; int i; for (i = read(); (pos < (off + len)) && (i != -1);) { cbuf[pos] = (char) i; pos++; i = read(); } if ((i == -1) && (pos == off)) { return -1; } return (pos - off); } /** * @param column * The column to set. */ public void setColumn(int column) { this.column = column; } /** * @param line * The line to set. */ public void setLine(int line) { this.line = line; } /** * Offset the current location to a user defined line and column. * * @param line * The line we want the reader to accept as new location * @param column * The column we want the reader to accept as new location */ public void setLocation(int line, int column) { this.line = line; this.column = column; } /** * @param position * The position to set. */ public void setPosition(int position) { this.position = position; } @Override public long skip(long n) throws IOException { if (n < 0) { throw new IOException("parameter is negative"); } long current = 0; int ch = 0; for (; (current < n) && (ch != -1); ch = read(), ++current) { // do nothing } return current; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reader/UnEscapeReader.java0000644000175000017500000001600710751651476025762 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reader; import java.io.FilterReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import de.intarsys.tools.stream.StreamTools; /** * A reader that can unescape character data from a wrapped reader. * */ public class UnEscapeReader extends FilterReader implements IUnEscaper { public static final char DefaultEscape = '\\'; private static final Map DefaultEscapeMap = new HashMap(); static { // escape the escape DefaultEscapeMap.put(new Character('\\'), new Character('\\')); // escape to insert whitespace DefaultEscapeMap.put(new Character('n'), new Character('\n')); DefaultEscapeMap.put(new Character('r'), new Character('\r')); DefaultEscapeMap.put(new Character('t'), new Character('\t')); // escape to remove whitespace DefaultEscapeMap.put(new Character('\n'), null); DefaultEscapeMap.put(new Character('\r'), null); DefaultEscapeMap.put(new Character('\t'), null); DefaultEscapeMap.put(new Character(' '), null); } public static String unescape(String in) throws IOException { UnEscapeReader reader = new UnEscapeReader(new StringReader(in)); return StreamTools.toString(reader); } private char escape = DefaultEscape; private Map escapeMap = DefaultEscapeMap; private boolean mapped = false; private boolean open = true; private char unicodePrefix = 'u'; public UnEscapeReader(Reader in) { super(in); } public UnEscapeReader(Reader in, char escape, Map map) { super(in); this.escape = escape; this.escapeMap = map; } public UnEscapeReader(Reader in, Map map) { super(in); this.escapeMap = map; } public void addEscapedCharacter(char key, char value) { // this creates a new copy! Map tempMap = getEscapeMap(); tempMap.put(new Character(key), new Character(value)); setEscapeMap(tempMap); } public void close() throws IOException { in.close(); open = false; } public char getEscape() { return escape; } public java.util.Map getEscapeMap() { return new HashMap(escapeMap); } public char getUnicodePrefix() { return unicodePrefix; } public boolean isMapped() { return mapped; } public int read() throws IOException { mapped = false; int i = in.read(); if (i == escape) { mapped = true; i = readEscaped(); } return i; } public int read(char[] cbuf, int off, int len) throws IOException { if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else { if (len == 0) { return 0; } } int pos = off; int i; // Korrektur BWA: es wurde jeweils ein Zeichen zu viel gelesen. for (i = 0; (pos < (off + len)) && (i != -1);) { i = read(); cbuf[pos] = (char) i; pos++; } if ((i == -1) && (pos == off)) { return -1; } return (pos - off); } protected int readEscaped() throws IOException { int i = in.read(); if (i == -1) { return -1; } if ((char) i == '\r') { int next = read(); if (((char) next == '\n') && !isMapped()) { // escaped CR/LF (Windows), ignore line feed return read(); } else { // escaped CR, ignore carriage return return next; } } if ((char) i == '\n') { // escaped LF (Unix), ignore line feed return read(); } if ((char) i == getUnicodePrefix()) { return readHex(); } Character key = new Character((char) i); Character value = (Character) escapeMap.get(key); if (value == null) { if (escapeMap.containsKey(key)) { // this key is mapped to null, skip from stream and read // again return read(); } else { throw new IOException("unrecognized escape sequence: \"\\" + (char) i + "\""); } } else { return value.charValue(); } } protected int readHex() throws IOException { // todo remove cb handling StringBuilder buf = new StringBuilder(); int ch; for (ch = in.read(); ((((char) ch >= '0') && ((char) ch <= '9')) || (((char) ch >= 'A') && ((char) ch <= 'F')) || (((char) ch >= 'a') && ((char) ch <= 'f'))) && (buf.length() < 4); ch = in.read()) { buf.append((char) ch); } if (ch == -1) { return -1; } if (buf.length() < 4) { throw new IOException("illegal escape sequence: \"\\u" + buf.toString() + "\""); } String hexString = new String(buf); return Integer.parseInt(hexString, 16); } public void removeEscapedCharacter(char key) { Map tempMap = getEscapeMap(); tempMap.remove(new Character(key)); setEscapeMap(tempMap); } public void removeEscapedCharacters() { setEscapeMap(new HashMap()); } public void setEscape(char newEscape) { if (newEscape == escape) { return; } Map tempMap = getEscapeMap(); tempMap.remove(new Character(getEscape())); tempMap.put(new Character(newEscape), new Character(newEscape)); setEscapeMap(tempMap); escape = newEscape; } protected void setEscapeMap(java.util.Map newEscapeMap) { escapeMap = newEscapeMap; } public void setUnicodePrefix(char newUniChar) { unicodePrefix = newUniChar; } public long skip(long n) throws IOException { if (n < 0) { throw new IOException("parameter is negative"); } long actual = 0; int ch = 0; for (; (actual < n) && (ch != -1); ch = read(), ++actual) { // ignore characters } return actual; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reader/FillReader.java0000644000175000017500000000612210751651476025142 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reader; import java.io.IOException; import java.io.Reader; /** * A Helper reader that repeatedly returns the characters in a predefined * pattern until it is closed. * */ public class FillReader extends Reader { /** * the pattern that is "read" all over. */ private String pattern; /** * Flag if reader is closed. */ private boolean closed = false; /** * The position within the string */ private int pos = 0; /** * Create a FillReader on string. * * @param pattern * The string that is read all over again. */ public FillReader(String pattern) { super(); if (pattern == null) { throw new NullPointerException("pattern may not be null"); } this.pattern = pattern; } /* * (non-Javadoc) * * @see java.io.Reader#close() */ public void close() throws IOException { closed = true; } /* * (non-Javadoc) * * @see java.io.Reader#read(char[], int, int) */ public int read(char[] cbuf, int off, int len) throws IOException { for (int i = off; i < (off + len); i++) { int c = read(); if (c == -1) { return off - i; } else { cbuf[i] = (char) c; } } return len; } /* * (non-Javadoc) * * @see java.io.Reader#read() */ public int read() throws IOException { if (closed) { return -1; } else { if (pos >= pattern.length()) { if (pattern.length() == 0) { return -1; } pos = 0; } return pattern.charAt(pos++); } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/reader/ILocationProvider.java0000644000175000017500000000347111025664516026523 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reader; /** * An interface describing the ability to provide information about the current * context into a data stream. * */ public interface ILocationProvider { int getColumn(); int getLine(); int getPosition(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/reader/IUnEscaper.java0000644000175000017500000000346111025664516025124 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reader; /** * An interface for readers that can escape character sequences. * */ public interface IUnEscaper { void addEscapedCharacter(char key, char value); boolean isMapped(); void setEscape(char escape); } libisrt-java-4.8.20100629/src/de/intarsys/tools/reader/DirectTagReader.java0000644000175000017500000002312611411055574026114 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.reader; import java.io.FilterReader; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.Map; import de.intarsys.tools.string.StringTools; /** * A {@link Reader} that is aware of embedded tags. An example is processing a * JSP page, where java is embededd using "<%...%>". After recognizing such a * tag, the associated {@link IDirectTagHandler} is informed to handle the tag. * After handling, the result of the {@link IDirectTagHandler} is streamd as a * replacement for the tag itself. After streaming the processed tag content, * reading the input continues as normal. * */ public class DirectTagReader extends FilterReader { static private class NullLocationProvider implements ILocationProvider { public int getColumn() { return 0; } public int getLine() { return 0; } public int getPosition() { return 0; } } public static final char ESCAPE_CHARACTER = '\\'; public static final Map DefaultEscapeMap = new HashMap(); private static final char[] defaultEndTag = "}".toCharArray(); private static final char[] defaultStartTag = "${".toCharArray(); static private ILocationProvider nullLocationProvider = new NullLocationProvider(); static { DefaultEscapeMap.put(new Character('\\'), new Character('\\')); DefaultEscapeMap.put(new Character('n'), new Character('\n')); DefaultEscapeMap.put(new Character('r'), new Character('\r')); DefaultEscapeMap.put(new Character('t'), new Character('\t')); DefaultEscapeMap.put(new Character('$'), new Character('$')); DefaultEscapeMap.put(new Character('}'), new Character('}')); DefaultEscapeMap.put(new Character('\n'), null); DefaultEscapeMap.put(new Character('\r'), null); DefaultEscapeMap.put(new Character('\t'), null); DefaultEscapeMap.put(new Character(' '), null); } static public String escape(String value) { return value.replaceAll("\\$\\{", "\\$\\{\\$\\{\\}"); } private int bufferLength = 0; private char[] endTag = defaultEndTag; private IDirectTagHandler handler; private char[] readBuffer = new char[100]; private char[] startTag = defaultStartTag; private StringBuilder tagBuffer = new StringBuilder(); private UnEscapeReader unescapeReader; private boolean checkTag = true; private Object context; public DirectTagReader(Reader pReader, IDirectTagHandler handler, Object context) { this(pReader, handler, context, true); } public DirectTagReader(Reader pReader, IDirectTagHandler handler, Object context, boolean escape) { super(pReader); if (escape) { this.in = new UnEscapeReader(pReader, ESCAPE_CHARACTER, DefaultEscapeMap); unescapeReader = (UnEscapeReader) this.in; } this.handler = handler; this.context = context; if (pReader instanceof ILocationProvider) { handler.setLocationProvider((ILocationProvider) pReader); } else { handler.setLocationProvider(nullLocationProvider); } } /** * Read from either the read buffer or the underlying stream. * * @return The next character available frm the read buffer or underlying * stream. * @throws IOException */ protected int basicRead() throws IOException { if (bufferLength > 0) { // consume "prepared" content - this is read ahead or // the result from a tag handling callback return readBuffer[--bufferLength]; } checkTag = true; return super.read(); } protected IDirectTagHandler getHandler() { return handler; } protected boolean isSpecialTag(String tag) { if (tag.length() == startTag.length) { for (int index = 0; index < startTag.length; index++) { if (tag.charAt(index) != startTag[index]) { return false; } } return true; } else { return false; } } /** * Read a character until we encounter a tag. * * @see java.io.Reader#read() */ @Override public int read() throws IOException { int i = basicRead(); if (checkTag && (i == startTag[0]) && (unescapeReader == null || !unescapeReader.isMapped())) { return scanTag(); } return i; } /* * (non-Javadoc) * * @see java.io.Reader#read(char[], int, int) */ @Override public int read(final char[] cbuf, final int off, final int len) throws IOException { for (int i = 0; i < len; i++) { final int ch = read(); if (ch == -1) { if (i == 0) { return -1; } else { return i; } } cbuf[off + i] = (char) ch; } return len; } protected int scanEndTag() throws IOException { int tagIndex = 0; int i = endTag[0]; while (i == endTag[tagIndex]) { tagIndex++; if (tagIndex == endTag.length) { return -1; } i = basicRead(); } if (i != -1) { unread(i); } unread(endTag, 0, tagIndex); // consume buffer content return basicRead(); } /** * Scan the stream for tagged content. We check the presence of the start * tag. If found the stream is read until the presence of the end tag. If * the start tag is not completely found, we return the literal stream * content. * * @return * @throws IOException */ protected int scanTag() throws IOException { int tagIndex = 0; int i = startTag[0]; while (i == startTag[tagIndex]) { tagIndex++; if (tagIndex == startTag.length) { handler.startTag(); return scanTagContent(); } i = basicRead(); } if (i != -1) { unread(i); } unread(startTag, 0, tagIndex); // consume buffer content return basicRead(); } /** * Scan the content between start and end tag and process the result. * * @throws IOException */ protected int scanTagContent() throws IOException { tagBuffer.setLength(0); int i = tagRead(); while (i != -1) { tagBuffer.append((char) i); i = tagRead(); } String tag = tagBuffer.toString(); String temp; if (isSpecialTag(tag)) { temp = tag; } else { // now process tag content detected temp = getHandler().process(tag, context); } if (!StringTools.isEmpty(temp)) { unread(temp.toCharArray(), 0, temp.length()); // we do not check for tags in result recursive checkTag = false; } // we make a full read to enable processing for an immediate new tag return read(); } public void setEndTag(String tag) { if (endTag != null && unescapeReader != null) { unescapeReader.removeEscapedCharacter(endTag[0]); } endTag = tag.toCharArray(); if (unescapeReader != null) { unescapeReader.addEscapedCharacter(endTag[0], endTag[0]); } } public void setStartTag(String tag) { if (startTag != null && unescapeReader != null) { unescapeReader.removeEscapedCharacter(startTag[0]); } startTag = tag.toCharArray(); if (unescapeReader != null) { unescapeReader.addEscapedCharacter(startTag[0], startTag[0]); } } /** * Read the underlying stream until the end tag is encountered. When we find * the end tag, we return -1, anything else is IOException. * * @return next char from stream between tags * @throws IOException */ protected int tagRead() throws IOException { int i = super.read(); if (i == -1) { throw new IOException("end tag '" + new String(endTag) + "' missing"); } if ((i == endTag[0]) && (unescapeReader == null || !unescapeReader.isMapped())) { return scanEndTag(); } return i; } protected void unread(char[] chars, int start, int len) { if (readBuffer.length < (bufferLength + len)) { char[] newBuffer = new char[(bufferLength + len) * 2]; System.arraycopy(readBuffer, 0, newBuffer, 0, bufferLength); readBuffer = newBuffer; } for (int i = (start + len) - 1; i >= start; i--) { readBuffer[bufferLength++] = chars[i]; } } protected void unread(int c) { if (readBuffer.length < (bufferLength + 1)) { char[] newBuffer = new char[(bufferLength + 1) * 2]; System.arraycopy(readBuffer, 0, newBuffer, 0, bufferLength); readBuffer = newBuffer; } readBuffer[bufferLength++] = (char) c; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/file/0000755000175000017500000000000011412336332021724 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/file/WildcardMatch.java0000644000175000017500000000676511124210476025313 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.file; import java.io.File; /** * Handles wildcards for filename matching. */ public class WildcardMatch { private boolean ignoreCase = true; private boolean matchSeparators = true; /** * */ public WildcardMatch() { super(); } protected char adjustCase(char c) { return ignoreCase ? Character.toLowerCase(c) : c; } public boolean isIgnoreCase() { return ignoreCase; } public boolean isMatchSeparators() { return matchSeparators; } public boolean match(final String pattern, final String string) { // TODO lot of optimizations // be sure test still runs char c; int len = pattern.length(); int n = 0; for (int p = 0; p < len; p++) { c = adjustCase(pattern.charAt(p)); switch (c) { case '?': if (string.length() == n) { return false; } if (!matchSeparators && (string.charAt(n) == File.separatorChar)) { return false; } break; case '*': if (++p == pattern.length()) { for (; string.length() > n; ++n) { if ((string.charAt(n) == File.separatorChar) && !matchSeparators) { return false; } } return true; } else { for (; string.length() >= n; ++n) { if (match(pattern.substring(p), string.substring(n))) { return true; } if ((n == string.length()) || ((string.charAt(n) == File.separatorChar) && !matchSeparators)) { return false; } } } return false; default: if (string.length() == n) { return false; } if (c != adjustCase(string.charAt(n))) { return false; } } ++n; } if (string.length() == n) { return true; } return false; } public void setIgnoreCase(boolean newIgnoreCase) { ignoreCase = newIgnoreCase; } public void setMatchSeparators(boolean newMatchSeparators) { matchSeparators = newMatchSeparators; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/file/FileTools.java0000644000175000017500000007761411412330254024503 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.file; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Logger; import de.intarsys.tools.logging.LogTools; import de.intarsys.tools.stream.StreamTools; import de.intarsys.tools.string.StringTools; /** * Some utility methods to ease life with {@link File} instances. */ public class FileTools { public static class Lock { protected File file; protected File lockFile; protected FileOutputStream lockStream; protected boolean valid = true; synchronized public boolean isValid() { return valid; } synchronized public void release() { unlock(this); } } public static final String DIRECTORY_LOCK = "directory.lock"; private final static Logger Log = LogTools.getLogger(FileTools.class); static private Map maps = new HashMap(); /** * Concatenate the two files given in source and * destination. * * @param source * The file to be appended. * @param destination * The file to append to. * * @throws IOException */ public static void appendFile(File source, File destination) throws IOException { FileInputStream is = null; FileOutputStream os = null; if (equalsOnSystem(source, destination)) { return; } try { is = new FileInputStream(source); os = new FileOutputStream(destination, true); StreamTools.copyStream(is, false, os, false); } catch (Exception e) { throw new IOException("copying failed (" + e.getMessage() + ")"); } finally { StreamTools.close(is); StreamTools.close(os); } } /** * Utility method for checking the availablity of a directory. * * @param dir * The directory to check. * @param create * Flag if we should create if dir not already exists. * @param checkCanRead * Flag if we should check read permission. * @param checkCanWrite * Flag if we should check write permission. * * @return The checked directory. * * @throws IOException */ public static File checkDirectory(File dir, boolean create, boolean checkCanRead, boolean checkCanWrite) throws IOException { if (dir == null) { return dir; } if (!dir.exists() && create) { if (!dir.mkdirs()) { // concurrent creation may lead to exception - recheck later // throw new IOException("Can't create directory " + // dir.getPath()); } } if (!dir.exists()) { throw new IOException("Can't create directory " + dir.getPath()); } if (!dir.isDirectory()) { throw new IOException("Can't create directory " + dir.getPath()); } if (checkCanRead && !dir.canRead()) { throw new IOException("No read access for directory " + dir.getPath()); } if (checkCanWrite && !dir.canWrite()) { throw new IOException("No write access for directory " + dir.getPath()); } return dir; } /** * @see #checkDirectory(File, boolean, boolean, boolean) */ public static File checkDirectory(String path, boolean create, boolean checkCanRead, boolean checkCanWrite) throws IOException { return checkDirectory(new File(path), create, checkCanRead, checkCanWrite); } /** * Copy the byte content of source to destination. * * @param source * The file whose contents we should copy. * @param destination * The file where the contents are copied to. * * @throws IOException */ public static void copyBinaryFile(File source, File destination) throws IOException { // todo move to stream if (!destination.getParentFile().exists()) { destination.getParentFile().mkdirs(); } FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(source); os = new FileOutputStream(destination); StreamTools.copyStream(is, os); } finally { StreamTools.close(is); StreamTools.close(os); } destination.setLastModified(source.lastModified()); } /** * @see #copyBinaryFile(File, File) */ public static void copyFile(File source, File destination) throws IOException { copyBinaryFile(source, destination); } /** * Copy the character content of source to * destination. * * @param source * The file whose contents we should copy. * @param sourceEncoding * The encoding of the source byte stream. * @param destination * The file where the contents are copied to. * @param destinationEncoding * The encoding of the destination byte stream. * * @throws IOException */ public static void copyFile(File source, String sourceEncoding, File destination, String destinationEncoding) throws IOException { // todo move to stream if ((sourceEncoding == null) || (destinationEncoding == null) || sourceEncoding.equals(destinationEncoding)) { copyBinaryFile(source, destination); return; } if (!destination.getParentFile().exists()) { destination.getParentFile().mkdirs(); } FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(source); os = new FileOutputStream(destination); StreamTools.copyEncodedStream(is, sourceEncoding, os, destinationEncoding); } catch (Exception e) { throw new IOException("copying failed (" + e.getMessage() + ")"); } finally { StreamTools.close(is); StreamTools.close(os); } } public static void copyRecursively(File source, File destination) throws IOException { if (source.isFile()) { copyFile(source, destination); return; } if (!source.isDirectory()) { throw new IOException("file '" + source.getAbsolutePath() + "' does not exist."); } if (destination.isFile()) { throw new IOException("cannot copy directory into file"); } destination.mkdirs(); String[] content = source.list(); for (int i = 0; i < content.length; i++) { copyRecursively(new File(source, content[i]), new File(destination, content[i])); } } public static File copyRecursivelyInto(File source, File destinationParent, String newName) throws IOException { if (destinationParent.isFile()) { throw new IOException("can't copy into file"); } String destinationName; if (newName == null) { destinationName = source.getName(); } else { destinationName = newName; } File destinationFile = new File(destinationParent, destinationName); if (source.equals(destinationFile)) { return destinationFile; } if (source.isFile()) { copyFile(source, destinationFile); return destinationFile; } if (!source.isDirectory()) { throw new IOException("file '" + source.getAbsolutePath() + "' does not exist."); } String[] content = source.list(); // play safe - list before creating directory (no recursion) destinationFile.mkdirs(); for (int i = 0; i < content.length; i++) { copyRecursivelyInto(new File(source, content[i]), destinationFile, content[i]); } return destinationFile; } /** * Create an empty file. * * @param file * @throws IOException */ public static void createEmptyFile(File file) throws IOException { FileOutputStream os = new FileOutputStream(file); try { // } finally { StreamTools.close(os); } } /** * Create a file object representing a temporary file in the user's temp dir * with the same name as the given file. * * @param file * file to use * @return file object representing a temporary file */ public static File createTempFile(File file) throws IOException { String name; String extension; int index; name = file.getName(); index = name.lastIndexOf('.'); if (index >= 0) { extension = name.substring(index); name = name.substring(0, index); } else { extension = StringTools.EMPTY; } if (name.length() < 3) { name = "tmp" + name; } return TempTools.createTempFile(name, extension); } /** * Create a file object representing a temporary file in the user's temp dir * with the given filename. *

* This does not actually create a file in the file system. * * @param filename * filename to use * @return file object representing a temporary file */ public static File createTempFile(String filename) throws IOException { return createTempFile(new File(filename)); } /** * Delete any file in directory that is older than * millis milliseconds. When recursiveScan is * true the directory lookup is made recursive. * * @param directory * The directory to scan. * @param millis * The number of milliseconds a file is allowed to live. * @param recursiveScan * Flag if we should handle directories recursive. * * @throws IOException */ public static void deleteAfter(File directory, long millis, boolean recursiveScan) throws IOException { if (millis <= 0) { return; } String[] fileNames = directory.list(); if (fileNames == null) { throw new IOException("can not list " + directory); } long checkMillis = System.currentTimeMillis() - millis; for (int j = 0; j < fileNames.length; j++) { File file = new File(directory, fileNames[j]); if (file.isDirectory() && recursiveScan) { deleteAfter(file, millis, recursiveScan); } if (file.lastModified() < checkMillis) { file.delete(); } } } /** * Deletes a file or directory, if necessary recursivly. * *

* Returns true if file could be deleted inclusive its * components, otherwise false. *

* * @param file * The file or directory to delete. * * @return true if file could be deleted inclusive its * components, otherwise false. */ public static boolean deleteRecursivly(File file) { return deleteRecursivly(file, true); } /** * Deletes a file or directory, if necessary recursivly. * *

* Returns true if file could be deleted inclusive its * components, otherwise false. *

* * @param file * The file or directory to delete. * @param deleteRoot * Flag if the root directory should be deleted itself. * * @return true if file could be deleted inclusive its * components, otherwise false. */ public static boolean deleteRecursivly(File file, boolean deleteRoot) { if (file == null || !file.exists()) { return true; } if (file.isFile()) { return file.delete(); } String[] files = file.list(); if (files == null) { return false; } if (files.length == 0) { return file.delete(); } for (int i = 0; i < files.length; i++) { if (!deleteRecursivly(new File(file, files[i]))) { return false; } } if (deleteRoot) { return file.delete(); } return true; } /** * true when the two files represent the same physical file in * the file system. * * @param source * The first file to be checked. * @param destination * The second file to be checked. * * @return true when the two files represent the same physical * file in the file system. */ public static boolean equalsOnSystem(File source, File destination) { try { if (isWindows()) { return source.getCanonicalPath().equalsIgnoreCase( destination.getCanonicalPath()); } else { return source.getCanonicalPath().equals( destination.getCanonicalPath()); } } catch (IOException e) { return false; } } /** * Get the local name of the file in its directory without the extension. * * @param file * The file whose base name is requested. * * @return The local name of the file in its directory without the * extension. */ public static String getBaseName(File file) { if (file == null) { return getBaseName((String) null, StringTools.EMPTY); } else { return getBaseName(file.getName(), StringTools.EMPTY); } } /** * Get the local name of the file in its directory without the extension. * * @param file * The file whose base name is requested. * * @return The local name of the file in its directory without the * extension. */ public static String getBaseName(File file, String defaultName) { if (file == null) { return getBaseName((String) null, defaultName); } else { return getBaseName(file.getName(), defaultName); } } /** * Get the local name of the file in its directory without the extension. * * @param filename * The filename whose base name is requested. * * @return The local name of the file in its directory without the * extension. */ public static String getBaseName(String filename) { return getBaseName(filename, StringTools.EMPTY); } /** * Get the local name of the file in its directory without the extension. * * @param filename * The filename whose base name is requested. * @param defaultName * returned if filename is null or a empty String * * @return The local name of the file in its directory without the * extension. */ public static String getBaseName(String filename, String defaultName) { if (StringTools.isEmpty(filename)) { return defaultName; } int dotPos = filename.lastIndexOf('.'); if (dotPos >= 1) { return filename.substring(0, dotPos); } return filename; } public static String getEncoding() { return System.getProperty("file.encoding"); } /** * Get the extension of the file name. If no extension is present, the empty * string is returned. * * @param file * The file whose extension is requested. * * @return The extension of the file name. If no extension is present, the * empty string is returned. */ public static String getExtension(File file) { return getExtension(file.getName(), StringTools.EMPTY); } /** * Get the extension of the file name. If no extension is present, the empty * string is returned. * * @param filename * The filename whose extension is requested. * * @return The extension of the file name. If no extension is present, the * empty string is returned. */ public static String getExtension(String filename) { return getExtension(filename, StringTools.EMPTY); } /** * Get the extension of the file name. If no extension is present, the * defaultName is returned. * * @param filename * The filename whose extension is requested. * * @param defaultName * returned if the filename is empty or null or there is no * extension * * @return The extension of the file name. If no extension is present, the * empty string is returned. */ public static String getExtension(String filename, String defaultName) { if (StringTools.isEmpty(filename)) { return defaultName; } int dotPos = filename.lastIndexOf('.'); if (dotPos >= 0) { return filename.substring(dotPos + 1); } return defaultName; } /** * Get the local name of the file in its directory (with extension). * * @param filename * The filename whose name is requested. * * @return The local name of the file in its directory (with extension) */ public static String getFileName(String filename) { return getFileName(filename, StringTools.EMPTY); } /** * Get the local name of the file in its directory (with extension). * * @param filename * The filename whose name is requested. * @param defaultName * returned if filename is null or a empty String * * @return The local name of the file in its directory (with extension) */ public static String getFileName(String filename, String defaultName) { if (StringTools.isEmpty(filename)) { return defaultName; } int dotPos = filename.lastIndexOf('/'); if (dotPos >= 0) { if (dotPos == filename.length() - 1) { return defaultName; } else { filename = filename.substring(dotPos + 1); } } dotPos = filename.lastIndexOf('\\'); if (dotPos >= 0) { if (dotPos == filename.length() - 1) { return defaultName; } else { filename = filename.substring(dotPos + 1); } } return filename; } /** * Try to get a valid parent for file. * * @param file */ public static File getParentFile(File file) { File parentFile = file.getParentFile(); if (parentFile == null) { parentFile = file.getAbsoluteFile().getParentFile(); } if (parentFile == null) { return null; } File grandpa = parentFile.getParentFile(); if (grandpa != null) { // filter UNC path root also, it is not "enumerable" String grandpaPath = grandpa.getAbsolutePath(); if (grandpaPath.equals("\\\\")) { return null; } } return parentFile; } /** * break a path down into individual elements and add to a list. example : * if a path is /a/b/c/d.txt, the breakdown will be [d.txt,c,b,a] * * @param f * input file * * @return a List collection with the individual elements of the path in * reverse order */ private static List getPathList(File f) throws IOException { List l = new ArrayList(); File r = f.getCanonicalFile(); while (r != null) { if (r.getName().length() == 0) { int dblptIndex = r.getPath().indexOf(":"); if (dblptIndex == -1) { l.add(""); } else { l.add(r.getPath().substring(0, dblptIndex)); } } else { l.add(r.getName()); } r = r.getParentFile(); } List reversed = new ArrayList(); for (int i = l.size() - 1; i >= 0; i--) { reversed.add(l.get(i)); } return reversed; } /** * get relative path of "file" with respect to "base" directory example : * * * base = /a/b/c; * file = /a/d/e/x.txt; * getRelativePath(file, base) == ../../d/e/x.txt; * * * @param base * base path, should be a directory, not a file, or it doesn't * make sense * @param file * file to generate path for * * @return path from home to f as a string */ public static String getPathRelativeTo(File file, File base) throws IOException { String relativePath = null; if (base != null) { List fileList = getPathList(file); List baseList = getPathList(base); relativePath = matchPathLists(fileList, baseList); } if (relativePath == null) { return file.getAbsolutePath(); } else { return relativePath; } } public static String getPathRelativeTo(File file, File base, boolean ifAncestor) { if (base == null) { return file.getPath(); } else { if (FileTools.isAncestor(base, file)) { try { return FileTools.getPathRelativeTo(file, base); } catch (IOException e) { return file.getPath(); } } else { return file.getPath(); } } } public static boolean isAncestor(File parent, File descendant) { if (parent == null) { return false; } File current = descendant; while (!parent.equals(current)) { if (current == null) { return false; } current = current.getParentFile(); } return true; } public static boolean isWindows() { return File.separatorChar == '\\'; } public static Lock lock(File file) { synchronized (maps) { if (maps.get(file) != null) { // some systems do not prevent locking in the same VM return null; } FileOutputStream os = null; FileChannel channel = null; File lockFile = null; try { if (file.isFile()) { lockFile = new File(file.getAbsolutePath() + ".lock"); } else { lockFile = new File(file, DIRECTORY_LOCK); } os = new FileOutputStream(lockFile); channel = os.getChannel(); channel.tryLock(); Lock lock = new Lock(); lock.file = file; lock.lockFile = lockFile; lock.lockStream = os; maps.put(file, lock); return lock; } catch (Exception e) { StreamTools.close(os); if (channel != null) { try { channel.close(); } catch (IOException ex) { // } } if (lockFile != null) { lockFile.delete(); } return null; } } } /** * figure out a string representing the relative path of 'f' with respect to * 'r' * * @param r * home path * @param f * path of file * * @return The relative path */ private static String matchPathLists(List fileList, List baseList) { Iterator sourceIterator = baseList.iterator(); Iterator targetIterator = fileList.iterator(); // remove equal path components boolean intersection = false; while (sourceIterator.hasNext() && targetIterator.hasNext()) { if (sourceIterator.next().equals(targetIterator.next())) { sourceIterator.remove(); targetIterator.remove(); intersection = true; } else { break; } } // only the differing path components remain if (!intersection) { return null; } String relPath = ""; for (int i = 0; i < baseList.size(); i++) { relPath += (".." + File.separator); } for (Iterator i = fileList.iterator(); i.hasNext();) { relPath += (i.next()); if (i.hasNext()) { relPath += File.separator; } } return relPath; } /** * @see #renameFile(File, String, File, String) */ public static void renameFile(File source, File destination) throws IOException { renameFile(source, null, destination, null); } /** * "Rename" a file. * *

* The effect is that there is a new file destination, encoded * in destinationEncoding, the old file source is * deleted. *

* * @param source * The source name of the file. * @param sourceEncoding * The encoding of the source file. * @param destination * The destination name of the file. * @param destinationEncoding * The encoding of the destination file. * * @throws IOException * */ public static void renameFile(File source, String sourceEncoding, File destination, String destinationEncoding) throws IOException { if (source.getCanonicalFile().equals(destination.getCanonicalFile())) { return; } if (((sourceEncoding != null) && (destinationEncoding != null) && !sourceEncoding .equals(destinationEncoding)) || !source.renameTo(destination)) { // try a little harder // some implementations can't rename over different file system // platforms // (e.g. from NT to OS/2) copyFile(source, sourceEncoding, destination, destinationEncoding); if (!source.delete()) { // undo creation of copy destination.delete(); throw new IOException("deleting " + source + " failed"); } } } /** * Return a new {@link File} instance for "path". If path is relative, than * it will be interpreted as a child of "parent", if it is absolute, it is * returned as is. *

* ATTENTION: On windows, if "path" is absolute but without drive or UNC * prefix, this root information is NOT taken from "parent". * * @param parent * @param path * @return Return a new {@link File} instance for "path". */ public static File resolvePath(File parent, String path) { if (StringTools.isEmpty(path)) { return (parent == null) ? new File("") : parent; } if (parent == null) { return new File(path); } File file = new File(path); if (file.isAbsolute()) { return file; } return new File(parent, path); } /** * Create a byte array with the files content. * * @param file * The file to read. * * @return Create a byte array with the files content. * * @throws IOException */ public static byte[] toBytes(File file) throws IOException { InputStream is = null; try { is = new FileInputStream(file); return StreamTools.toByteArray(is); } finally { if (is != null) { is.close(); } } } /** * Read a file's content at once and return as a string. * *

* Use with care! *

* * @param file * The file to read. * * @return The string content of the file. * * @throws IOException */ public static String toString(File file) throws IOException { return toString(file, System.getProperty("file.encoding")); } /** * Read a file's content at once and return as a string in the correct * encoding. * *

* Use with care! *

* * @param file * The file to read. * @param encoding * The encoding to use. * * @return The string content of the file. * * @throws IOException */ public static String toString(File file, String encoding) throws IOException { InputStream is = null; try { is = new FileInputStream(file); return StreamTools.toString(is, encoding); } finally { if (is != null) { is.close(); } } } /** * Replaces all characters that are generally not allowed or considered * useful in filenames with underscore. * * @param param * java.lang.String * * @return java.lang.String */ public static String trimPath(String param) { if (param == null) { return null; } String tmp = param.trim(); // uniform use of slash and backslash String drivePrefix = StringTools.EMPTY; // save drive if ((tmp.length() >= 2) && (tmp.charAt(1) == ':')) { drivePrefix = tmp.substring(0, 2); tmp = tmp.substring(2); } tmp = tmp.replaceAll("[\\*\"\\?\\<\\>\\|\\:!\\n\\t\\r\\f]", "_"); return drivePrefix + tmp; } protected static void unlock(Lock lock) { synchronized (maps) { maps.remove(lock.file); lock.valid = false; StreamTools.close(lock.lockStream); lock.lockFile.delete(); } } /** * Wait for a file to arrive. * *

* The method waits at most timeout milliseconds for a file to * arrive. When delay is != 0 the method checks the file's size * for changes it reaches a stable size. *

* * @param file * The file to wait for. * @param timeout * The maximum time in milliseconds to wait for first occurence * of file. * @param delay * The number of milliseconds between two checks against the * files size. * * @throws IOException */ public static void wait(File file, long timeout, long delay) throws IOException { // todo zero length files long stop = System.currentTimeMillis() + timeout; for (;;) { try { if (file.exists()) { if (delay > 0) { long oldSize = -1; long newSize = file.length(); for (;;) { if (oldSize != newSize) { oldSize = newSize; Thread.sleep(delay); newSize = file.length(); continue; } break; } } return; } if (System.currentTimeMillis() > stop) { // timeout throw new IOException("timeout waiting for " + file.getPath()); } Thread.sleep(1000); } catch (InterruptedException e) { // interrupted throw new IOException("interrupted waiting for " + file.getPath()); } } } /** * Create a file from the byte content. * * @param file * The file to write/create * @param bytes * The data to be written into the file. * * @throws IOException */ public static void write(File file, byte[] bytes) throws IOException { FileOutputStream os = new FileOutputStream(file); try { // write stream all at once os.write(bytes); } finally { StreamTools.close(os); } } /** * Create a file from the string content. * * @param file * The file to write/create * @param text * The text to be written into the file. * * @throws IOException */ public static void write(File file, String text) throws IOException { write(file, text, Charset.defaultCharset().name(), false); } /** * Create a file from the string content. * * @param file * The file to write/create * @param text * The text to be written into the file. * @param append * Flag to append to an existing file or create a new file. * * @throws IOException */ public static void write(File file, String text, boolean append) throws IOException { write(file, text, Charset.defaultCharset().name(), append); } /** * Create a file from the string content. * * @param file * The file to write/create * @param text * The text to be written into the file. * * @throws IOException */ public static void write(File file, String text, String encoding) throws IOException { write(file, text, encoding, false); } /** * Create a file from the string content / append a string to a file * * @param file * The file to write/create * @param text * The text to be written into the file. * @param append * Flag to append to an existing file or create a new file. * * @throws IOException */ public static void write(File file, String text, String encoding, boolean append) throws IOException { OutputStream os = null; Writer writer = null; try { os = new FileOutputStream(file, append); writer = new OutputStreamWriter(os, encoding); writer.write(text); } finally { StreamTools.close(writer); StreamTools.close(os); } } private FileTools() { // } } libisrt-java-4.8.20100629/src/de/intarsys/tools/file/SynchTools.java0000644000175000017500000000351511204240630024672 0ustar twernertwernerpackage de.intarsys.tools.file; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; /** * Tool methods to implement a file based synchronization with other platform * processes. *

* This is especially useful for synchronizing in shell scripting integration * scenarios, in conjunction with some commandline based access to this methods. */ public class SynchTools { private static byte[] bytes; static public void delSynchFile(File file) throws IOException { file.delete(); } public static byte[] getBytes() { return bytes; } static public File getSynchFile() throws IOException { return File.createTempFile("synchfile", ".synch"); } public static void setBytes(byte[] bytes) { SynchTools.bytes = bytes; } static public void setSynchFile(File file) throws IOException { setSynchFile(file, getBytes()); bytes = null; } static public void setSynchFile(File file, byte[] bytes) throws IOException { FileOutputStream os = new FileOutputStream(file); if (bytes != null) { os.write(bytes); } os.close(); } static public void setSynchFile(File file, String value) throws IOException { FileWriter w = new FileWriter(file); w.write(value); w.close(); } static public void waitSynchFile(File file, int timeout) throws IOException { long start = System.currentTimeMillis(); long count = 0; while (count < timeout && !file.exists()) { try { Thread.sleep(100); } catch (InterruptedException e) { throw new IOException("waiting for synch file '" + file.getPath() + "' interrupted"); } count = System.currentTimeMillis() - start; } if (!file.exists()) { throw new IOException("timeout waiing for synch file '" + file.getPath() + "'"); } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/file/Loader.java0000644000175000017500000001160410751651500024001 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.file; import java.io.File; import java.io.IOException; import de.intarsys.tools.string.StringTools; /** * A utility class to simplify the task of loading files and / or directories. * */ abstract public class Loader { public static final String PATH_SEPARATOR = "/"; //$NON-NLS-1$ public static final String DEFAULT_LANGUAGE = "en"; //$NON-NLS-1$ protected static final String PROP_USERLANGUAGE = "user.language"; //$NON-NLS-1$ public Loader() { } abstract protected boolean basicLoadFile(File file, boolean readOnly, String path) throws IOException; public boolean load(File file, boolean readOnly, boolean recursive) throws IOException { if (file == null || !file.exists()) { return false; } return basicLoad(file, readOnly, recursive, StringTools.EMPTY); } protected boolean basicLoad(File file, boolean readOnly, boolean recursive, String path) throws IOException { if (file.isDirectory()) { return basicLoadDirectory(file, readOnly, recursive, path); } else { return basicLoadFile(file, readOnly, path); } } protected boolean basicLoadDirectory(File file, boolean readOnly, boolean recursive, String path) throws IOException { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { File childFile = files[i]; if (recursive) { String newPath = path; if (childFile.isDirectory()) { newPath = path + childFile.getName() + PATH_SEPARATOR; } basicLoad(childFile, readOnly, recursive, newPath); } else { if (childFile.isFile()) { basicLoadFile(childFile, readOnly, path); } } } return true; } public boolean load(File parent, String filename, boolean readOnly, boolean recursive) throws IOException { if (filename == null) { return false; } File file = new File(filename); if (!file.isAbsolute()) { file = new File(parent, filename); } return load(file, readOnly, recursive); } public boolean loadNLS(File file, boolean readOnly, boolean recursive) throws IOException { if (file == null || !file.exists()) { return false; } if (file.isDirectory()) { String language = System.getProperty(PROP_USERLANGUAGE); File languageDir = new File(file, language); if (load(languageDir, readOnly, recursive)) { return true; } File defaultDir = new File(file, DEFAULT_LANGUAGE); return load(defaultDir, readOnly, recursive); } else { File parent = file.getParentFile(); if (parent == null) { return false; } String basename = FileTools.getBaseName(file); String extension = FileTools.getExtension(file); String language = System.getProperty(PROP_USERLANGUAGE); File languageFile = new File(parent, basename + "_" + language //$NON-NLS-1$ + "." + extension); //$NON-NLS-1$ if (file.exists() && basicLoadFile(languageFile, readOnly, StringTools.EMPTY)) { return true; } return basicLoadFile(file, readOnly, StringTools.EMPTY); } } public boolean loadNLS(File parent, String filename, boolean readOnly, boolean recursive) throws IOException { if (filename == null) { return false; } File file = new File(filename); if (!file.isAbsolute()) { file = new File(parent, filename); } return loadNLS(file, readOnly, recursive); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/file/AttachmentTools.java0000644000175000017500000002136111412330250025674 0ustar twernertwernerpackage de.intarsys.tools.file; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import de.intarsys.tools.locator.FileLocator; import de.intarsys.tools.locator.ILocator; import de.intarsys.tools.locator.ILocatorSupport; import de.intarsys.tools.logging.LogTools; import de.intarsys.tools.stream.StreamTools; import de.intarsys.tools.string.StringTools; /** * Utility methods to handle attachment relationships between files. * */ public class AttachmentTools { private final static Logger Log = LogTools.getLogger(FileTools.class); protected static String createAttachmentName(String masterName, String movedName, String attachName) { String prefix = StringTools.getCommonPrefix(masterName, attachName, true); int masterSuffixLength = masterName.length() - prefix.length(); int attachSuffixLength = attachName.length() - prefix.length(); // set newName to movedName String newName = movedName; // remove master suffix from newName newName = newName.substring(0, newName.length() - masterSuffixLength); // add attachment suffix to newName newName = newName + attachName .substring(attachName.length() - attachSuffixLength); return newName; } /** * Create a list of {@link File} instances selected from the array of * candidates that are recognized as attachments to file. *

* The attachments are selected using a ";" separated list of suffixes * (including the "."). *

* A file is accepted as an attachment if it has an attachment suffix and * the file base name is either the same as the target filename or target * file base name.
* * foo.bar * foo.bar.suffix (accepted) * foo.suffix (accepted) * foo.txt (rejected) * *

* All checks are case insensitive. * * @param master * @param files * @param extensions * @return a list of {@link File} instances selected from the array of * candidates that are recognized as attachments to * file. */ public static List createAttachments(File master, File[] files, String extensions) { if (StringTools.isEmpty(extensions)) { return Collections.EMPTY_LIST; } String targetName = null; String targetBaseName = null; if (master != null) { targetName = master.getName().toLowerCase(); targetBaseName = FileTools.getBaseName(targetName); } List result = new ArrayList(); String[] tempExtensions = extensions.toLowerCase().split(";"); for (int j = 0; j < files.length; j++) { File checkFile = files[j]; String tempName = checkFile.getName().toLowerCase(); if (tempName.equals(targetName)) { // this is target itself... continue; } String tempBaseName = FileTools.getBaseName(tempName); if (master == null || tempBaseName.equals(targetName) || tempBaseName.equals(targetBaseName)) { for (int i = 0; i < tempExtensions.length; i++) { if (tempName.endsWith(tempExtensions[i])) { result.add(checkFile); break; } } } } return result; } /** * Find all attachments to master. Attachments are defined to * be all files in the same directory as master that satisfy * one of the extensions. * * @param master * @param extensions * @return all attachments to master */ public static List createAttachments(File master, String extensions) { File tempDir; File tempFile; if (master.isDirectory()) { tempDir = master; tempFile = null; } else { tempDir = master.getParentFile(); tempFile = master; } if (tempDir == null) { return null; } File[] files = tempDir.listFiles(); return createAttachments(tempFile, files, extensions); } public static void deleteAttachments(List attachments) { for (Iterator it = attachments.iterator(); it.hasNext();) { Object attachment = it.next(); if (attachment instanceof File) { if (((File) attachment).exists() && !((File) attachment).delete()) { Log.log(Level.WARNING, "deleting '" //$NON-NLS-1$ + attachment + "' failed"); //$NON-NLS-1$ } } else if (attachment instanceof ILocator) { if (((ILocator) attachment).exists()) { try { ((ILocator) attachment).delete(); } catch (IOException e) { Log.log(Level.WARNING, "deleting '" //$NON-NLS-1$ + attachment + "' failed"); //$NON-NLS-1$ } } } else if (attachment instanceof ILocatorSupport) { ILocator tempLocator = ((ILocatorSupport) attachment) .getLocator(); if (tempLocator.exists()) { try { tempLocator.delete(); } catch (IOException e) { Log.log(Level.WARNING, "deleting '" //$NON-NLS-1$ + tempLocator + "' failed"); //$NON-NLS-1$ } } } else { // todo } } } static public File moveAttachment(File master, File attachment, File movedFile, boolean delete) { if (movedFile == null || attachment == null) { return null; } String masterName = master.getName(); String movedName = movedFile.getName(); File movedDir; if (movedFile.isDirectory()) { movedDir = movedFile; } else { movedDir = movedFile.getParentFile(); } try { File movedAttachment = moveAttachment(masterName, attachment, movedName, movedDir, delete); return movedAttachment; } catch (Exception e) { Log.log(Level.WARNING, "failed to move attachment '" + attachment + "' attached to '" + master + "'"); return attachment; } } static protected File moveAttachment(String masterName, Object attachment, String movedName, File dir, boolean delete) throws IOException { if (attachment instanceof FileLocator) { // avoid streaming attachment = ((FileLocator) attachment).getFile(); } if (attachment instanceof File) { File tempFile = (File) attachment; String tempName = tempFile.getName(); String newName = createAttachmentName(masterName, movedName, tempName); File newAttachment = new File(dir, newName); if (delete) { if (Log.isLoggable(Level.FINE)) { Log.log(Level.FINE, "move '" + tempFile.getAbsolutePath() + "' to '" + newAttachment.getAbsolutePath() + "'"); } FileTools.renameFile(tempFile, newAttachment); } else { if (Log.isLoggable(Level.FINE)) { Log.log(Level.FINE, "copy '" + tempFile.getAbsolutePath() + "' to '" + newAttachment.getAbsolutePath() + "'"); } FileTools.copyFile(tempFile, newAttachment); } return newAttachment; } else if (attachment instanceof ILocator) { ILocator tempLocator = (ILocator) attachment; String tempName = tempLocator.getTypedName(); String newName = createAttachmentName(masterName, movedName, tempName); File newAttachment = new File(dir, newName); if (Log.isLoggable(Level.FINE)) { Log.log(Level.FINE, "create file '" + newAttachment.getAbsolutePath() + "'"); } InputStream source = null; OutputStream destination = null; try { source = tempLocator.getInputStream(); destination = new FileOutputStream(newAttachment); StreamTools.copyStream(source, destination); } finally { StreamTools.close(source); StreamTools.close(destination); } if (delete) { if (Log.isLoggable(Level.FINE)) { Log.log(Level.FINE, "delete locator '" + tempLocator.getFullName() + "'"); } tempLocator.delete(); } return newAttachment; } else { // todo log warning return null; } } static public List moveAttachments(File master, List attachments, File movedFile, boolean delete) { if (master == null || movedFile == null || attachments == null || attachments.isEmpty()) { return attachments; } List result = new ArrayList(); String masterName = master.getName(); String movedName = movedFile.getName(); File movedDir; if (movedFile.isDirectory()) { movedDir = movedFile; } else { movedDir = movedFile.getParentFile(); } for (Iterator it = attachments.iterator(); it.hasNext();) { Object tempAttachment = it.next(); try { File movedAttachment = moveAttachment(masterName, tempAttachment, movedName, movedDir, delete); result.add(movedAttachment); } catch (Exception e) { result.add(tempAttachment); Log.log(Level.WARNING, "failed to move attachment '" + tempAttachment + "' attached to '" + master + "'"); } } return result; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/file/ArchiveTools.java0000644000175000017500000002547211253703436025211 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of intarsys 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 de.intarsys.tools.file; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.NumberFormat; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import de.intarsys.tools.stream.StreamTools; public class ArchiveTools { /** * A utility to manage archiving files in a directory. * */ static class DumpDirectory { public static DumpDirectory get(File file) { return get(file.getAbsolutePath()); } public static synchronized DumpDirectory get(String name) { DumpDirectory dd = (DumpDirectory) dumpDirs.get(name); if (dd == null) { dd = new DumpDirectory(new File(name)); // just for locking; dd.prepare(); dumpDirs.put(name, dd); } return dd; } File dir; int currentCount; int dirCount; long lastDump = System.currentTimeMillis(); protected DumpDirectory(File dir) { super(); setDir(dir); } protected void checkDir() throws IOException { // check and create directory if (!getDir().exists()) { if (!getDir().mkdirs()) { throw new IOException(" can't create temporary directory " + getDir()); } } } protected void checkFiles(int max) throws IOException { // todo execute check in low priority daemon // // clean up archive directory, delete oldest files if more than // count // available // files must be stored with dump archive to guarantee that preifx // sorts // correctly // this implementation relies on the fact, that only the receiver // object // manipulates files in the directory if ((max <= 0) || (currentCount <= max)) { return; } String[] fileNames = dir.list(); if (fileNames == null) { throw new IOException("can not list directory " + dir.getAbsolutePath()); } if (fileNames.length != (dirCount + currentCount)) { prepare(fileNames); } Arrays.sort(fileNames); int delete = Math.min(fileNames.length, currentCount - max); for (int i = 0; i < delete; i++) { File deleteFile = new File(dir, fileNames[i]); if (deleteFile.isFile()) { if (!deleteFile.delete()) { throw new IOException("can not delete file " + deleteFile.getAbsolutePath()); } currentCount--; } } } public java.io.File getDir() { return dir; } public synchronized File getDumpFile(String name, int max) throws IOException { File newFile = new File(getDir(), getUniquePrefix() + "." + name); // check directory every time, maybe deleted by some nerd... checkDir(); if (!newFile.createNewFile()) { throw new IOException("can not create file " + newFile.getAbsolutePath()); } currentCount++; try { checkFiles(max); } catch (IOException e) { // ignore if we can not hold the correct level in dump directory } return newFile; } public long getLastDump() { return lastDump; } protected long getUniqueMillis() { // ensure unique counter values, millisecondsbased long current = System.currentTimeMillis(); while (getLastDump() >= current) { current++; } setLastDump(current); return current; } protected String getUniquePrefix() { return theFormat.format(getUniqueMillis()); } protected void prepare() { String[] fileNames = dir.list(); if (fileNames == null) { // error, ignore return; } prepare(fileNames); } protected void prepare(String[] fileNames) { currentCount = 0; dirCount = 0; if (fileNames != null) { for (int i = 0; i < fileNames.length; i++) { File f = new File(dir, fileNames[i]); if (f.isFile()) { currentCount++; } else { dirCount++; } } } } private void setDir(java.io.File newDir) { dir = newDir; } private void setLastDump(long newLastDump) { lastDump = newLastDump; } } // private static Map dumpDirs = new HashMap(); // the number format used for archiving private static final NumberFormat theFormat; static { theFormat = NumberFormat.getNumberInstance(); theFormat.setMaximumFractionDigits(0); theFormat.setMinimumIntegerDigits(19); theFormat.setGroupingUsed(false); } /** * Archive a files content. * *

* The method creates a copy in the archive directory with a unique name * that is guaranteed to create a sortable representation so that newer * files have a "greater" filename. Creation of file names is thread safe. * If more than max files are in the archive directory, the * oldest files are deleted. max = 0 means never create archive, max = -1 * means always create archive. If deleteSource is * true, the file to be archived is deleted after the archive * was created. *

* * @param root * The root for relative addressing. * @param relativePath * The path relative to root where to create the archive. * @param file * The file to archive. * @param max * The maximum number of archive files allowed.han * @param sourceEncoding * The encoding of the file to be archived. * @param destinationEncoding * The encoding of the archived file. * @param deleteSource * Flag if source should be deleted. * @param forceArchive * Flag if we should archive even if file is already in the * archive directory. * @return The name of the archived file, or null. * * @throws IOException */ public static String archive(File root, String relativePath, File file, int max, String sourceEncoding, String destinationEncoding, boolean deleteSource, boolean forceArchive) throws IOException { if ((max == 0) || (root == null)) { // no archiving desired return null; } String dirName = FileTools.resolvePath(root, relativePath) .getAbsolutePath(); File archive; if (!forceArchive && dirName.equals(file.getParentFile().getAbsolutePath())) { // i'm already in the temp directory, no need to copy archive = file; } else { DumpDirectory d = DumpDirectory.get(dirName); archive = d.getDumpFile(file.getName(), max); if (deleteSource) { FileTools.renameFile(file, sourceEncoding, archive, destinationEncoding); } else { FileTools.copyFile(file, sourceEncoding, archive, destinationEncoding); } } try { archive.setLastModified(System.currentTimeMillis()); } catch (Exception ignore) { // getLog().logWarning(getLogPrefix() + " could not set // modification // time for file " + renamedFile.getPath()); } return archive.getAbsolutePath(); } /** * Create a archive file and dump the input stream to this file. Calls * createArchive, and then copies the is to the output stream. * * @param root * The root for relative addressing. * @param relativePath * The path relative to root where to create the archive. * @param filename * The file to archive. * @param max * The maximum number of archive files allowed.han * @param is * The input stream to be dumped. * @return The name of the archived file, or null. * * @throws IOException */ public static String archive(File root, String relativePath, String filename, InputStream is, int max) throws IOException { if ((max == 0) || (root == null)) { // no archiving desired return null; } File archive = createArchive(root, relativePath, filename, max); FileOutputStream os = new FileOutputStream(archive); try { StreamTools.copyStream(is, os); } catch (Exception e) { throw new IOException("archiving failed (" + e.getMessage() + ")"); } finally { try { if (os != null) { os.close(); } } catch (Exception ignore) { // ignore failure } } return archive.getAbsolutePath(); } /** * Just creates a archive file, nothing will be dumped inside this file. * * @param root * The root for relative addressing. * @param relativePath * The path relative to root where to create the archive. * @param filename * The file to archive. * @param max * The maximum number of archive files allowed.han * * @return The name of the archived file, or null. * * @throws IOException */ public static File createArchive(File root, String relativePath, String filename, int max) throws IOException { if ((max == 0) || (root == null)) { // no archiving desired return null; } String dirName = FileTools.resolvePath(root, relativePath) .getAbsolutePath(); DumpDirectory d = DumpDirectory.get(dirName); File archive = d.getDumpFile(filename, max); return archive; } public static OutputStream createOutputStream(File root, String filename, int max) throws IOException { if ((max == 0) || (root == null)) { // no archiving desired return null; } DumpDirectory d = DumpDirectory.get(root); File archive = d.getDumpFile(filename, max); return new FileOutputStream(archive); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/file/TempTools.java0000644000175000017500000001053311201021562024507 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.file; import java.io.File; import java.io.FileFilter; /** * Tools for dealing with temporary files and directories. *

* This class provides a locked, VM unique temp directory. Upon startup, * unlocked directories are removed. */ public class TempTools { private static File tempDir; private static File tempDirVM; private static FileTools.Lock lock; private static int fileCounter = 0; private static int dirCounter = 0; static { cleanUp(); } /** * Clean up temporary directories. */ protected static void cleanUp() { File[] files = getTempDir().listFiles(new FileFilter() { public boolean accept(File file) { if (file.isDirectory() && file.getName().startsWith(TempTools.class.getName())) { return true; } return false; } }); if (files == null) { return; } for (int i = 0; i < files.length; i++) { cleanUpTempDir(files[i]); } } /** * Clean up a single temporary directory * * @param file */ protected static void cleanUpTempDir(File file) { FileTools.Lock tempLock = FileTools.lock(file); if (tempLock == null) { return; } tempLock.release(); // orphaned directory, try to clean up FileTools.deleteRecursivly(file); } synchronized public static File createTempDir(String prefix, String suffix) { // resource local to unique VM temp directory // - don't need to check for name String tempName = prefix + dirCounter++ + suffix; File tempFile = new File(TempTools.getTempDirVM(), tempName); tempFile.mkdirs(); return tempFile; } /** * Create the root directory for all temp files * * @param parent * @return */ protected static File createTempDirVM(File parent) { String name = TempTools.class.getName(); File tempFile = new File(parent, name); int counter = 0; while (true) { tempFile = new File(parent, name + "_" + counter); if (!tempFile.exists() && tempFile.mkdirs()) { lock = FileTools.lock(tempFile); if (lock != null) { break; } } counter++; } return tempFile; } synchronized public static File createTempFile(String prefix, String suffix) { // resource local to unique VM temp directory // - don't need to check for name String tempName = prefix + fileCounter++ + suffix; File tempFile = new File(TempTools.getTempDirVM(), tempName); return tempFile; } public static File getTempDir() { if (tempDir == null) { tempDir = new File(System.getProperty("java.io.tmpdir")); } return tempDir; } public static File getTempDirVM() { if (tempDirVM == null) { tempDirVM = createTempDirVM(getTempDir()); } return tempDirVM; } public static void setTempDir(File pTempDir) { tempDir = pTempDir; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/file/MagicFileNumberTest.java0000644000175000017500000002111511027514760026425 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.file; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import de.intarsys.tools.hex.HexTools; import de.intarsys.tools.randomaccess.IRandomAccess; import de.intarsys.tools.randomaccess.RandomAccessByteArray; import de.intarsys.tools.stream.StreamTools; public class MagicFileNumberTest { public static class Type { private String suffix; private byte[] magicBytes; public Type(String suffix, byte[] magic) { this.suffix = suffix; this.magicBytes = magic; } public String getKey() { return HexTools.bytesToHexString(magicBytes); } public byte[] getMagicBytes() { return magicBytes; } public String getSuffix() { return suffix; } public boolean matches(IRandomAccess data) throws IOException { data.reset(); for (int i = 0; i < magicBytes.length; i++) { if (magicBytes[i] != data.read()) { return false; } } return true; } @Override public String toString() { return suffix; } } static private Map types; static { types = new HashMap(); addTypes(); } /** * @param fileSuffix * just the suffix without any starting suffix delimiters (e.g.: * 'pdf') * @param magicBytes * any bytes, not null or zero size */ static public void addType(String fileSuffix, byte[] magicBytes) { if ((fileSuffix == null) || (magicBytes == null) || (magicBytes.length == 0)) { return; } Type type = new Type(fileSuffix, magicBytes); if (!types.containsKey(type.getKey())) { types.put(type.getKey(), type); } } static protected void addTypes() { /* * known types, found on * http://www.astro.keele.ac.uk/oldusers/rno/Computing/File_magic.html */ /* image files */ /* Bitmap format */ addType("bmp", new byte[] { 0x42, 0x4d }); //$NON-NLS-1$ /* FITS format */ addType("fits", new byte[] { 0x53, 0x49, 0x4d, 0x50, 0x4c, 0x45 }); //$NON-NLS-1$ /* GIF format */ addType("gif", new byte[] { 0x47, 0x49, 0x46, 0x38 }); //$NON-NLS-1$ /* Graphics Kernel System */ addType("gks", new byte[] { 0x47, 0x4b, 0x53, 0x4d }); //$NON-NLS-1$ /* IRIS rgb format */ addType("rgb", new byte[] { 0x01, (byte) 0xda }); //$NON-NLS-1$ /* ITC (CMU WM) format */ addType("itc", new byte[] { (byte) 0xf1, 0x00, 0x40, (byte) 0xbb }); //$NON-NLS-1$ /* JPEG File Interchange Format */ addType("jpg", new byte[] { (byte) 0xff, (byte) 0xD8, (byte) 0xff }); //$NON-NLS-1$ /* NIFF (Navy TIFF) */ addType("nif", new byte[] { 0x49, 0x49, 0x4e, 0x31 }); //$NON-NLS-1$ /* PM format */ addType("pm", new byte[] { 0x56, 0x49, 0x45, 0x57 }); //$NON-NLS-1$ /* PNG format */ addType("png", new byte[] { (byte) 0x89, 0x50, 0x4e, 0x47 }); //$NON-NLS-1$ /* Postscript format */ addType("ps", new byte[] { 0x25, 0x21 }); //$NON-NLS-1$ /* Sun Rasterfile */ addType("ras", new byte[] { 0x59, (byte) 0xa6, 0x6a, (byte) 0x95 }); //$NON-NLS-1$ /* TIFF format (Motorola - big endian) */ addType("tif", new byte[] { 0x4d, 0x4d, 0x00, 0x2a }); //$NON-NLS-1$ /* TIFF format (Intel - little endian) */ addType("tif", new byte[] { 0x49, 0x49, 0x2a, 0x00 }); //$NON-NLS-1$ /* XCF Gimp file structure */ addType("xcf", new byte[] { 0x67, 0x69, 0x6d, 0x70, 0x20, 0x78, 0x63, //$NON-NLS-1$ 0x66, 0x20, 0x76 }); /* Xfig format */ addType("fig", new byte[] { 0x23, 0x46, 0x49, 0x47 }); //$NON-NLS-1$ /* XPM format */ addType("xpm", new byte[] { 0x2f, 0x2a, 0x20, 0x58, 0x50, 0x4d, 0x20, //$NON-NLS-1$ 0x2a, 0x2f }); /* compressed files */ /* Bzip */ addType("bz", new byte[] { 0x42, 0x5a }); //$NON-NLS-1$ /* Compress */ addType("Z", new byte[] { 0x1f, (byte) 0x9d }); //$NON-NLS-1$ /* gzip format */ addType("gz", new byte[] { 0x1f, (byte) 0x8b }); //$NON-NLS-1$ /* pkzip format */ addType("zip", new byte[] { 0x50, 0x4b, 0x03, 0x04 }); //$NON-NLS-1$ /* archive files */ /* TAR */ addType("tar", new byte[] { 0x75, 0x73, 0x74, 0x61, 0x72 }); //$NON-NLS-1$ /* excecutable files */ /* MS-DOS, OS/2 or MS Windows */ addType("exe", new byte[] { 0x4d, 0x5a }); //$NON-NLS-1$ /* Unix elf */ addType("unix elf", new byte[] { 0x7f, 0x45, 0x4c, 0x46 }); //$NON-NLS-1$ /* pgp */ /* pgp public ring */ addType("pgp public ring", new byte[] { (byte) 0x99, 0x00 }); //$NON-NLS-1$ /* pgp security ring */ addType("pgp security ring", new byte[] { (byte) 0x95, 0x01 }); //$NON-NLS-1$ /* pgp security ring */ addType("pgp security ring", new byte[] { (byte) 0x95, 0x00 }); //$NON-NLS-1$ /* pgp encrypted data */ addType("pgp encrypted data", new byte[] { (byte) 0xA6, 0x00 }); //$NON-NLS-1$ /* other */ try { addType("pdf", "%PDF".getBytes("ASCII")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } catch (UnsupportedEncodingException e) { // will not happen } } /** * @param data * any not null or zero size data * @return a file suffix without a delimiter (e.g.: 'pdf') or * null */ static public String guessFileSuffix(byte[] data) { if (data == null) { return null; } IRandomAccess ra = null; try { ra = new RandomAccessByteArray(data); return guessFileSuffix(ra); } catch (IOException e) { // should not occur throw new RuntimeException(e); } finally { StreamTools.close(ra); } } /** * @param data * any not null or zero size data * @return a file suffix without a delimiter (e.g.: 'pdf') or * null */ static public String guessFileSuffix(IRandomAccess data) throws IOException { for (Iterator i = types.entrySet().iterator(); i.hasNext();) { Type type = (Type) ((Map.Entry) i.next()).getValue(); if (type.matches(data)) { return type.getSuffix(); } } return null; } /** * does the data contain only ISO-8819-x printable characters ? */ static public boolean isText(byte[] data) { IRandomAccess ra = null; try { ra = new RandomAccessByteArray(data); return isText(ra); } catch (IOException e) { // should not occur throw new RuntimeException(e); } finally { StreamTools.close(ra); } } /** * does the data contain only ISO-8819-x printable characters ? */ static public boolean isText(IRandomAccess data) throws IOException { if (data == null) { return false; } data.reset(); for (int i = 0, c = data.read(); c != -1 && i < 1024; c = data.read(), i++) { c = c & 0xFF; if (c >= 0x20 && c <= 0x7E) { // ASCII printable continue; } if (c >= 0xA0) { // ISO 8819 extension continue; } switch (c) { case 0x09: // HORIZONTAL TABULATION case 0x0A: // LINE FEED case 0x0B: // VERTICAL TABULATION case 0x0C: // FORM FEED case 0x0D: // CARRIAGE RETURN continue; default: } return false; } return true; } private MagicFileNumberTest() { } } libisrt-java-4.8.20100629/src/de/intarsys/tools/string/0000755000175000017500000000000011412336332022313 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/string/StringTools.java0000644000175000017500000005317411412330332025451 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.string; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import de.intarsys.tools.file.FileTools; /** * A tool class for the handling of strings. * */ public class StringTools { public static final String CR = "\r"; //$NON-NLS-1$ public static final String CRLF = "\r\n"; //$NON-NLS-1$ public static final String DATEFORMAT_SIMPLE = "yy-MM-dd HH:mm:ss:SSSS"; //$NON-NLS-1$ private static DateFormat DEFAULT_DATEFORMAT; /** An empty string constant */ public static final String EMPTY = ""; //$NON-NLS-1$ public static final String FORMAT_D = "d"; //$NON-NLS-1$ public static final String FORMAT_F = "f"; //$NON-NLS-1$ public static final String FORMAT_I = "i"; //$NON-NLS-1$ public static final String FORMAT_P = "p"; //$NON-NLS-1$ public static final String FORMAT_S = "s"; //$NON-NLS-1$ public static final String LF = "\n"; //$NON-NLS-1$ private static final String[] NO_ARGS = new String[0]; /** An single space constant */ public static final String SPACE = " "; //$NON-NLS-1$ public static String breakForced(String value, int max, String breakPattern) { StringBuilder sb = new StringBuilder(); if (value != null) { int begin = 0; int end = max; int length = value.length(); int currentlength = length; while (currentlength > max) { sb.append(value.substring(begin, end)); currentlength -= max; begin += max; end += max; if (currentlength > 0) { sb.append(breakPattern); } } if (end > length) { end = length; } sb.append(value.substring(begin, end)); } return sb.toString(); } /** * Capitalizes the first letter of the text. * * @param text * @return a capitalized version of the text */ public static String capitalize(String text) { if (isEmpty(text)) { return EMPTY; } String first = text.substring(0, 1); first = first.toUpperCase(); if (text.length() > 1) { return first + text.substring(1); } else { return first; } } /** * clear character array content. * * @param value * The value to be cleared */ static public void clear(char[] value) { if (value == null) { return; } Arrays.fill(value, '0'); } /** * Create a string representation and format value according to * the instructions in format. *

* If value is null, the empty string is returned. *

*/ public static String format(Object value, String format) { if (value == null) { return EMPTY; } if (format.startsWith(FORMAT_S)) { return formatString(value, format.substring(1)); } if (format.startsWith(FORMAT_F)) { return formatFloat(value, format.substring(1)); } if (format.startsWith(FORMAT_I)) { return formatInteger(value, format.substring(1)); } if (format.startsWith(FORMAT_D)) { return formatDate(value, format.substring(1)); } if (format.startsWith(FORMAT_P)) { return formatPath(value, format.substring(1)); } // the default formattings if (value instanceof Date) { return new SimpleDateFormat(DATEFORMAT_SIMPLE).format(value); } if (value instanceof Long) { return Long.toString(((Long) value).longValue(), 32); } return value.toString(); } /** */ protected static String formatDate(Object value, String format) { Date date = null; if (value instanceof Date) { date = (Date) value; } else if (value instanceof Number) { date = new Date(((Number) value).longValue()); } else if (value instanceof String) { return (String) value; } else { return EMPTY; } if (StringTools.isEmpty(format)) { return formatDateDefault(date); } String pattern = parseArgsString(format); if (pattern == null) { char dateTime = '+'; char command = format.charAt(0); if ((command == 'd') || (command == 't')) { // date or time only dateTime = command; if (format.length() > 1) { command = format.charAt(1); } else { command = 'f'; } } if (dateTime == 'd') { if (command == 's') { DateFormat dateFormat = DateFormat .getDateInstance(DateFormat.SHORT); return dateFormat.format(date); } else if (command == 'm') { DateFormat dateFormat = DateFormat .getDateInstance(DateFormat.MEDIUM); return dateFormat.format(date); } else if (command == 'f') { DateFormat dateFormat = DateFormat .getDateInstance(DateFormat.FULL); return dateFormat.format(date); } } else if (dateTime == 't') { if (command == 's') { DateFormat dateFormat = DateFormat .getTimeInstance(DateFormat.SHORT); return dateFormat.format(date); } else if (command == 'm') { DateFormat dateFormat = DateFormat .getTimeInstance(DateFormat.MEDIUM); return dateFormat.format(date); } else if (command == 'f') { DateFormat dateFormat = DateFormat .getTimeInstance(DateFormat.FULL); return dateFormat.format(date); } } else { if (command == 's') { DateFormat dateFormat = DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.SHORT); return dateFormat.format(date); } else if (command == 'm') { DateFormat dateFormat = DateFormat.getDateTimeInstance( DateFormat.MEDIUM, DateFormat.MEDIUM); return dateFormat.format(date); } else if (command == 'f') { DateFormat dateFormat = DateFormat.getDateTimeInstance( DateFormat.FULL, DateFormat.FULL); return dateFormat.format(date); } } return formatDateDefault(date); } else { DateFormat tempFormat = new SimpleDateFormat(pattern); try { return tempFormat.format(date); } catch (Exception e) { return formatDateDefault(date); } } } /** * @param value */ protected static synchronized String formatDateDefault(Date date) { if (DEFAULT_DATEFORMAT == null) { DEFAULT_DATEFORMAT = new SimpleDateFormat("yyyy_MM_dd-HH_mm_ss_SSS"); //$NON-NLS-1$ } return DEFAULT_DATEFORMAT.format(date); } /** */ protected static String formatFloat(Object value, String format) { if (value == null) { return EMPTY; } double number = 0; if (value instanceof Number) { number = ((Number) value).doubleValue(); } else { if (value instanceof Date) { number = ((Date) value).getTime(); } else { if (value instanceof String) { try { number = Double.parseDouble((String) value); } catch (NumberFormatException e) { return (String) value; } } else { return value.toString(); } } } String pattern = parseArgsString(format); NumberFormat tempFormat = null; if (pattern == null) { tempFormat = NumberFormat.getNumberInstance(); } else { tempFormat = new DecimalFormat(pattern); } try { return tempFormat.format(number); } catch (Exception e) { return value.toString(); } } /** */ protected static String formatInteger(Object value, String format) { if (value == null) { return EMPTY; } char base = 'd'; if (format.length() > 1) { base = format.charAt(1); } long number = 0; if (value instanceof Number) { number = ((Number) value).longValue(); } else { if (value instanceof Date) { number = ((Date) value).getTime(); } else { if (value instanceof String) { try { number = Long.parseLong((String) value); } catch (NumberFormatException e) { return (String) value; } } else { return value.toString(); } } } try { if (base == 'b') { return Long.toString(number, 2); } if (base == 'o') { return Long.toString(number, 8); } if (base == 'd') { return Long.toString(number, 10); } if (base == 'x') { return Long.toString(number, 16); } return Long.toString(number, 10); } catch (Exception e) { return value.toString(); } } protected static String formatPath(Object value, String string) { return FileTools.trimPath(StringTools.safeString(value)); } protected static String formatString(Object value, String format) { String result = null; if (value == null) { result = EMPTY; } else { result = value.toString(); } String[] args = parseArgs(format); if (args.length == 0) { return result; } int rangeStart = 0; int rangeStop = result.length() - 1; try { rangeStart = Integer.parseInt(args[0]); if (args.length == 2) { rangeStop = Integer.parseInt(args[1]); } } catch (NumberFormatException e) { return result; } if (rangeStart < 0) { rangeStart = result.length() + rangeStart; } if (rangeStop < 0) { rangeStop = result.length() + rangeStop; } if (rangeStart < 0) { rangeStart = 0; } if (rangeStop < 0) { rangeStop = 0; } if (rangeStart > rangeStop) { rangeStop = rangeStart - 1; } if (rangeStart > result.length()) { rangeStart = result.length(); } if (rangeStop >= result.length()) { rangeStop = result.length() - 1; } return result.substring(rangeStart, rangeStop + 1); } public static String getCommonPrefix(String a, String b, boolean ignoreCase) { int lengthA = a.length(); int lengthB = b.length(); int max = lengthA > lengthB ? lengthB : lengthA; int i = 0; String tmpA; String tmpB; if (ignoreCase) { tmpA = a.toLowerCase(); tmpB = b.toLowerCase(); } else { tmpA = a; tmpB = b; } for (; i < max; i++) { if (tmpA.charAt(i) != tmpB.charAt(i)) { break; } } return a.substring(0, i); } /** * The first line of text (all characters up to the first occurence of * either "\n" or "\r". * * @param text * The text where the first line is looked up. * * @return The first line of text */ public static String getFirstLine(String text) { if (text == null) { return EMPTY; } int indexCR = text.indexOf(CR); if (indexCR == -1) { indexCR = text.length(); } int indexLF = text.indexOf(LF); if (indexLF == -1) { indexLF = text.length(); } return text.substring(0, (indexCR > indexLF) ? indexLF : indexCR); } public static String getLeading(String value, int count) { if (value == null || value.length() <= count || count <= 3) { return value; } return value.substring(0, count - 3) + "..."; } /** * The number of lines in text. This is 1 + the number of "\n" * in text. * * @param text * The text where the lines are counted. * @return The number of lines in text. This is 1 + the number * of "\n" in text. */ public static int getLineCount(String text) { int count = 1; char[] chars = text.toCharArray(); for (int i = 0; i < chars.length; i++) { if (chars[i] == '\n') { count++; } } return count; } public static String getTrailing(String value, int count) { if (value == null || value.length() <= count) { return value; } return "..." + value.substring(value.length() - count + 3, value.length()); } /** * true if value is "empty" in any respect. *

* This is the case when value == null, value has no characters or only * whitespace. * * @param value * The value to be inspected for emptyness. * @return true if value is "empty" in any * respect. */ static public boolean isEmpty(char[] value) { if ((value == null) || (value.length == 0)) { return true; } for (int i = 0; i < value.length; i++) { if (!Character.isWhitespace(value[i])) { return false; } } return true; } /** * true if value is "empty" in any respect. *

* This is the case when value == null, value has no characters or only * whitespace. * * @param value * The value to be inspected for emptyness. * @return true if value is "empty" in any * respect. */ static public boolean isEmpty(String value) { return (value == null) || (value.length() == 0) || (value.trim().length() == 0); } /** * true if value seems to be a numeric value. To * qualify only the first character is examined. value * qualifies as numeric if the first character is a digit, a "+", a "-" or a * ".". * * @param value * @return true if value seems to be numeric. */ public static boolean isNumeric(String value) { if (value == null || value.length() == 0) { return false; } char c = value.charAt(0); return Character.isDigit(c) || c == '-' || c == '+' || c == '.'; } /** * Joins a List of Strings to a single one. All elements are separated by * the separator. * * @param elements * List of Strings * @param separator * a String used as a separator between two elements, e.g. "\n" * for a new line. May be null. * @return the joined string */ public static String join(List elements, String separator) { return join(elements.toArray(new String[0]), separator); } /** * Joins an array of Strings to a single one. All elements are separated by * the separator. * * @param elements * array of Strings * @param separator * a String used as a separator between two elements, e.g. "\n" * for a new line. May be null. * @return the joined string */ public static String join(String[] elements, String separator) { int last = elements.length - 1; if (last == -1) { return EMPTY; } if (last == 0) { return elements[0]; } StringBuilder buffer = new StringBuilder(); for (int i = 0; i < last; i++) { buffer.append(elements[i]); if (separator != null) { buffer.append(separator); } } buffer.append(elements[last]); return buffer.toString(); } public static String padLeft(String value, int count) { if (value == null || value.length() >= count) { return value; } StringBuilder sb = new StringBuilder(); for (int i = count - value.length(); i > 0; i--) { sb.append(" "); } sb.append(value); return sb.toString(); } public static String padRight(String value, int count) { if (value == null || value.length() >= count) { return value; } StringBuilder sb = new StringBuilder(); sb.append(value); for (int i = count - value.length(); i > 0; i--) { sb.append(" "); } return sb.toString(); } protected static String[] parseArgs(String string) { String tempArgs = parseArgsString(string); if (tempArgs == null) { return NO_ARGS; } return tempArgs.split(","); } protected static String parseArgsString(String string) { int open = string.indexOf('('); int close = string.indexOf(')'); if ((open == -1) || (close == -1) || (open > close)) { return null; } return string.substring(open + 1, close); } /** * Parse a commandline string with the default escape character. * * @param line * The commandline string. * @return The array of string tokens in the commandline string. */ static public String[] parseCommandline(String line) { return parseCommandline(line, '\\'); } /** * Parse a commandline string. * * @param line * The commandline string. * @return The array of string tokens in the commandline string. */ static public String[] parseCommandline(String line, char escape) { List result = new ArrayList(); StringBuilder sb = new StringBuilder(); boolean escaped = false; boolean quoted = false; boolean commented = false; for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); if (commented) { if (c == '\n') { commented = false; } continue; } if (escaped) { escaped = false; if (c != '"') { sb.append(escape); } sb.append(c); continue; } if (c == escape) { escaped = true; continue; } if (c == '"') { quoted = !quoted; continue; } if (!quoted && (c == '#')) { if (sb.length() > 0) { result.add(sb.toString()); sb.setLength(0); } commented = true; continue; } if (!quoted && Character.isWhitespace(c)) { if (sb.length() > 0) { result.add(sb.toString()); sb.setLength(0); } continue; } sb.append(c); } if (escaped) { sb.append(escape); } if (sb.length() > 0) { result.add(sb.toString()); sb.setLength(0); } return (String[]) result.toArray(new String[result.size()]); } /** * Create a string representation of object that is guaranteed * not to fail in any case. * * @param object * The object to be printed. * @return Create a string representation of object that is * guaranteed not to fail in any case. */ public static String safeString(Object object) { try { return String.valueOf(object); } catch (RuntimeException e) { return ""; //$NON-NLS-1$ } } /** * Create a byte array from the string. This is simply a fast version of * getBytes, ignoring any encoding. *

* If you use this, you should be sure you will encounter valid ascii * characters only! * * @param value * @return A byte array created from value, ignoring high byte. */ static public byte[] toByteArray(String value) { byte[] result = new byte[value.length()]; value.getBytes(0, result.length, result, 0); return result; } /** * Create a string from the byte array. This is simply a fast version of new * String(), ignoring any encoding. *

* If you use this, you should be sure you will encounter valid ascii * characters only! * * @param value * @return A string created from the byte values in value. */ static public String toString(byte[] value) { return new String(value, 0); } /** * Create a string containing only the alphanumeric content of * value. * * @param value * The string to be trimmed. * @return A string containing only the alphanumeric content of * value. */ static public String trimAlphaNumeric(String value) { StringReader reader; StringWriter writer; char[] buffer; reader = new StringReader(value); buffer = new char[1]; writer = new StringWriter(); try { while (reader.read(buffer) != -1) { if (Character.isLetterOrDigit(buffer[0])) { writer.write(buffer); } } } catch (IOException ex) { // working in memory; ignore } return writer.toString(); } /** * Create a new string from value without leading whitespace. * * @param value * The string to be stripped. * * @return A copy of value with leading whitespace stripped. */ public static String trimLeft(String value) { int i = 0; int len = value.length(); while (i < len) { if (Character.isWhitespace(value.charAt(i))) { i++; continue; } break; } return value.substring(i); } /** * Create a new string from value without trailing whitespace. * * @param value * The string to be stripped. * * @return A copy of value with trailing whitespace stripped. */ public static String trimRight(String value) { int i = value.length() - 1; while (i >= 0) { if (Character.isWhitespace(value.charAt(i))) { i--; continue; } break; } return value.substring(0, i + 1); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/string/Converter.java0000644000175000017500000002451411411055574025140 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.string; import java.io.File; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; import de.intarsys.tools.file.FileTools; /** * Simple string conversion utilities; */ public class Converter { public static final String ELEMENT_SEPARATOR = ";"; //$NON-NLS-1$ public static final String KEY_VALUE_SEPARATOR = "="; //$NON-NLS-1$ public static boolean asBoolean(String booleanString) throws ConverterException { booleanString = booleanString.toLowerCase().trim(); if (booleanString.equals("false") || booleanString.equals("f") || booleanString.equals("no") || booleanString.equals("n") || booleanString.equals("0") || booleanString.equals("falsch") || booleanString.equals("nein")) { return false; } if (booleanString.equals("true") || booleanString.equals("t") || booleanString.equals("yes") || booleanString.equals("y") || booleanString.equals("1") || booleanString.equals("wahr") || booleanString.equals("w") || booleanString.equals("ja") || booleanString.equals("j")) { return true; } throw new ConverterException("Can't parse boolean string: " + booleanString + " to a legal value"); } public static boolean asBoolean(String booleanString, boolean defaultValue) { if (StringTools.isEmpty(booleanString)) { return defaultValue; } try { return asBoolean(booleanString); } catch (ConverterException e) { return defaultValue; } } public static boolean asBooleanChecked(String booleanString, boolean defaultValue) throws ConverterException { if (StringTools.isEmpty(booleanString)) { return defaultValue; } return asBoolean(booleanString); } public static Class asClass(String str) throws ConverterException { str = str.trim(); if (str.equals("")) { return null; } try { return Class.forName(str); } catch (ClassNotFoundException cnfe) { throw new ConverterException(str + " is not a possible Classname!"); } } public static double asDouble(String str) throws ConverterException { try { str = str.trim(); return Double.parseDouble(str); } catch (NumberFormatException e) { throw new ConverterException("Can't parse number string: " + str + " to a legal value"); } } public static double asDouble(String str, double defaultValue) { if (StringTools.isEmpty(str)) { return defaultValue; } try { return asDouble(str); } catch (ConverterException e) { return defaultValue; } } public static double asDoubleChecked(String str, double defaultValue) throws ConverterException { if (StringTools.isEmpty(str)) { return defaultValue; } return asDouble(str); } public static File asFile(String pValue) throws ConverterException { String str = pValue.trim(); str = FileTools.trimPath(str); if (str.equals("")) { throw new ConverterException("Parameter " + pValue + " is not a valid Filename"); } try { return new File(str); } catch (NullPointerException e) { throw new ConverterException("Can't parse file string: " + str + " to a file"); } } public static float asFloat(String str) throws ConverterException { try { str = str.trim(); return Float.parseFloat(str); } catch (NumberFormatException e) { throw new ConverterException("Can't parse number string: " + str + " to a legal value"); } } public static float asFloat(String str, float defaultValue) { if (StringTools.isEmpty(str)) { return defaultValue; } try { return asFloat(str); } catch (ConverterException e) { return defaultValue; } } public static float[] asFloatArray(String value) { if (value == null) { return null; } StringTokenizer tk = new StringTokenizer(value, ELEMENT_SEPARATOR, false); float[] result = new float[tk.countTokens()]; int i = 0; try { while (tk.hasMoreTokens()) { String token = tk.nextToken(); result[i] = Float.parseFloat(token.trim()); i++; } } catch (NumberFormatException e) { return null; } return result; } public static float asFloatChecked(String str, float defaultValue) throws ConverterException { if (StringTools.isEmpty(str)) { return defaultValue; } return asFloat(str); } public static int[] asIntArray(String value) { if (value == null) { return null; } StringTokenizer tk = new StringTokenizer(value, ELEMENT_SEPARATOR, false); int[] result = new int[tk.countTokens()]; int i = 0; try { while (tk.hasMoreTokens()) { String token = tk.nextToken(); result[i] = Integer.parseInt(token.trim()); i++; } } catch (NumberFormatException e) { return null; } return result; } public static int asInteger(String str) throws ConverterException { try { str = str.trim(); return Integer.parseInt(str); } catch (NumberFormatException e) { throw new ConverterException("Can't parse integer string: " + str + " to a legal value"); } } public static int asInteger(String str, int defaultValue) { if (StringTools.isEmpty(str)) { return defaultValue; } try { return asInteger(str); } catch (ConverterException e) { return defaultValue; } } public static int asIntegerChecked(String str, int defaultValue) throws ConverterException { if (StringTools.isEmpty(str)) { return defaultValue; } return asInteger(str); } public static long asLong(String str) throws ConverterException { try { str = str.trim(); return Long.parseLong(str); } catch (NumberFormatException e) { throw new ConverterException("Can't parse integer string: " + str + " to a legal value"); } } public static long asLong(String str, long defaultValue) { if (StringTools.isEmpty(str)) { return defaultValue; } try { return asLong(str); } catch (ConverterException e) { return defaultValue; } } public static long asLongChecked(String str, long defaultValue) throws ConverterException { if (StringTools.isEmpty(str)) { return defaultValue; } return asLong(str); } public static Map asMap(String string) { String key; String value; String token; Map map = new HashMap(5); if (string == null) { return map; } StringTokenizer tk = new StringTokenizer(string, ELEMENT_SEPARATOR, false); while (tk.hasMoreTokens()) { token = tk.nextToken(); int i = token.indexOf(KEY_VALUE_SEPARATOR); if (i == -1) { key = token; value = ""; } else { key = token.substring(0, i); if (i >= token.length()) { value = ""; } value = token.substring(i + 1); } map.put(key, value); } return map; } public static Map asMapBoolean(String string) { Map stringMap = asMap(string); Map boolMap = new HashMap(stringMap.size() * 2); for (Iterator i = stringMap.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); Boolean value = Boolean.valueOf((String) entry.getValue()); boolMap.put(entry.getKey(), value); } return boolMap; } public static String asString(String str, String defaultValue) { if (StringTools.isEmpty(str)) { return defaultValue; } else { return str.trim(); } } public static String[] asStringArray(String value) { if (value == null) { return null; } return value.split(ELEMENT_SEPARATOR); } public static Boolean asThreeState(String booleanString) throws ConverterException { booleanString = booleanString.toLowerCase().trim(); if (booleanString.equals("false") || booleanString.equals("f") || booleanString.equals("no") || booleanString.equals("n") || booleanString.equals("0") || booleanString.equals("falsch") || booleanString.equals("nein")) { return Boolean.FALSE; } if (booleanString.equals("true") || booleanString.equals("t") || booleanString.equals("yes") || booleanString.equals("y") || booleanString.equals("1") || booleanString.equals("wahr") || booleanString.equals("w") || booleanString.equals("ja") || booleanString.equals("j")) { return Boolean.TRUE; } if (booleanString.equals("undeterminate") || booleanString.equals("undefined") || booleanString.equals("?") || booleanString.equals("u")) { return null; } throw new ConverterException("Can't parse boolean string: " + booleanString + " to a legal value"); } public static Boolean asThreeState(String booleanString, Boolean defaultValue) { if (StringTools.isEmpty(booleanString)) { return defaultValue; } try { return asBoolean(booleanString); } catch (ConverterException e) { return defaultValue; } } private Converter() { super(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/string/ConverterException.java0000644000175000017500000000363510751651500027015 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.string; public class ConverterException extends Exception { public ConverterException() { } public ConverterException(String message) { super(message); } public ConverterException(Throwable cause) { super(cause); } public ConverterException(String message, Throwable cause) { super(message, cause); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/string/CharacterTools.java0000644000175000017500000000552511052336456026111 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.string; /** * A tool class for the handling of strings. * */ public class CharacterTools { /** * true if c is a vowel. * * @param c * The character to check. * @return true if c is a vowel. */ static public boolean isVowel(char c) { return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'; } /** * Create a byte array from the char array ignoring any encoding. * * @param value * @return A byte array created from the char array in value. */ static public byte[] toByteArray(char[] value) { if (value == null) { return null; } byte[] bytes = new byte[value.length]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) value[i]; } return bytes; } /** * Create a char array from the byte array ignoring any encoding. * * @param value * @return A char array created from the byte array in value. */ static public char[] toCharArray(byte[] value) { if (value == null) { return null; } char[] chars = new char[value.length]; for (int i = 0; i < chars.length; i++) { chars[i] = (char) value[i]; } return chars; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/cache/0000755000175000017500000000000011412336332022050 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/cache/Cache.java0000644000175000017500000001206311412330224023712 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.cache; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import de.intarsys.tools.component.ISynchronizable; /** * A very simple cache implementation. The cache supports "null" entries. * *

* The cache strategy depends on the samples taken in the CacheEntry. *

*/ public class Cache implements ISynchronizable { /** Map for associative access to elements */ private final Map> map = new HashMap>(); /** Collection for sorted access according to cache strategy */ private final CacheEntry[] elements; /** counter for currently available cache elements */ private int ptr = 0; /** * Create a cache with a maximum size of size elements. * * @param size * The maximum number of elements held in the cache. */ public Cache(int size) { super(); elements = new CacheEntry[size]; } /** * Clear all entries in the cache. * */ synchronized public void clear() { map.clear(); for (int i = 0; i < ptr; i++) { elements[i] = null; } ptr = 0; } /** * The object with the key "key" or null. * * @param key * The key to be used for looking up the cache. * * @return The object with the key "key" or null. */ synchronized public T get(Object key) { CacheEntry result = map.get(key); if (result != null) { if (result.getValue() instanceof ISynchronizable) { ISynchronizable synch = (ISynchronizable) result.getValue(); if (synch.isOutOfSynch()) { remove(key); result = null; } } } if (result != null) { result.touch(); return result.getValue(); } else { return null; } } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#isOutOfSynch() */ public boolean isOutOfSynch() { return false; } /** * Store the object "value" with the key "key" in the cache. * * @param key * The key to use for storing the object * @param value * The value to put in the cache. */ synchronized public void put(Object key, T value) { CacheEntry entry = new CacheEntry(key, value); if (ptr >= elements.length) { removeStrategy(); } elements[ptr++] = entry; map.put(key, entry); } /** * Remove an object from the cache. * * @param key */ synchronized public void remove(Object key) { CacheEntry entry = map.remove(key); for (int i = 0; i < ptr; i++) { CacheEntry current = elements[i]; if (current == entry) { ptr--; if (i < ptr) { System.arraycopy(elements, i + 1, elements, i, ptr - i); } elements[ptr] = null; } } } /** * Perform the "cleanup" of the cache. The "least valuable" cache entry is * removed. * */ protected void removeStrategy() { Arrays.sort(elements, 0, ptr); --ptr; CacheEntry entry = elements[ptr]; map.remove(entry.getKey()); elements[ptr] = null; } /** * The actual size of the cache. * * @return The actual size of the cache. */ synchronized public int size() { return ptr; } /* * (non-Javadoc) * * @see de.intarsys.tools.component.ISynchronizable#synch() */ synchronized public void synch() { for (int i = 0; i < ptr; i++) { CacheEntry element = elements[i]; if (element.getValue() instanceof ISynchronizable) { ((ISynchronizable) element.getValue()).synch(); } } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/cache/CacheEntry.java0000644000175000017500000000657211411055570024753 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.cache; /** * An entry in the cache implementation. * *

* A cache entries "importance" is expressed by a "sample". The CacheEntry with * the smallest sample is considered the least valuable. *

* *

* This implementation supports a simple "most recently used" strategy. *

*/ public class CacheEntry implements Comparable { /** remember the last used sample to ensure no two samples are the same */ private static int LASTSAMPLE = 0; /** The key of the cache entry */ private final Object key; /** The wrapped value of the entry */ private final T value; /** The sample representing the "importance" of the entry */ private int sample; /** * Create a cache entry. * * @param key * The key for the entry * @param value * The value for the entry */ protected CacheEntry(Object key, T value) { super(); this.key = key; this.value = value; touch(); } /* * (non-Javadoc) * * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(Object o) { CacheEntry other = (CacheEntry) o; if (getSample() == other.getSample()) { return 0; } if (getSample() < other.getSample()) { return 1; } return -1; } /** * The key of the cache entry. * * @return Returns the key. */ public Object getKey() { return key; } /** * The sample representing the "importance" of the entry. * * @return Returns the sample. */ public int getSample() { return sample; } /** * The value of the cache entry. * * @return Returns the value. */ public T getValue() { return value; } /** * Mark the Cache entry as recently used. */ synchronized protected void touch() { sample = LASTSAMPLE++; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/facade/0000755000175000017500000000000011412336332022210 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/facade/DelegatingFacadeFactory.java0000644000175000017500000000641210751651476027553 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.facade; import de.intarsys.tools.attribute.IAttributeSupport; /** * */ public class DelegatingFacadeFactory extends FacadeFactory { private IFacadeFactory[] factories = new IFacadeFactory[10]; private int count = 0; /** * */ public DelegatingFacadeFactory() { super(); } protected IFacade basicCreate(Object nativeObject) { for (int i = 0; i < count; i++) { IFacade result = factories[i].createFacade(nativeObject); if (result != null) { return result; } } return null; } public void addFactory(IFacadeFactory factory) { if (count >= factories.length) { IFacadeFactory[] tempFactories = new IFacadeFactory[count + 2]; System.arraycopy(factories, 0, tempFactories, 0, count); factories = tempFactories; } factories[count++] = factory; } public void removeFactory(IFacadeFactory factory) { for (int i = 0; i < count; i++) { IFacadeFactory oldFactory = factories[i]; if (oldFactory == factory) { if ((i + 1) < count) { System.arraycopy(factories, i + 1, factories, i, count - i - 1); } factories[count--] = null; } } } final public IFacade createFacade(Object nativeObject) { if (nativeObject instanceof IAttributeSupport) { IAttributeSupport as = (IAttributeSupport) nativeObject; IFacade result = (IFacade) as.getAttribute(ATTR_FACADE); if (result == null) { result = basicCreate(nativeObject); if (result != null) { as.setAttribute(ATTR_FACADE, result); } } return result; } if (nativeObject != null) { return basicCreate(nativeObject); } return null; } private static final Object ATTR_FACADE = new Object(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/facade/IFacade.java0000644000175000017500000000350211412330242024321 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.facade; /** * An object hiding the real implementation object * */ public interface IFacade { /** * The implementation behind the facade. * * @return The implementation behind the facade. */ public Object getImpl(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/facade/FacadeFactory.java0000644000175000017500000000404510751651500025553 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.facade; /** * * */ abstract public class FacadeFactory implements IFacadeFactory { private static IFacadeFactory ACTIVE = new DelegatingFacadeFactory(); public static final IFacadeFactory get() { return ACTIVE; } public static final void set(IFacadeFactory factory) { if (factory == null) { throw new NullPointerException("factory can't be null"); } ACTIVE = factory; } /** * */ public FacadeFactory() { super(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/facade/FacadeTools.java0000644000175000017500000000466610751651500025255 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.facade; /** * Tool class to handle common IFacadeFactory scenarios. * */ public class FacadeTools { public static Object createFacade(IFacadeFactory factory, Object object) { if (object instanceof IFacadeSupport) { return ((IFacadeSupport) object).createFacade(); } Object result = factory.createFacade(object); if (result == null) { return object; } else { return result; } } public static Object createFacade(Object object) { if (object instanceof IFacadeSupport) { return ((IFacadeSupport) object).createFacade(); } Object result = FacadeFactory.get().createFacade(object); if (result == null) { return object; } else { return result; } } public static Object unwrap(Object object) { if (object instanceof IFacade) { return ((IFacade) object).getImpl(); } return object; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/facade/IFacadeFactory.java0000644000175000017500000000374711064131272025671 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.facade; /** * A factory for {@link IFacade} instances to an {@link Object}. */ public interface IFacadeFactory { /** * The {@link IFacade} associated with object. * * @param object * The object whose {@link IFacade} is to be created. * * @return The {@link IFacade} associated with object. */ public IFacade createFacade(Object object); } libisrt-java-4.8.20100629/src/de/intarsys/tools/facade/IFacadeSupport.java0000644000175000017500000000351011064131272025722 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.facade; /** * An object that is able to create its own {@link IFacade}. */ public interface IFacadeSupport { /** * The associated {@link IFacade}. * * @return The associated {@link IFacade}. */ public IFacade createFacade(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/facade/Facade.java0000644000175000017500000000374010751651500024224 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.facade; /** * A common superclass for implementaing the facade pattern. * */ abstract public class Facade implements IFacade { protected Object object; /** * */ public Facade(Object object) { super(); this.object = object; } public Object getImpl() { return object; } protected Object createFacade(Object impl) { return FacadeTools.createFacade(impl); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/xml/0000755000175000017500000000000011412336332021605 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/xml/EntityDecoder.java0000644000175000017500000000352311142350242025211 0ustar twernertwernerpackage de.intarsys.tools.xml; import java.io.IOException; import java.io.Reader; import de.intarsys.tools.reader.DirectTagReader; import de.intarsys.tools.reader.IDirectTagHandler; import de.intarsys.tools.reader.ILocationProvider; public class EntityDecoder extends DirectTagReader { private static IDirectTagHandler ENTITY_HANDLER = new IDirectTagHandler() { public String process(String tagContent, Object context) throws IOException { try { if (tagContent.startsWith("#")) { char c = (char) Integer.parseInt(tagContent.substring(1), 10); return new String(new char[] { c }); } if (tagContent.equals("amp")) { return "&"; } if (tagContent.equals("lt")) { return "<"; } if (tagContent.equals("gt")) { return ">"; } if (tagContent.equals("apos")) { return "'"; } if (tagContent.equals("auml")) { return "ä"; } if (tagContent.equals("Auml")) { return "Ä"; } if (tagContent.equals("ouml")) { return "ö"; } if (tagContent.equals("Ouml")) { return "Ö"; } if (tagContent.equals("uuml")) { return "ü"; } if (tagContent.equals("Uuml")) { return "Ü"; } } catch (Exception e) { } return tagContent; } public void setLocationProvider(ILocationProvider locationProvider) { } public void startTag() { } }; private static String ENTITY_END = ";"; //$NON-NLS-1$ private static String ENTITY_START = "&"; //$NON-NLS-1$ public EntityDecoder(Reader reader) { super(reader, ENTITY_HANDLER, null); setStartTag(ENTITY_START); setEndTag(ENTITY_END); } public EntityDecoder(Reader reader, boolean escape) { super(reader, ENTITY_HANDLER, null, escape); setStartTag(ENTITY_START); setEndTag(ENTITY_END); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/xml/XMLEncodeSpecialChars.java0000644000175000017500000000567411025664516026534 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.xml; import java.io.FilterReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; /** * A reader that encodes XML special characters to entities. * */ public class XMLEncodeSpecialChars extends FilterReader { /** * A local buffer for reading escaped character sequences */ private StringReader buffer = null; public XMLEncodeSpecialChars(Reader in) { super(in); } /* * (non-Javadoc) * * @see java.io.Reader#read() */ @Override public int read() throws IOException { int c; if (buffer != null) { c = buffer.read(); if (c == -1) { buffer = null; } else { return c; } } c = super.read(); if (c == '"') { buffer = new StringReader("""); } else if (c == '&') { buffer = new StringReader("&"); } else if (c == '<') { buffer = new StringReader("<"); } else if (c == '>') { buffer = new StringReader(">"); } else { return c; } return buffer.read(); } /* * (non-Javadoc) * * @see java.io.Reader#read(char[], int, int) */ @Override public int read(char[] cbuf, int off, int len) throws IOException { int result = -1; for (int i = off; i < (off + len);) { int c = read(); if (c == -1) { return result; } cbuf[i++] = (char) c; result = i - off; } return len; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/xml/HTMLEncodeLineBreaks.java0000644000175000017500000000552111025664516026305 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.xml; import java.io.FilterReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; /** * A reader that encodes literal line breaks to html tags. *

* "\r" are ignored, "\n" are encoded. * */ public class HTMLEncodeLineBreaks extends FilterReader { /** * A local buffer for reading escaped character sequences */ private StringReader buffer = null; public HTMLEncodeLineBreaks(Reader in) { super(in); } /* * (non-Javadoc) * * @see java.io.Reader#read() */ @Override public int read() throws IOException { int c; if (buffer != null) { c = buffer.read(); if (c == -1) { buffer = null; } else { return c; } } c = super.read(); if (c == '\n') { buffer = new StringReader("
"); } else if (c == '\r') { return read(); } else { return c; } return buffer.read(); } /* * (non-Javadoc) * * @see java.io.Reader#read(char[], int, int) */ @Override public int read(char[] cbuf, int off, int len) throws IOException { int result = -1; for (int i = off; i < (off + len);) { int c = read(); if (c == -1) { return result; } cbuf[i++] = (char) c; result = i - off; } return len; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/xml/XMLTools.java0000644000175000017500000000625411142350242024134 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.xml; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import de.intarsys.tools.stream.StreamTools; public class XMLTools { public static String decodeSpecialChars(String encodedString) throws IOException { EntityDecoder decoder = new EntityDecoder(new StringReader( encodedString), false); try { return StreamTools.toString(decoder); } finally { StreamTools.close(decoder); } } public static String encodeDefault(String plainString) { Reader in = new HTMLEncodeLineBreaks(new XMLEncodeSpecialChars( new StringReader(plainString))); Writer out = new StringWriter(); try { StreamTools.copyEncoded(in, out); } catch (IOException e) { // these readers do not produce such errors. } return out.toString(); } public static String encodeLineBreaks(String plainString) { Reader in = new HTMLEncodeLineBreaks(new StringReader(plainString)); Writer out = new StringWriter(); try { StreamTools.copyEncoded(in, out); } catch (IOException e) { // these readers do not produce such errors. } return out.toString(); } public static String encodeSpecialChars(String plainString) { Reader in = new XMLEncodeSpecialChars(new StringReader(plainString)); Writer out = new StringWriter(); try { StreamTools.copyEncoded(in, out); } catch (IOException e) { // these readers do not produce such errors. } return out.toString(); } /** * This is a non instantiable tool class */ private XMLTools() { super(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/pool/0000755000175000017500000000000011412336332021756 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/pool/IPool.java0000644000175000017500000000513511411055574023654 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.pool; /** * A pool of objects. * */ public interface IPool { /** * Add an object to the pool. * * @param object * The object to be added to the pool. * @throws Exception */ public void checkin(Object object) throws Exception; /** * Get an object from the pool. *

* This may be a reused object or a new one, up to the pool strategy and * size. * * @param timeout * The maximum time to wait for an instance to be available in * milliseconds. -1 will wait indefinitely, 0 will not wait. * * @return A new object from the pool. * @throws Exception */ public Object checkout(long timeout) throws Exception; /** * Close the pool. * * @throws Exception */ public void close() throws Exception; /** * Destroy an object previously allocated from the pool. * * @param object * The object to be destroyed. * @throws Exception */ public void destroy(Object object) throws Exception; } libisrt-java-4.8.20100629/src/de/intarsys/tools/pool/GenericPool.java0000644000175000017500000000710411411055574025036 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.pool; import java.util.Stack; /** * A very simple implementation of a generic {@link IPool}. * */ public class GenericPool implements IPool { final private IPoolObjectFactory objectFactory; final private Stack objects; private boolean closed; public GenericPool(IPoolObjectFactory objectFactory) { super(); this.objectFactory = objectFactory; this.objects = new Stack(); this.closed = false; } public void checkin(Object object) throws Exception { deactivateObject(object); synchronized (this) { assertOpen(); objects.push(object); } } protected void deactivateObject(Object object) throws Exception { if (objectFactory == null) { return; } objectFactory.deactivateObject(object); } protected void destroyObject(Object object) throws Exception { if (objectFactory == null) { return; } objectFactory.destroyObject(object); } protected boolean isClosed() { return closed; } protected void assertOpen() { if (closed) { throw new IllegalStateException("pool closed"); } } public Object checkout(long timeout) throws Exception { Object result = null; synchronized (this) { assertOpen(); if (objects.isEmpty()) { result = createObject(); } else { result = objects.pop(); } } activateObject(result); return result; } protected void activateObject(Object object) throws Exception { if (objectFactory == null) { return; } objectFactory.activateObject(object); } protected Object createObject() throws Exception { if (objectFactory == null) { throw new IllegalStateException("can not create new object"); } Object result = objectFactory.createObject(); if (result == null) { throw new IllegalStateException("new object can't be null"); } return result; } public void close() throws Exception { closed = true; } public void destroy(Object object) throws Exception { destroyObject(object); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/pool/IPoolObjectFactory.java0000644000175000017500000000473611052336426026340 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.pool; /** * A factory for the lifecycle management of objects in a generic pool * implementation. * */ public interface IPoolObjectFactory { /** * Create the new object. * * @return The new object * @throws Exception */ public Object createObject() throws Exception; /** * Destroy the object. * * @param obj * The object to be destroyed. * @throws Exception */ public void destroyObject(Object obj) throws Exception; /** * Activate the object before checkout from pool. * * @param obj * The object to be activated. * @throws Exception */ public void activateObject(Object obj) throws Exception; /** * Deactivate object before checkin to pool. * * @param obj * The object to be deeactivated. * @throws Exception */ public void deactivateObject(Object obj) throws Exception; } libisrt-java-4.8.20100629/src/de/intarsys/tools/randomaccess/0000755000175000017500000000000011412336332023447 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/randomaccess/BufferedRandomAccess.java0000644000175000017500000002311311411055574030324 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.randomaccess; import java.io.IOException; /** * todo 1 length reply may be invalid */ public class BufferedRandomAccess extends AbstractRandomAccess { private static int DEFAULT_BUFFER_SIZE = 4096; /** * The buffer for the delegates data */ private byte[] bytes; /** * The relative index of the buffer's first byte in the delegates data */ private long bytesOffset = 0; /** * The number of valid bytes in the buffer */ private int count = 0; /** * The index into the buffer indicating the current byte */ private int localOffset = 0; /** * The buffered random access delegate */ private IRandomAccess randomAccess; /** * The total offset in the delegates data. *

* totalOffset = bufferOffset + localOffset; or count == 0 (invalid/empty * buffer); * */ private long totalOffset = 0; private boolean closed = false; /** * The length of the random access data */ private long length; /** * Flag if data in the buffer is currently changed. */ private boolean bufferChanged = false; public BufferedRandomAccess(IRandomAccess randomAccess) throws IOException { this(randomAccess, DEFAULT_BUFFER_SIZE); } public BufferedRandomAccess(IRandomAccess randomAccess, int bufferSize) throws IOException { this.randomAccess = randomAccess; this.bytes = new byte[bufferSize]; this.length = randomAccess.getLength(); } protected int basicRead(byte[] buffer, int start, int numBytes) throws IOException { if (localOffset >= count) { if (numBytes >= bytes.length) { flushBuffer(); randomAccess.seek(totalOffset); int readBytes = randomAccess.read(buffer, start, numBytes); if (readBytes > 0) { totalOffset += readBytes; localOffset = count; } return readBytes; } else { fillBuffer(); if (localOffset >= count) { return -1; } } } int avail = count - localOffset; int cnt = (avail < numBytes) ? avail : numBytes; System.arraycopy(bytes, localOffset, buffer, start, cnt); localOffset += cnt; totalOffset += cnt; return cnt; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#close() */ public void close() throws IOException { if (isClosed()) { return; } flushBuffer(); randomAccess.close(); setClosed(true); } protected void fillBuffer() throws IOException { flushBuffer(); randomAccess.seek(totalOffset); count = randomAccess.read(bytes, 0, bytes.length); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccess#flush() */ public void flush() throws IOException { if (isClosed()) { throw new IOException("random access closed"); } flushBuffer(); randomAccess.flush(); } protected void flushBuffer() throws IOException { if (bufferChanged && (count > 0)) { randomAccess.seek(bytesOffset); randomAccess.write(bytes, 0, count); } bytesOffset = totalOffset; localOffset = 0; count = 0; bufferChanged = false; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#getLength() */ public long getLength() throws IOException { if (isClosed()) { throw new IOException("random access closed"); } return length; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#getOffset() */ public long getOffset() throws IOException { if (isClosed()) { throw new IOException("random access closed"); } return totalOffset; } protected boolean isClosed() { return closed; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#isReadOnly() */ public boolean isReadOnly() { return randomAccess.isReadOnly(); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#read() */ public int read() throws IOException { if (closed) { throw new IOException("random access closed"); } if (localOffset >= count) { fillBuffer(); if (localOffset >= count) { return -1; } } totalOffset++; return bytes[localOffset++] & 0xff; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#read(byte[]) */ public int read(byte[] buffer) throws IOException { return read(buffer, 0, buffer.length); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#read(byte[], int, * int) */ public int read(byte[] buffer, int start, int numBytes) throws IOException { if (closed) { throw new IOException("random access closed"); } if (numBytes == 0) { return 0; } int totalByteCount = 0; while (totalByteCount < numBytes) { int byteCount = basicRead(buffer, start + totalByteCount, numBytes - totalByteCount); if (byteCount <= 0) { break; } totalByteCount += byteCount; } if (totalByteCount == 0) { return -1; } return totalByteCount; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#seek(long) */ public void seek(long offset) throws IOException { if (closed) { throw new IOException("random access closed"); } totalOffset = offset; long newLocalOffset = totalOffset - bytesOffset; if ((newLocalOffset < 0) || (newLocalOffset >= count)) { flushBuffer(); } else { localOffset = (int) newLocalOffset; } } public void seekBy(long delta) throws IOException { if (closed) { throw new IOException("random access closed"); } totalOffset += delta; long newLocalOffset = localOffset + delta; if ((newLocalOffset < 0) || (newLocalOffset >= count)) { flushBuffer(); } else { localOffset = (int) newLocalOffset; } } protected void setClosed(boolean closed) { this.closed = closed; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#setLength(int) */ public void setLength(long newLength) throws IOException { if (closed) { throw new IOException("random access closed"); } if (newLength < (bytesOffset + bytes.length)) { flushBuffer(); } if (newLength < totalOffset) { totalOffset = newLength; bytesOffset = newLength; } length = newLength; randomAccess.setLength(newLength); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#write(byte[]) */ public void write(byte[] buffer) throws IOException { write(buffer, 0, buffer.length); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#write(byte[], int, * int) */ public void write(byte[] buffer, int start, int numBytes) throws IOException { if (closed) { throw new IOException("random access closed"); } if (numBytes >= bytes.length) { // greater than local buffer size -> write directly flushBuffer(); randomAccess.seek(totalOffset); randomAccess.write(buffer, start, numBytes); totalOffset += numBytes; bytesOffset = totalOffset; if (totalOffset > length) { length = totalOffset; } return; } if (numBytes > (bytes.length - localOffset)) { // greater than rest of buffer -> flush and fill new one flushBuffer(); } System.arraycopy(buffer, start, bytes, localOffset, numBytes); bufferChanged = true; totalOffset += numBytes; localOffset += numBytes; if (totalOffset > length) { length = totalOffset; } if (localOffset >= count) { count = localOffset; } } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#write(int) */ public void write(int b) throws IOException { if (closed) { throw new IOException("random access closed"); } if (localOffset >= bytes.length) { flushBuffer(); } bufferChanged = true; if (localOffset == count) { count++; } totalOffset++; if (totalOffset > length) { length = totalOffset; } bytes[localOffset++] = (byte) b; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/randomaccess/AbstractRandomAccess.java0000644000175000017500000001116410751651500030345 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.randomaccess; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Stack; /** * Supports reading and writing to a random access data container. A random * access data container behaves like a large array of bytes. * */ public abstract class AbstractRandomAccess implements IRandomAccess { class MyOutputStream extends OutputStream { public MyOutputStream() { // } /** * must move with own pointer through random access!! */ private long offset = 0; public void write(int b) throws IOException { AbstractRandomAccess.this.seek(offset); AbstractRandomAccess.this.write(b); offset++; } public void write(byte[] b) throws IOException { AbstractRandomAccess.this.seek(offset); AbstractRandomAccess.this.write(b); offset += b.length; } public void write(byte[] b, int off, int len) throws IOException { AbstractRandomAccess.this.seek(offset); AbstractRandomAccess.this.write(b, off, len); offset += len; } public void close() throws IOException { // do not close } } class MyInputStream extends InputStream { public MyInputStream() { // } /** * must move with own pointer through random access!! */ private long offset = 0; public int read() throws IOException { AbstractRandomAccess.this.seek(offset); int i = AbstractRandomAccess.this.read(); if (i != -1) { offset++; } return i; } public int read(byte[] b, int off, int len) throws IOException { AbstractRandomAccess.this.seek(offset); int i = AbstractRandomAccess.this.read(b, off, len); if (i != -1) { offset += i; } return i; } public int read(byte[] b) throws IOException { AbstractRandomAccess.this.seek(offset); int i = AbstractRandomAccess.this.read(b); if (i != -1) { offset += i; } return i; } public void close() throws IOException { // do not close.... } } private Stack positionStack; public AbstractRandomAccess() { positionStack = new Stack(); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#getInputStream() */ public InputStream asInputStream() { return new MyInputStream(); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#getOutputStream() */ public OutputStream asOutputStream() { return new MyOutputStream(); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#mark() */ public void mark() throws IOException { getPositionStack().push(new Long(getOffset())); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#reset() */ public void reset() throws IOException { if (getPositionStack().isEmpty()) { seek(0); } else { seek(((Long) getPositionStack().pop()).longValue()); } } /** * @return Returns the positionStack. */ protected Stack getPositionStack() { return positionStack; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/randomaccess/PACKAGE.java0000644000175000017500000000341210751651500025347 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.randomaccess; import java.util.logging.Logger; import de.intarsys.tools.logging.LogTools; public class PACKAGE { public final static Logger Log = LogTools.getLogger(PACKAGE.class); } libisrt-java-4.8.20100629/src/de/intarsys/tools/randomaccess/RandomAccessFilter.java0000644000175000017500000001110710751651500030024 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.randomaccess; import java.io.IOException; /** * Filter implementation for random access. * */ public class RandomAccessFilter extends AbstractRandomAccess { protected IRandomAccess random; /** * */ public RandomAccessFilter(IRandomAccess random) { super(); this.random = random; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccess#seek(long) */ public void seek(long offset) throws IOException { random.seek(offset); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccess#seekBy(long) */ public void seekBy(long delta) throws IOException { random.seekBy(delta); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccess#read() */ public int read() throws IOException { return random.read(); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccess#getOffset() */ public long getOffset() throws IOException { return random.getOffset(); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccess#getLength() */ public long getLength() throws IOException { return random.getLength(); } protected IRandomAccess getRandom() { return random; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccess#setLength(long) */ public void setLength(long newLength) throws IOException { random.setLength(newLength); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccess#read(byte[]) */ public int read(byte[] buffer) throws IOException { return random.read(buffer); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccess#read(byte[], int, int) */ public int read(byte[] buffer, int start, int numBytes) throws IOException { return random.read(buffer, start, numBytes); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccess#close() */ public void close() throws IOException { random.close(); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccess#flush() */ public void flush() throws IOException { random.flush(); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccess#isReadOnly() */ public boolean isReadOnly() { return random.isReadOnly(); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccess#write(int) */ public void write(int b) throws IOException { random.write(b); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccess#write(byte[]) */ public void write(byte[] buffer) throws IOException { random.write(buffer); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccess#write(byte[], int, int) */ public void write(byte[] buffer, int start, int numBytes) throws IOException { random.write(buffer, start, numBytes); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/randomaccess/IRandomAccess.java0000644000175000017500000002120411412330306026757 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.randomaccess; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.RandomAccessFile; /** * An interface for an object that can randomly access bytes in a data stream. *

* This is an abstraction of {@link RandomAccessFile} to support other data * storage objects (like byte arrays and so on). */ public interface IRandomAccess { /** * A {@link InputStream} view on the data structure. * * @return A {@link InputStream} view on the data structure. */ public abstract InputStream asInputStream(); /** * A {@link OutputStream} view on the data structure. * * @return A {@link OutputStream} view on the data structure. */ public abstract OutputStream asOutputStream(); /** * Closes this random access data container and releases any system * resources associated with the stream. A closed random access data * container cannot perform input or output operations and cannot be * reopened. * * @exception IOException * if an I/O error occurs. */ public void close() throws IOException; /** * Force changes to be made persistent. * * @throws IOException */ public void flush() throws IOException; /** * Returns the length of this data container. * * @return the length of this data container, measured in bytes. * @exception IOException * if an I/O error occurs. */ public long getLength() throws IOException; /** * Returns the current offset in this data container. * * @return the offset from the beginning of the data container, in bytes, at * which the next read or write occurs. * @exception IOException * if an I/O error occurs. */ public long getOffset() throws IOException; /** * true if this is a read only data container. * * @return true if this is a read only data container. */ public boolean isReadOnly(); /** * Mark the current offset into the data in a stack like manner. */ public abstract void mark() throws IOException; /** * Reads a byte of data from this data container. The byte is returned as an * integer in the range 0 to 255 (0x00-0x0ff). This method * blocks if no input is yet available. *

* This method behaves in exactly the same way as the * {@link InputStream#read()} method of InputStream. * * @return the next byte of data, or -1 if the end of the data * container has been reached. * @exception IOException * if an I/O error occurs. Not thrown if the end of the data * container has been reached. */ public int read() throws IOException; /** * Reads up to buffer.length bytes of data from this data * container into an array of bytes. This method blocks until at least one * byte of input is available. *

* This method behaves in the exactly the same way as the * {@link InputStream#read(byte[])} method of InputStream. * * @param buffer * the buffer into which the data is read. * @return the total number of bytes read into the buffer, or * -1 if there is no more data because the end of this * data container has been reached. * @exception IOException * if an I/O error occurs. */ public int read(byte[] buffer) throws IOException; /** * Reads up to len bytes of data from this data container into * an array of bytes. This method blocks until at least one byte of input is * available. *

* * @param buffer * the buffer into which the data is read. * @param start * the start offset of the data. * @param numBytes * the maximum number of bytes read. * @return the total number of bytes read into the buffer, or * -1 if there is no more data because the end of the * file has been reached. * @exception IOException * if an I/O error occurs. */ public int read(byte[] buffer, int start, int numBytes) throws IOException; /** * Reset to the last position on the mark-stack. */ public abstract void reset() throws IOException; /** * Sets the offset, measured from the beginning of the data container at * which the next read or write occurs. The offset may be set beyond the end * of the data container. Setting the offset beyond the end of the data * container does not change the data container length. The length will * change only by writing after the offset has been set beyond the end of * the data container. * * @param offset * the offset position, measured in bytes from the beginning of * the data container * @exception IOException * if offset is less than 0 or if * an I/O error occurs. */ public void seek(long offset) throws IOException; /** * Sets the offset, measured from the current offset at which the next read * or write occurs. The offset may be set beyond the end of the data * container. Setting the offset beyond the end of the data container does * not change the data container length. The length will change only by * writing after the offset has been set beyond the end of the data * container. * * @param delta * the amount of bytes by which to change the current offset * position * * @exception IOException * if the resulting offset is less than * 0 or if an I/O error occurs. */ public void seekBy(long delta) throws IOException; /** * Assign the length. All bytes after length are truncated. If the real * length is currently less than newLength, the data structure will be * enlarged. * * @param newLength * @throws IOException */ public void setLength(long newLength) throws IOException; /** * Writes b.length bytes from the specified byte array, * starting at the current offset. * * @param buffer * the data. * @exception IOException * if an I/O error occurs. */ public void write(byte[] buffer) throws IOException; /** * Writes len bytes from the specified byte array starting at * start. * * @param buffer * the data. * @param start * the start offset in the data. * @param numBytes * the number of bytes to write. * @exception IOException * if an I/O error occurs. */ public abstract void write(byte[] buffer, int start, int numBytes) throws IOException; /** * Writes the specified byte . The write starts at the current offset. * * @param b * the byte to be written. * @exception IOException * if an I/O error occurs. */ public void write(int b) throws IOException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/randomaccess/RandomAccessByteArray.java0000644000175000017500000001471311411055574030512 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.randomaccess; import java.io.IOException; /** * A wrapper around a byte array to allow random access like API. * */ public class RandomAccessByteArray extends AbstractRandomAccess { /** * The minimum number of bytes we will resize the byte array buffer */ private static final int RESIZE_BYTES = 32; /** * The byte array data */ protected byte[] data; /** * The current offset into the byte array */ private int offset; /** * The number of valid bytes in the byte array */ protected int length; public RandomAccessByteArray(byte[] buffer) { this.offset = 0; if (buffer == null) { this.data = new byte[RESIZE_BYTES]; this.length = 0; } else { this.data = buffer; this.length = buffer.length; } } public RandomAccessByteArray(byte[] buffer, int length) { this.offset = 0; if (buffer == null) { this.data = new byte[RESIZE_BYTES]; this.length = 0; } else { this.data = buffer; this.length = length; } } final protected void basicSetLengthResize(int newLength) { if (newLength > data.length) { byte[] newData; if ((newLength - data.length) < RESIZE_BYTES) { newData = new byte[data.length + RESIZE_BYTES]; } else { newData = new byte[newLength]; } System.arraycopy(data, 0, newData, 0, length); data = newData; } length = newLength; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccess#close() */ public void close() throws IOException { flush(); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccess#flush() */ public void flush() throws IOException { // } /** * @return Returns the data. */ protected byte[] getData() { return data; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#getLength() */ public long getLength() throws IOException { return length; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#getOffset() */ public long getOffset() { return offset; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#isReadOnly() */ public boolean isReadOnly() { return false; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#read() */ public int read() { if (offset < length) { return data[offset++] & 0xff; } return -1; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#read(byte[]) */ public int read(byte[] buffer) { return read(buffer, 0, buffer.length); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#read(byte[], int, * int) */ public int read(byte[] buffer, int bufferOffset, int numBytes) { int remaining = (length - offset); if (numBytes > remaining) { numBytes = remaining; if (numBytes == 0) { return -1; } } System.arraycopy(data, offset, buffer, bufferOffset, numBytes); offset += numBytes; return numBytes; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#seek(long) */ public void seek(long pOffset) throws IOException { this.offset = (int) pOffset; if (offset < 0) { offset = 0; throw new IOException("offset less than 0"); } } public void seekBy(long delta) throws IOException { this.offset = (int) (offset + delta); if (offset < 0) { offset = 0; throw new IOException("offset less than 0"); } } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#setLength(int) */ public void setLength(long newLength) { int tempLength = (int) newLength; if (tempLength > length) { basicSetLengthResize(tempLength); } else { if (offset > tempLength) { offset = tempLength; } length = tempLength; } } public byte[] toByteArray() { byte[] newbuf = new byte[length]; System.arraycopy(data, 0, newbuf, 0, length); return newbuf; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#write(byte[]) */ public void write(byte[] buffer) { write(buffer, 0, buffer.length); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#write(byte[]) */ public void write(byte[] buffer, int start, int numBytes) { int newLength = offset + numBytes; if (newLength > length) { basicSetLengthResize(newLength); } System.arraycopy(buffer, start, data, offset, numBytes); offset += numBytes; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#write(int) */ public void write(int b) { int newLength = offset + 1; if (newLength > length) { basicSetLengthResize(newLength); } data[offset++] = (byte) b; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/randomaccess/RandomAccessFile.java0000644000175000017500000001377611171645034027476 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.randomaccess; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.logging.Logger; /** * Implements random access to a file. */ public class RandomAccessFile extends AbstractRandomAccess { /** The logger to be used in this package */ private static Logger Log = PACKAGE.Log; /** * The wrapped RandomAccessFile of the java library */ private java.io.RandomAccessFile fileAccess; /** * Flag if this is used read only */ private boolean readOnly = false; private File file; /** * @param file * to open for random access * @throws FileNotFoundException * if file was not found or the file is locked by a different * process */ public RandomAccessFile(File file) throws IOException { this(file, true); } /** * @param file * to open for random access * @throws FileNotFoundException * if file was not found or the file is locked by a different * process */ public RandomAccessFile(File file, boolean create) throws IOException { this.file = file; if (create && !file.exists()) { File dir = file.getParentFile(); if ((dir != null) && !dir.exists()) { dir.mkdirs(); } file.createNewFile(); } if (!file.exists()) { throw new FileNotFoundException( "file does not exist or can't be created"); } if (file.canWrite()) { try { fileAccess = new java.io.RandomAccessFile(file, "rw"); return; } catch (IOException e) { // canWrite() doesn't check for user permissions // try again with readonly } } fileAccess = new java.io.RandomAccessFile(file, "r"); readOnly = true; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#close() */ public void close() throws IOException { if (fileAccess != null) { fileAccess.close(); } } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccess#flush() */ public void flush() throws IOException { fileAccess.getChannel().force(true); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#getLength() */ public long getLength() throws IOException { return fileAccess.length(); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#getOffset() */ public long getOffset() throws IOException { return fileAccess.getFilePointer(); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#isReadOnly() */ public boolean isReadOnly() { return readOnly; } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#read() */ public int read() throws IOException { return fileAccess.read(); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#read(byte[]) */ public int read(byte[] buffer) throws IOException { return fileAccess.read(buffer); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#read(byte[], int, * int) */ public int read(byte[] buffer, int start, int numBytes) throws IOException { return fileAccess.read(buffer, start, numBytes); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#seek(long) */ public void seek(long offset) throws IOException { fileAccess.seek(offset); } public void seekBy(long delta) throws IOException { seek(fileAccess.getFilePointer() + delta); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#setLength(int) */ public void setLength(long newLength) throws IOException { fileAccess.setLength(newLength); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#write(byte[]) */ public void write(byte[] buffer) throws IOException { fileAccess.write(buffer); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#write(byte[], int, * int) */ public void write(byte[] buffer, int start, int numBytes) throws IOException { fileAccess.write(buffer, start, numBytes); } /* * (non-Javadoc) * * @see de.intarsys.tools.randomaccess.IRandomAccessData#write(int) */ public void write(int b) throws IOException { fileAccess.write(b); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/randomaccess/RandomAccessViewport.java0000644000175000017500000001045511153723336030427 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.randomaccess; import java.io.IOException; /** * A viewport in an existing {@link IRandomAccess}. * */ public class RandomAccessViewport extends RandomAccessFilter { private final long viewOffset; private long viewLength; private long viewEnd; /** * Create a viewport to the existing {@link IRandomAccess} ra. *

* ATTENTION: This will not seek to offset in ra. * This means after creation before initial use you have to position the * {@link IRandomAccess} yourself using seek. * * @param ra * @param offset * @param length * @throws IOException */ public RandomAccessViewport(IRandomAccess ra, long offset, long length) throws IOException { super(ra); this.viewLength = length; this.viewOffset = offset; this.viewEnd = viewOffset + viewLength; } @Override public long getLength() throws IOException { long realLength = getRandom().getLength(); if (getViewLength() == -1) { return realLength - getViewOffset(); } return Math.min(getViewLength(), realLength - getViewOffset()); } @Override public long getOffset() throws IOException { return getRandom().getOffset() - getViewOffset(); } protected long getViewEnd() { return viewEnd; } protected long getViewLength() { return viewLength; } protected long getViewOffset() { return viewOffset; } @Override public boolean isReadOnly() { return true; } @Override public int read() throws IOException { if (getViewLength() != -1 && getOffset() >= getViewEnd()) { return -1; } return super.read(); } @Override public int read(byte[] buffer) throws IOException { return read(buffer, 0, buffer.length); } @Override public int read(byte[] buffer, int start, int numBytes) throws IOException { if (getViewLength() != -1 && getOffset() >= getViewEnd()) { return -1; } if (getViewLength() != -1) { numBytes = Math.min(numBytes, (int) (getViewEnd() - getOffset())); } return super.read(buffer, start, numBytes); } @Override public void seek(long offset) throws IOException { super.seek(getViewOffset() + offset); } @Override public void seekBy(long delta) throws IOException { super.seekBy(delta); } @Override public void setLength(long newLength) throws IOException { throw new IOException("not yet supported"); } @Override public void write(byte[] buffer) throws IOException { super.write(buffer); } @Override public void write(byte[] buffer, int start, int numBytes) throws IOException { super.write(buffer, start, numBytes); } @Override public void write(int b) throws IOException { super.write(b); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/encoding/0000755000175000017500000000000011412336332022573 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/encoding/Base64.java0000644000175000017500000002112411412330236024457 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.encoding; /** * An encoder for the BASE 64 code. * */ public class Base64 { final private static byte PAD = (byte) '='; final private static char[] base64Chars = { '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', '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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; final private static int[] base64Positions = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; /** * Decodes Base64 data into octets * * @param inputBytes * Byte array containing Base64 data * * @return byte array containing decoded data. */ public static byte[] decode(byte[] inputBytes) { // this is probably not the most performant implementation, // but I find it slightly more readable than others I've seen // [MIT] .... sorry, but refactored version is x times faster (but ugly) if (inputBytes == null) { return null; } int newSize = 0; int len = inputBytes.length; for (int i = 0; i < len; i++) { byte octect = inputBytes[i]; if (((octect == 0x20) || (octect == 0xd) || (octect == 0xa) || (octect == 0x9))) { continue; } if ((base64Positions[inputBytes[i]] != -1)) { if (newSize != i) { inputBytes[newSize] = inputBytes[i]; } newSize++; continue; } if ((inputBytes[i] == PAD)) { // ignore error in case there is data after PAD break; } // data error return null; } if (newSize == 0) { return new byte[0]; } if ((newSize % 4) == 1) { // invalid return null; } byte[] result = new byte[((newSize - 1) / 4 * 3) + ((newSize - 1) % 4)]; int threeI = 0; int fourI = 0; for (int i = 0; threeI < result.length; i++, threeI += 3, fourI += 4) { int bits; boolean padded3; boolean padded4; padded3 = padded4 = false; bits = (base64Positions[inputBytes[fourI]] << 18) + (base64Positions[inputBytes[fourI + 1]] << 12); if (newSize > (fourI + 2)) { bits += (base64Positions[inputBytes[fourI + 2]] << 6); if (newSize > (fourI + 3)) { bits += base64Positions[inputBytes[fourI + 3]]; } else { padded4 = true; } } else { // 3rd and 4th result bytes are padded padded3 = padded4 = true; } result[threeI] = (byte) (bits >> 16); if (!padded3) { result[threeI + 1] = (byte) ((bits >> 8) & 0xff); } if (!padded4) { result[threeI + 2] = (byte) (bits & 0xff); } } return result; } /** * Encodes hex octets into Base64 * * @param inputBytes * Array containing binaryData * * @return Encoded Base64 array */ public static byte[] encode(byte[] inputBytes) { // this is probably not the most performant implementation, // but I find it slightly more readable than others I've seen byte[] result; int inputLength; if (inputBytes == null) { return null; } inputLength = inputBytes.length; result = new byte[(inputLength + 2) / 3 * 4]; int i = 0; int iTimesFour = 0; int iTimesThree = 0; while (iTimesFour < result.length) { int bits; boolean pad3; boolean pad4; pad3 = pad4 = false; bits = (inputBytes[iTimesThree] << 16) & 0xff0000; if (inputLength > ((iTimesThree) + 1)) { bits |= ((inputBytes[(iTimesThree) + 1] << 8) & 0xff00); if (inputLength > ((iTimesThree) + 2)) { bits |= (inputBytes[(iTimesThree) + 2] & 0xff); } else { pad4 = true; } } else { // have to pad 3rd and 4th result byte pad3 = pad4 = true; } result[iTimesFour] = (byte) base64Chars[(bits >> 18) & 0x3f]; result[(iTimesFour) + 1] = (byte) base64Chars[(bits >> 12) & 0x3f]; result[(iTimesFour) + 2] = (byte) (pad3 ? PAD : base64Chars[(bits >> 6) & 0x3f]); result[(iTimesFour) + 3] = (byte) (pad4 ? PAD : base64Chars[(bits) & 0x3f]); i++; iTimesFour += 4; iTimesThree += 3; } return result; } /** * returns length of decoded data given an array containing encoded data. * WhiteSpace removing is done if data array not valid. * * @param base64Data * * @return a -1 would be return if not */ public static int getDecodedDataLength(byte[] base64Data) { if (base64Data == null) { return -1; } if (base64Data.length == 0) { return 0; } // byte[] normalizedBase64Data = removeWhiteSpace( base64Data );//Remove // any whiteSpace byte[] decodedData = null; if ((decodedData = decode(base64Data)) == null) { // decode could // return a null // byte array return -1; } return decodedData.length; } public static boolean isArrayByteBase64(byte[] arrayOctect) { return (getDecodedDataLength(arrayOctect) >= 0); } public static boolean isBase64(byte octect) { return (((octect == 0x20) || (octect == 0xd) || (octect == 0xa) || (octect == 0x9)) || (octect == PAD) || (base64Positions[octect] != -1)); } public static boolean isBase64(String isValidString) { if (isValidString == null) { return false; } return (isArrayByteBase64(isValidString.getBytes())); } /** * Remove whitespace from MIME containing encoded Base64 data. e.g. " * sdffferererrereresfsdfsdfsdff\n\r iiiiiiiiierejrlkwjerklwjerwerwr==\n\r" * * @param data * * @return The input data without whitespace. */ public static byte[] removeWhiteSpace(byte[] data) { if (data == null) { return null; } int newSize = 0; int len = data.length; int i = 0; for (; i < len; i++) { byte octect = data[i]; if (!((octect == 0x20) || (octect == 0xd) || (octect == 0xa) || (octect == 0x9))) { newSize++; } } if (newSize == len) { return data; // return input array since no whiteSpace } byte[] arrayWithoutSpaces = new byte[newSize]; // Allocate new array // without whiteSpace int j = 0; for (i = 0; i < len; i++) { byte octect = data[i]; if (((octect == 0x20) || (octect == 0xd) || (octect == 0xa) || (octect == 0x9))) { continue; } else { arrayWithoutSpaces[j++] = data[i]; // copy non-WhiteSpace } } return arrayWithoutSpaces; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/encoding/Base32.java0000644000175000017500000001107111267270502024461 0ustar twernertwernerpackage de.intarsys.tools.encoding; /* (PD) 2001 The Bitzi Corporation * Please see http://bitzi.com/publicdomain for more info. * * Base32.java * */ /** * Base32 - encodes and decodes 'Canonical' Base32 * * @author Robert Kaye & Gordon Mohr */ public class Base32 { private static final String base32Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; private static final int[] base32Lookup = { 0xFF,0xFF,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F, // '0', '1', '2', '3', '4', '5', '6', '7' 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, // '8', '9', ':', ';', '<', '=', '>', '?' 0xFF,0x00,0x01,0x02,0x03,0x04,0x05,0x06, // '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G' 0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E, // 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O' 0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16, // 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W' 0x17,0x18,0x19,0xFF,0xFF,0xFF,0xFF,0xFF, // 'X', 'Y', 'Z', '[', '\', ']', '^', '_' 0xFF,0x00,0x01,0x02,0x03,0x04,0x05,0x06, // '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g' 0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E, // 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o' 0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16, // 'p', 'q', 'r', 's', 't', 'u', 'v', 'w' 0x17,0x18,0x19,0xFF,0xFF,0xFF,0xFF,0xFF // 'x', 'y', 'z', '{', '|', '}', '~', 'DEL' }; static public String encode(final byte[] bytes) { int i =0, index = 0, digit = 0; int currByte, nextByte; // begin fix // added by jonelo@jonelo.de, Feb 13, 2005 // according to RFC 3548, the encoding must also contain paddings in some cases int add=0; switch (bytes.length) { case 1: add=6; break; case 2: add=4; break; case 3: add=3; break; case 4: add=1; break; } // end fix StringBuffer base32 = new StringBuffer(((bytes.length+7)*8/5)+add); while(i < bytes.length) { currByte = (bytes[i]>=0) ? bytes[i] : (bytes[i]+256); // unsign /* Is the current digit going to span a byte boundary? */ if (index > 3) { if ((i+1)=0) ? bytes[i+1] : (bytes[i+1]+256); else nextByte = 0; digit = currByte & (0xFF >> index); index = (index + 5) % 8; digit <<= index; digit |= nextByte >> (8 - index); i++; } else { digit = (currByte >> (8 - (index + 5))) & 0x1F; index = (index + 5) % 8; if (index == 0) i++; } base32.append(base32Chars.charAt(digit)); } // begin fix // added by jonelo@jonelo.de, Feb 13, 2005 // according to RFC 3548, the encoding must also contain paddings in some cases switch (bytes.length) { case 1: base32.append("======"); break; case 2: base32.append("===="); break; case 3: base32.append("==="); break; case 4: base32.append("="); break; } // end fix return base32.toString(); } static public byte[] decode(final String base32) { int i, index, lookup, offset, digit; byte[] bytes = new byte[base32.length()*5/8]; for(i = 0, index = 0, offset = 0; i < base32.length(); i++) { lookup = base32.charAt(i) - '0'; /* Skip chars outside the lookup table */ if ( lookup < 0 || lookup >= base32Lookup.length) continue; digit = base32Lookup[lookup]; /* If this digit is not in the table, ignore it */ if (digit == 0xFF) continue; if (index <= 3) { index = (index + 5) % 8; if (index == 0) { bytes[offset] |= digit; offset++; if(offset>=bytes.length) break; } else bytes[offset] |= digit << (8 - index); } else { index = (index + 5) % 8; bytes[offset] |= (digit >>> index); offset++; if(offset>=bytes.length) break; bytes[offset] |= digit << (8 - index); } } return bytes; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/environment/0000755000175000017500000000000011412336332023351 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/environment/file/0000755000175000017500000000000011412336332024270 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/environment/file/StandardFileEnvironment.java0000644000175000017500000000542411035462526031733 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.environment.file; import java.io.File; public class StandardFileEnvironment implements IFileEnvironment { private File baseDir; private File profileDir; private File workingDir; private File tempDir; public StandardFileEnvironment() { baseDir = new File(System.getProperty("user.dir")); //$NON-NLS-1$ profileDir = new File(System.getProperty("user.home")); //$NON-NLS-1$ tempDir = new File(System.getProperty("java.io.tmpdir")); //$NON-NLS-1$ workingDir = new File(System.getProperty("user.dir")); //$NON-NLS-1$ } public StandardFileEnvironment(File pBaseDir, File pProfileDir) { baseDir = pBaseDir; profileDir = pProfileDir; tempDir = new File(System.getProperty("java.io.tmpdir")); //$NON-NLS-1$ workingDir = pBaseDir; } public StandardFileEnvironment(File pBaseDir, File pProfileDir, File pTempDir, File pWorkingDir) { baseDir = pBaseDir; profileDir = pProfileDir; tempDir = pTempDir; workingDir = pWorkingDir; } public File getBaseDir() { return baseDir; } public File getProfileDir() { return profileDir; } public File getTempDir() { return tempDir; } public File getWorkingDir() { return workingDir; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/environment/file/FileEnvironment.java0000644000175000017500000000455711035462526030260 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.environment.file; /** * A VM singleton for accessing an {@link IFileEnvironment}. The * {@link IFileEnvironment} returned is thread context sensitive. */ public class FileEnvironment { protected static IFileEnvironment sharedEnvironment = new StandardFileEnvironment(); protected static ThreadLocal environment = new ThreadLocal() { @Override protected Object initialValue() { return getShared(); } }; public static IFileEnvironment get() { return (IFileEnvironment) environment.get(); } synchronized public static IFileEnvironment getShared() { return sharedEnvironment; } public static void set(IFileEnvironment cc) { environment.set(cc); } synchronized public static void setShared(IFileEnvironment cc) { sharedEnvironment = cc; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/environment/file/IFileEnvironment.java0000644000175000017500000000507511035462526030365 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.environment.file; import java.io.File; /** * An object describing the process / VM file system context. */ public interface IFileEnvironment { /** * The platform base directory. *

* Normally this will be equal to the VM "user.dir" property. * * @return The platform base directory. */ public File getBaseDir(); /** * Some user specific private directory. *

* Normally this will be equal to the VM "user.home" property or an * application defined subdirectory. * * @return Some private directory. * */ public File getProfileDir(); /** * The directory for temporary files. *

* Normally this will be equal to the VM "java.io.tmpdir" property. * * @return The directory for temporary files. */ public File getTempDir(); /** * The working directory. *

* Normally this will be equal to the VM "user.dir" property. * * @return The working directory. */ public File getWorkingDir(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/authenticate/0000755000175000017500000000000011412336332023463 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/authenticate/PasswordProvider.java0000644000175000017500000000053211412330212027632 0ustar twernertwernerpackage de.intarsys.tools.authenticate; /** * A VM singleton for accessing a {@link IPasswordProvider}. * */ public class PasswordProvider { private static IPasswordProvider ACTIVE; static public IPasswordProvider get() { return ACTIVE; } static public void set(IPasswordProvider active) { ACTIVE = active; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/authenticate/IAuthenticationProvider.java0000644000175000017500000000361411412330206031127 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.authenticate; /** * A simple interface for providing complete authentication. * */ public interface IAuthenticationProvider extends IPasswordProvider { /** * A username or null to indicate cancellation. * * @return A username or null to indicate cancellation. */ public String getUsername(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/authenticate/ConstantPasswordProvider.java0000644000175000017500000000413011257124646031365 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.authenticate; /** * A simple {@link IPasswordProvider} to return a constant value. */ public class ConstantPasswordProvider implements IPasswordProvider { private final char[] password; public ConstantPasswordProvider(char[] password) { super(); this.password = password; } /* * (non-Javadoc) * * @see de.intarsys.tools.authenticate.IPasswordProvider#getPassword() */ public char[] getPassword() { // return a copy - client might clear password! return password.clone(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/authenticate/IPasswordValidator.java0000644000175000017500000000374410751651500030121 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.authenticate; import java.io.IOException; /** * A simple interface for a password validator. * */ public interface IPasswordValidator { /** * Check if the password provided by the user is valid. * * @param password * The password provided by the user. * @return true if password valid. */ public boolean isValid(char[] password) throws IOException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/authenticate/PasswordTools.java0000644000175000017500000001151111412330214027141 0ustar twernertwernerpackage de.intarsys.tools.authenticate; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.KeySpec; import java.util.Random; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEParameterSpec; import de.intarsys.tools.encoding.Base64; import de.intarsys.tools.string.StringTools; /** * A tool class for handling passwords and authentication * */ public class PasswordTools { final private static String CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDREFGHIJKLMNOPQRSTUVWXYZ"; private static Cipher ecipher; private static Cipher dcipher; /** * Create a random password of length length. * * @param length * @return A new random password. */ static public char[] createRandom(int length) { Random rand = new Random(System.currentTimeMillis()); StringBuffer sb = new StringBuffer(); for (int i = 0; i <= length; i++) { int pos = rand.nextInt(CHARS.length()); sb.append(CHARS.charAt(pos)); } return sb.toString().toCharArray(); } /** * Decrypt a byte array which was previously encrypted using * encrypt. Provided the same salt and passphrase are used for * initialization, this method returns the original unencrypted input. * * @param bytes * @return The decrypted representation of bytes */ static public byte[] decrypt(byte[] bytes) { try { return dcipher.doFinal(bytes); } catch (BadPaddingException e) { } catch (IllegalBlockSizeException e) { } return null; } /** * Decrypt a string which was previously encrypted using * encrypt. Provided the same salt and passphrase are used for * initialization, this method returns the original unencrypted input. * * @param value * @return The decrypted representation of value */ static public char[] decrypt(String value) { try { byte[] bytes = Base64.decode(StringTools.toByteArray(value)); byte[] decrypted = decrypt(bytes); return new String(decrypted, "UTF8").toCharArray(); } catch (UnsupportedEncodingException e) { // must have encoding return null; } } /** * Encrypt a clear text array of bytes. The result is the plain encrypted * byte array. * * @param bytes * @return The encrpyted representation of bytes */ static public byte[] encrypt(byte[] bytes) { try { return ecipher.doFinal(bytes); } catch (BadPaddingException e) { } catch (IllegalBlockSizeException e) { } return null; } /** * Encrypt a clear text array of chars. The result is a Base64 encoded * string version of the encrypted UTF-8 encoded input bytes. * * @param value * @return An encrypted, invertible representation of value */ static public String encrypt(char[] value) { try { byte[] bytes = new String(value).getBytes("UTF8"); byte[] encrypted = encrypt(bytes); return new String(Base64.encode(encrypted)); } catch (UnsupportedEncodingException e) { // must have encoding return null; } } /** * A one way hash for a clear text password. * * @param password * @return A one way hash for a clear text password. */ static public String hash(char[] password) { if (StringTools.isEmpty(password)) { return ""; } MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { return new String(password); } try { md.update(new String(password).getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // can't happen return new String(password); } byte raw[] = md.digest(); return new String(Base64.encode(raw)); } /** * Initialize the {@link PasswordTools}. * * @param salt * @param passphrase */ static public void initialize(byte[] salt, char[] passphrase) { try { int iterationCount = 19; // KeySpec keySpec = new PBEKeySpec(passphrase, salt, iterationCount); SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES") .generateSecret(keySpec); ecipher = Cipher.getInstance(key.getAlgorithm()); dcipher = Cipher.getInstance(key.getAlgorithm()); AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount); ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec); } catch (Exception e) { throw new IllegalStateException("can't initialize password tools", e); } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/authenticate/NullPasswordProvider.java0000644000175000017500000000363411154241516030506 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.authenticate; /** * A dummy {@link IPasswordProvider} for example to use in a batch environment. */ public class NullPasswordProvider implements IPasswordProvider { /* * (non-Javadoc) * * @see de.intarsys.tools.authenticate.IPasswordProvider#getPassword() */ public char[] getPassword() { return null; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/authenticate/IPasswordProvider.java0000644000175000017500000000415211257124656027771 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.authenticate; /** * A simple interface for a password provider. Implementors can provide * passwords from any source, for example a database or a GUI. */ public interface IPasswordProvider { /** * Returns a password or null to indicate cancellation. *

* You should be prepared that requesting the password twice will return an * empty array or null, as the provider may null out the object for security * reasons. * * @return a char[] containing the password or null */ public char[] getPassword(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/writer/0000755000175000017500000000000011412336332022321 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/writer/ConsoleWriter.java0000644000175000017500000000742710751651500025777 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.writer; import java.io.IOException; import java.io.Writer; /** * The console writer wraps System.out in a writer that is never closed * accidently. * */ public class ConsoleWriter extends Writer { /** * ConsoleWriter constructor comment. */ public ConsoleWriter() { super(); } /** * ConsoleWriter constructor comment. * * @param lock * java.lang.Object */ protected ConsoleWriter(Object lock) { super(lock); } /** * Close the stream, flushing it first. Once a stream has been closed, * further write() or flush() invocations will cause an IOException to be * thrown. Closing a previously-closed stream, however, has no effect. * * @exception IOException * If an I/O error occurs */ public void basicClose() throws IOException { System.out.close(); } /** * Close the stream, flushing it first. Once a stream has been closed, * further write() or flush() invocations will cause an IOException to be * thrown. Closing a previously-closed stream, however, has no effect. * * @exception IOException * If an I/O error occurs */ public void close() throws IOException { // you don't want to close the console } /** * Flush the stream. If the stream has saved any characters from the various * write() methods in a buffer, write them immediately to their intended * destination. Then, if that destination is another character or byte * stream, flush it. Thus one flush() invocation will flush all the buffers * in a chain of Writers and OutputStreams. * * @exception IOException * If an I/O error occurs */ public void flush() throws IOException { System.out.flush(); } /** * Write a portion of an array of characters. * * @param cbuf * Array of characters * @param off * Offset from which to start writing characters * @param len * Number of characters to write * * @exception IOException * If an I/O error occurs */ public void write(char[] cbuf, int off, int len) throws IOException { System.out.print(String.copyValueOf(cbuf, off, len)); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/writer/LogWriter.java0000644000175000017500000000765111025664520025116 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.writer; import java.io.FilterWriter; import java.io.IOException; import java.io.Writer; /** * A writer that logs any char written. *

* The writer is piped in the writing process, any characters written are copied * to an associated writer object. * *

 * Client -> LogWriter -> Writer -> Destination
 *            |
 *            v
 *           Writer (Copy)
 * 
*/ public class LogWriter extends FilterWriter { /** * */ private Writer log; /** * EscapeWriter constructor comment. * * @param o * java.io.Writer * @param log * */ public LogWriter(Writer o, Writer log) { super(o); setLog(log); } /** * Close the stream, flushing it first. Once a stream has been closed, * further write() or flush() invocations will cause an IOException to be * thrown. Closing a previously-closed stream, however, has no effect. * * @exception java.io.IOException * If an I/O error occurs */ @Override public void close() throws java.io.IOException { super.close(); if (getLog() != null) { getLog().close(); } } /** * Flush the stream. If the stream has saved any characters from the various * write() methods in a buffer, write them immediately to their intended * destination. Then, if that destination is another character or byte * stream, flush it. Thus one flush() invocation will flush all the buffers * in a chain of Writers and OutputStreams. * * @exception java.io.IOException * If an I/O error occurs */ @Override public void flush() throws java.io.IOException { super.flush(); if (getLog() != null) { getLog().flush(); } } public java.io.Writer getLog() { return log; } private void setLog(java.io.Writer newLog) { log = newLog; } @Override public void write(char[] cbuf, int off, int len) throws IOException { super.write(cbuf, off, len); if (getLog() != null) { getLog().write(cbuf, off, len); } } @Override public void write(int c) throws IOException { super.write(c); if (getLog() != null) { getLog().write(c); } } @Override public void write(String str, int off, int len) throws IOException { super.write(str, off, len); if (getLog() != null) { getLog().write(str, off, len); } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/writer/EscapeWriter.java0000644000175000017500000000757111025664520025576 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.writer; import java.io.IOException; import java.io.Writer; /** * A writer that escapes predefined character sequences. * */ public class EscapeWriter extends Writer { // the underlying writer object private Writer out; // the code to use for replacement private String destinationChars = "\\nrt"; // the chars to replace private String sourceChars = "\\\n\r\t"; /** * EscapeWriter constructor comment. * * @param o * java.io.Writer */ public EscapeWriter(Writer o) { super(o); setOut(o); } /** * Close the stream, flushing it first. Once a stream has been closed, * further write() or flush() invocations will cause an IOException to be * thrown. Closing a previously-closed stream, however, has no effect. * * @exception java.io.IOException * If an I/O error occurs */ @Override public void close() throws java.io.IOException { getOut().close(); } /** * Flush the stream. If the stream has saved any characters from the various * write() methods in a buffer, write them immediately to their intended * destination. Then, if that destination is another character or byte * stream, flush it. Thus one flush() invocation will flush all the buffers * in a chain of Writers and OutputStreams. * * @exception java.io.IOException * If an I/O error occurs */ @Override public void flush() throws java.io.IOException { getOut().flush(); } public java.lang.String getDestinationChars() { return destinationChars; } public java.io.Writer getOut() { return out; } public java.lang.String getSourceChars() { return sourceChars; } public void setDestinationChars(java.lang.String newDestinationChars) { destinationChars = newDestinationChars; } private void setOut(java.io.Writer newOut) { out = newOut; } public void setSourceChars(java.lang.String newSourceChars) { sourceChars = newSourceChars; } @Override public void write(char[] cbuf, int off, int len) throws IOException { for (int i = off; i < (off + len); i++) { int index = getSourceChars().indexOf(cbuf[i]); if (index >= 0) { out.write('\\'); out.write(getDestinationChars().charAt(index)); } else { out.write(cbuf[i]); } } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/0000755000175000017500000000000011412336332022465 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/functor/INamedFunctor.java0000644000175000017500000000363611411055572026041 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * An {@link IFunctor} that can be identified via a unique id. */ public interface INamedFunctor extends IFunctor { /** * */ public static final String ATTR_ID = "id"; /** * A unique id for the {@link IFunctor}. * * @return A unique id for the {@link IFunctor}. */ public String getId(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/ArgTools.java0000644000175000017500000006331711412330264025072 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; import java.awt.geom.Point2D; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import de.intarsys.tools.enumeration.EnumItem; import de.intarsys.tools.enumeration.EnumMeta; import de.intarsys.tools.locator.FileLocator; import de.intarsys.tools.locator.ILocator; import de.intarsys.tools.locator.ILocatorFactory; import de.intarsys.tools.reflect.ClassTools; import de.intarsys.tools.string.Converter; import de.intarsys.tools.string.StringTools; /** * Tool class to ease handling of arguments. * */ public class ArgTools { static private int nesting = 0; public static final IFunctor toString = new IFunctor() { public Object perform(IFunctorCall call) throws FunctorInvocationException { Args args = (Args) call.getReceiver(); StringBuilder sb = new StringBuilder(); if (args.isNamed()) { for (Iterator it = args.names().iterator(); it.hasNext();) { String name = (String) it.next(); sb.append(name); sb.append(" = "); sb.append(args.get(name)); sb.append("\n"); } } else { for (int i = 0; i < args.size(); i++) { sb.append(i); sb.append(" = "); sb.append(args.get(i)); sb.append("\n"); } } return sb.toString(); } }; private static Set visited; protected static ILocator createLocator(Object optionValue, ILocator defaultValue, ILocatorFactory factory) { if (optionValue == null) { return defaultValue; } if (optionValue instanceof ILocator) { return (ILocator) optionValue; } if (optionValue instanceof File) { try { return factory.createLocator(((File) optionValue) .getAbsolutePath()); } catch (IOException e) { return defaultValue; } } if (optionValue instanceof String) { if (StringTools.isEmpty((String) optionValue)) { return defaultValue; } try { return factory.createLocator((String) optionValue); } catch (IOException e) { return defaultValue; } } return defaultValue; } /** * The argument value at name as an {@link IArgs} instance. If * the argument value is not provided or not convertible, * defaultValueis returned. *

* This method performs the necessary casts and conversions. Supported input * types are null, {@link IArgs}, {@link String}, {@link Map} * and {@link List}. * * @param args * @param name * @param defaultValue * @return The argument value at name as an {@link IArgs} * instance. */ public static IArgs getArgs(IArgs args, String name, IArgs defaultValue) { if (args == null) { return defaultValue; } Object optionValue = args.get(name); if (optionValue == null) { return defaultValue; } if (optionValue instanceof IArgs) { return (IArgs) optionValue; } if (optionValue instanceof String) { optionValue = Converter.asMap((String) optionValue); } if (optionValue instanceof Map) { return new Args((Map) optionValue); } if (optionValue instanceof List) { return new Args((List) optionValue); } return defaultValue; } /** * The argument value at name as a boolean. If the argument * value is not provided or not convertible, defaultValueis * returned. *

* This method performs the necessary casts and conversions. Supported input * types are null, {@link Boolean}, {@link String}. * * @param args * @param name * @param defaultValue * @return The argument value at name as a boolean */ public static boolean getBool(IArgs args, String name, boolean defaultValue) { if (args == null) { return defaultValue; } Object optionValue = args.get(name); if (optionValue == null) { return defaultValue; } if (optionValue instanceof Boolean) { return ((Boolean) optionValue).booleanValue(); } if (optionValue instanceof String) { String optionString = (String) optionValue; return Converter.asBoolean(optionString, defaultValue); } return defaultValue; } /** * The argument value at name as a byte. If the argument value * is not provided or not convertible, defaultValueis returned. *

* This method performs the necessary casts and conversions. Supported input * types are null, {@link Number}, {@link String}. * * @param args * @param name * @param defaultValue * @return The argument value at name as a byte. */ public static byte getByte(IArgs args, String name, byte defaultValue) { if (args == null) { return defaultValue; } Object value = args.get(name); if (value instanceof Number) { return ((Number) value).byteValue(); } if (value instanceof String) { try { return Byte.parseByte((String) value); } catch (NumberFormatException e) { return defaultValue; } } return defaultValue; } /** * The argument value at name as a char. If the argument value * is not provided or not convertible, defaultValueis returned. *

* This method performs the necessary casts and conversions. Supported input * types are null, {@link Character}, {@link String}. * * @param args * @param name * @param defaultValue * @return The argument value at name as a char. */ public static char getChar(IArgs args, String name, char defaultValue) { if (args == null) { return defaultValue; } Object value = args.get(name); if (value instanceof Character) { return ((Character) value).charValue(); } if (value instanceof String) { String valueString = (String) value; if (valueString.length() > 0) { return valueString.charAt(0); } } return defaultValue; } /** * The argument value at name as a char[]. If the argument * value is not provided or not convertible, defaultValueis * returned. *

* This method performs the necessary casts and conversions. Supported input * types are null, {@link String}, char[]. Unlike the other * conversion methods, this one throws an IllegalArgumentException, if the * value is not of type String or char[]. * * @param args * @param name * @param defaultValue * @exception IllegalArgumentException * if value is not of type String or * char[] * @return The argument value at name as a {@link String}. */ public static char[] getCharArray(IArgs args, String name, char[] defaultValue) throws IllegalArgumentException { if (args == null) { return defaultValue; } Object optionValue = args.get(name); if (optionValue == null) { return defaultValue; } if (optionValue instanceof char[]) { return (char[]) optionValue; } if (optionValue instanceof String) { return ((String) optionValue).toCharArray(); } throw new IllegalArgumentException("argument '" + name //$NON-NLS-1$ + "' must be of type string or char[]"); //$NON-NLS-1$ } /** * The argument value at name as a {@link Class}. If the * argument value is not provided or not convertible, * defaultValueis returned. *

* This method performs the necessary casts and conversions. Supported input * types are null, {@link Boolean}, {@link String}. * * @param args * @param name * @param defaultValue * @return The argument value at name as a {@link Class}. */ public static Class getClass(IArgs args, String name, Class defaultValue) { if (args == null) { return defaultValue; } Object optionValue = args.get(name); if (optionValue == null) { return defaultValue; } if (optionValue instanceof Class) { return (Class) optionValue; } if (optionValue instanceof String) { String optionString = (String) optionValue; try { return ClassTools.createClass(optionString, Object.class, null); } catch (Exception e) { return defaultValue; } } return defaultValue; } /** * The argument value at name as a {@link Date}. If the * argument value is not provided or not convertible, * defaultValueis returned. *

* This method performs the necessary casts and conversions. Supported input * types are null, {@link Date}, {@link String}. * * @param args * @param name * @param defaultValue * @return The argument value at name as a {@link Date}. */ public static Date getDate(IArgs args, String name, Date defaultValue) { if (args == null) { return defaultValue; } Object optionValue = args.get(name); if (optionValue == null) { return defaultValue; } if (optionValue instanceof Date) { return (Date) optionValue; } if (optionValue instanceof String) { String optionString = (String) optionValue; try { return DateFormat.getInstance().parse(optionString); } catch (ParseException e) { return defaultValue; } } return defaultValue; } /** * The argument value at name as a {@link EnumItem}. If the * argument value is not provided or not convertible, the enumeration * default value is returned. *

* This method performs the necessary casts and conversions. Supported input * types are null, {@link EnumItem}, {@link String}. * * @param args * @param meta * @param name * @return The argument value at name as a {@link EnumItem}. */ public static T getEnumItem(IArgs args, EnumMeta meta, String name) { if (args == null) { return meta.getDefault(); } Object optionValue = args.get(name); if (optionValue == null) { return meta.getDefault(); } if (optionValue instanceof EnumItem) { return (T) optionValue; } if (optionValue instanceof String) { String optionString = (String) optionValue; return meta.getItemOrDefault(optionString); } return meta.getDefault(); } /** * The argument value at name as a {@link EnumItem}. If the * argument value is not provided or not convertible, the enumeration item * with the id defaultValuee is returned. *

* This method performs the necessary casts and conversions. Supported input * types are null, {@link EnumItem}, {@link String}. * * @param args * @param meta * @param name * @return The argument value at name as a {@link EnumItem}. */ public static T getEnumItem(IArgs args, EnumMeta meta, String name, String defaultValue) { if (args == null) { return meta.getItemOrDefault(defaultValue); } Object optionValue = args.get(name); if (optionValue == null) { return meta.getItemOrDefault(defaultValue); } if (optionValue instanceof EnumItem) { return (T) optionValue; } if (optionValue instanceof String) { String optionString = (String) optionValue; return meta.getItemOrDefault(optionString); } return meta.getItemOrDefault(defaultValue); } /** * The argument value at name as a {@link File}. If the * argument value is not provided or not convertible, * defaultValueis returned. *

* This method performs the necessary casts and conversions. Supported input * types are null, {@link File}, {@link String}, * {@link ILocator}. * * @param args * @param name * @param defaultValue * @return The argument value at name as a {@link Date}. */ public static File getFile(IArgs args, String name, File defaultValue) { if (args == null) { return defaultValue; } Object value = args.get(name); if (value instanceof File) { return (File) value; } if (value instanceof String) { return new File((String) value); } if (value instanceof FileLocator) { return ((FileLocator) value).getFile(); } if (value instanceof ILocator) { return new File(((ILocator) value).getFullName()); } return defaultValue; } /** * The argument value at name as a float. If the argument value * is not provided or not convertible, defaultValueis returned. *

* This method performs the necessary casts and conversions. Supported input * types are null, {@link Number}, {@link String}. * * @param args * @param name * @param defaultValue * @return The argument value at name as a float. */ public static float getFloat(IArgs args, String name, float defaultValue) { if (args == null) { return defaultValue; } Object value = args.get(name); if (value instanceof Number) { return ((Number) value).floatValue(); } if (value instanceof String) { String stringValue = (String) value; if (stringValue.indexOf("%") != -1) { //$NON-NLS-1$ try { Number result = NumberFormat.getPercentInstance().parse( stringValue); return result.floatValue(); } catch (ParseException e) { // todo log warning return defaultValue; } } try { return Float.parseFloat(stringValue); } catch (NumberFormatException e) { // todo log warning return defaultValue; } } return defaultValue; } /** * The argument value at name as a int. If the argument value * is not provided or not convertible, defaultValueis returned. *

* This method performs the necessary casts and conversions. Supported input * types are null, {@link Number}, {@link String}. * * @param args * @param name * @param defaultValue * @return The argument value at name as a int. */ public static int getInt(IArgs args, String name, int defaultValue) { if (args == null) { return defaultValue; } Object value = args.get(name); if (value instanceof Number) { return ((Number) value).intValue(); } if (value instanceof String) { try { return Integer.parseInt((String) value); } catch (NumberFormatException e) { return defaultValue; } } return defaultValue; } /** * The argument value at name as a {@link ILocator}. If the * argument value is not provided or not convertible, * defaultValueis returned. *

* This method performs the necessary casts and conversions. Supported input * types are null, {@link ILocator}, {@link String}, * {@link File} * * @param args * @param name * @param defaultValue * @param factory * @return The argument value at name as a {@link ILocator}. */ public static ILocator getLocator(IArgs args, String name, ILocator defaultValue, ILocatorFactory factory) { if (args == null) { return defaultValue; } Object optionValue = args.get(name); return createLocator(optionValue, defaultValue, factory); } /** * The argument value at name as a List. If the * argument value is not provided, nullis returned. *

* This method performs the necessary casts and conversions. Supported input * types are {@link Collection} of {@link ILocator}, {@link String} and * {@link File}. * * @param args * @param name * @param factory * @return The argument value at name as a {@link List}. */ public static List getLocators(IArgs args, String name, ILocatorFactory factory) { if (args == null) { return null; } Object optionValue = args.get(name); if (optionValue == null) { return null; } List locators = new ArrayList(); if (optionValue instanceof Collection) { for (Iterator i = ((Collection) optionValue).iterator(); i .hasNext();) { Object candidate = i.next(); ILocator locator = createLocator(candidate, null, factory); if (locator != null) { locators.add(locator); } } } else { ILocator locator = createLocator(optionValue, null, factory); if (locator != null) { locators.add(locator); } } return locators; } /** * The argument value at name as a {@link Map}. If the argument * value is not provided or not convertible, defaultValueis * returned. *

* This method performs the necessary casts and conversions. Supported input * types are null, {@link Map}, {@link String}. * * @param args * @param name * @param defaultValue * @return The argument value at name as a {@link Map}. */ public static Map getMap(IArgs args, String name, Map defaultValue) { if (args == null) { return defaultValue; } Object optionValue = args.get(name); if (optionValue == null) { return defaultValue; } if (optionValue instanceof Map) { return (Map) optionValue; } if (optionValue instanceof String) { return Converter.asMap((String) optionValue); } return defaultValue; } /** * The argument value at name as a {@link Object}. If the * argument value is not provided or not convertible, * defaultValueis returned. *

* This method performs the necessary casts and conversions. Supported input * types are null, {@link Object}. * * @param args * @param name * @param defaultValue * @return The argument value at name as a {@link Object}. */ public static Object getObject(IArgs args, String name, Object defaultValue) { if (args == null) { return defaultValue; } Object optionValue = args.get(name); if (optionValue == null) { return defaultValue; } return optionValue; } /** * The argument value at name as a {@link Point2D}. If the * argument value is not provided or not convertible, * defaultValueis returned. *

* This method performs the necessary casts and conversions. Supported input * types are null, {@link Point2D}, {@link String}. * * @param args * @param name * @param defaultValue * @return The argument value at name as a {@link Point2D}. */ public static Point2D getPoint(IArgs args, String name, Point2D defaultValue) { if (args == null) { return defaultValue; } Object optionValue = args.get(name); if (optionValue == null) { return defaultValue; } if (optionValue instanceof Point2D) { return (Point2D) optionValue; } if (optionValue instanceof String) { String optionString = (String) optionValue; String[] coords = optionString.split("[x*@]"); //$NON-NLS-1$ if ((coords == null) || (coords.length != 2)) { return defaultValue; } try { float x = Float.parseFloat(coords[0]); float y = Float.parseFloat(coords[1]); return new Point2D.Float(x, y); } catch (NumberFormatException e) { return defaultValue; } } return defaultValue; } /** * The argument value at name as a {@link String}. If the * argument value is not provided or not convertible, * defaultValueis returned. *

* This method performs the necessary casts and conversions. Supported input * types are null, {@link String}, {@link Object}. * * @param args * @param name * @param defaultValue * @return The argument value at name as a {@link String}. */ public static String getString(IArgs args, String name, String defaultValue) { if (args == null) { return defaultValue; } Object optionValue = args.get(name); if (optionValue == null) { return defaultValue; } if (optionValue instanceof String) { return (String) optionValue; } if (optionValue instanceof char[]) { return new String((char[]) optionValue); } return String.valueOf(optionValue); } /** * Create a new argument name from name by prefixing with * prefix. * * @param prefix * @param name * @return The new argument name. */ public static String prefix(String prefix, String name) { if (name == null) { return null; } if ((prefix == null) || (prefix.length() == 0)) { return name; } return prefix + Character.toUpperCase(name.charAt(0)) + name.substring(1); } /** * Cast or convert value to an {@link IArgs}. * * @param value * @return The {@link IArgs} created from value. */ public static IArgs toArgs(Object value) { if (value instanceof IArgs) { return (IArgs) value; } if (value instanceof String) { value = Converter.asMap((String) value); } if (value instanceof Map) { return new Args((Map) value); } if (value instanceof List) { return new Args((List) value); } return Args.EMPTY; } /** * Convert the args to a {@link List}. * * @param args * @return The {@link List} representation of the args */ public static List toList(IArgs args) { List result = new ArrayList(); int i = args.size(); while (i > 0) { i--; result.add(args.get(i)); } return result; } /** * Convert the args to a {@link Map}. * * @param args * @return The {@link Map} representation of the args */ public static Map toMap(IArgs args) { Map result = new HashMap(); if (args != null) { for (Iterator it = args.names().iterator(); it.hasNext();) { String name = (String) it.next(); result.put(name, args.get(name)); } } return result; } /** * Create a printable {@link String} for args. * * @param args * @param prefix * @return */ synchronized public static String toString(IArgs args, String prefix) { if (visited == null) { visited = new HashSet(); nesting = 0; } if (visited.contains(args)) { return "...recursive..."; } if (nesting == 4) { return "...nested to deeply..."; } visited.add(args); nesting++; try { StringBuilder sb = new StringBuilder(); if (args.isNamed()) { // flat ones.... for (Iterator it = args.names().iterator(); it.hasNext();) { String name = (String) it.next(); Object value = args.get(name); if (!(value instanceof IArgs)) { toStringPlain(prefix, sb, name, value); } } // nested ones... for (Iterator it = args.names().iterator(); it.hasNext();) { String name = (String) it.next(); Object value = args.get(name); if (value instanceof IArgs) { toStringArgs(prefix, sb, name, (IArgs) value); } } } else { for (int i = 0; i < args.size(); i++) { Object value = args.get(i); if (value instanceof IArgs) { toStringArgs(prefix, sb, "" + i, (IArgs) value); } else { toStringPlain(prefix, sb, "" + i, value); } } } return sb.toString(); } finally { nesting--; if (nesting == 0) { visited = null; } } } protected static void toStringArgs(String prefix, StringBuilder sb, String name, IArgs value) { for (int i = 1; i < nesting; i++) { sb.append(" "); } sb.append(name); sb.append(" = "); sb.append("{"); sb.append("\n"); sb.append(toString(value, prefix)); sb.append("\n"); for (int i = 1; i < nesting; i++) { sb.append(" "); } sb.append("}"); sb.append("\n"); } protected static void toStringPlain(String prefix, StringBuilder sb, String name, Object value) { for (int i = 1; i < nesting; i++) { sb.append(" "); } sb.append(name); sb.append(" = "); sb.append(StringTools.safeString(value)); sb.append("\n"); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/NullFunctor.java0000644000175000017500000000366111006026312025602 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * A common utility {@link IFunctor} doing just nothing. */ public class NullFunctor extends CommonFunctor { /* * (non-Javadoc) * * @see de.intarsys.tools.functor.IFunctor#perform(de.intarsys.tools.functor.IFunctorCall) */ public Object perform(IFunctorCall call) throws FunctorInvocationException { return null; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/DeclarationBlock.java0000644000175000017500000000661411024145276026543 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * A generic implementation for {@link IDeclarationBlock}. * */ public class DeclarationBlock extends Declaration implements IDeclarationBlock { final public static IDeclarationBlock EMPTY = new EmptyDeclarationBlock(); private IDeclaration[] declarations; public DeclarationBlock(Object declarationContext) { super(declarationContext); declarations = new IDeclaration[0]; } public DeclarationBlock(Object declarationContext, IDeclaration[] declarations) { super(declarationContext); this.declarations = declarations; } public IFunctorCall accept(IFunctorCall call) throws DeclarationException { IFunctorCall result = call; for (int i = 0; i < declarations.length; i++) { IDeclaration declaration = declarations[i]; result = declaration.accept(result); } return result; } public void addDeclaration(IDeclaration declaration) { IDeclaration[] newDeclarations = new IDeclaration[declarations.length + 1]; System.arraycopy(declarations, 0, newDeclarations, 0, declarations.length); newDeclarations[declarations.length] = declaration; declarations = newDeclarations; } public IDeclaration[] getDeclarations() { return declarations; } @Override public boolean isBlock() { return true; } public boolean removeDeclaration(IDeclaration declaration) { for (int i = 0; i < declarations.length; i++) { if (declarations[i] == declaration) { IDeclaration[] newDeclarations = new IDeclaration[declarations.length - 1]; System.arraycopy(declarations, 0, newDeclarations, 0, i); System.arraycopy(declarations, i + 1, newDeclarations, i, declarations.length - i - 1); declarations = newDeclarations; return true; } } return false; } public int size() { return declarations.length; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/IFunctorHandler.java0000644000175000017500000000424310765277202026374 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * An object that supports execution of functors. */ public interface IFunctorHandler { /** * Perform the encapsulated business logic for functor * * @param functor * @param call * The call context * @return The behavior execution result. * * @throws FunctorInvocationException * An exception that raised while executing the business logic * will be wrapped in a FunctorInvocationException. */ public Object perform(IFunctor functor, IFunctorCall call) throws FunctorInvocationException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/FunctorInvocationException.java0000644000175000017500000000425110751651500030665 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * An exception while performing an {@link IFunctor}. * */ public class FunctorInvocationException extends Exception { /** * */ public FunctorInvocationException() { super(); } /** * @param message */ public FunctorInvocationException(String message) { super(message); } /** * @param message * @param cause */ public FunctorInvocationException(String message, Throwable cause) { super(message, cause); } /** * @param cause */ public FunctorInvocationException(Throwable cause) { this(cause.getMessage(), cause); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/DeclaredArgs.java0000644000175000017500000001530411256644772025673 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; import java.util.Set; /** * This {@link IArgs} implementation allows the declaration of arguments. *

* The declaration is matched against the actual arguments defined in * args. The declaration defines a mapping from indexed to named * and AND vice versa. *

* If we have indexed args, a declaration associates a name with the argument in * the sequence of declaration. *

* If we have named args, a declaration defines the index of the argument with * the same name. * */ public class DeclaredArgs implements IArgs { public static DeclaredArgs createStrict(IArgs args) { DeclaredArgs result = new DeclaredArgs(args); result.setLazy(false); result.setStrict(true); return result; } public static DeclaredArgs createStrictIfDeclared(IArgs args) { DeclaredArgs result = new DeclaredArgs(args); result.setLazy(true); result.setStrict(true); return result; } public static DeclaredArgs createTransparent(IArgs args) { DeclaredArgs result = new DeclaredArgs(args); result.setLazy(false); result.setStrict(false); return result; } private IArgs argsIn; private IArgs argsOut; private Args declaredArgs; private boolean lazy = true; private boolean strict = false; protected DeclaredArgs(IArgs args) { this.argsIn = args; this.argsOut = args; } public void add(Object object) { switchArgs(); declaredArgs.add(object); } public void clear() { switchArgs(); declaredArgs.clear(); } protected void declare(IFunctorCall call, ArgumentDeclaration argDecl) throws DeclarationException { declare(call, argDecl.getName(), argDecl.getIndex(), argDecl .getDefaultFunctor()); } protected void declare(IFunctorCall call, String name, int index, IFunctor defaultFunctor) throws DeclarationException { switchArgs(); Object value = null; if (argsIn.isNamed()) { value = argsIn.get(name); if (value == null && argsIn.isDefined(name)) { // avoid overwriting a client defined null value return; } } else if (argsIn.isIndexed()) { value = argsIn.get(index); if (value == null && argsIn.isDefined(index)) { return; } } if (value instanceof IArgs || value == null) { // if our value is undefined we compute and assign the result of the // default functor // // if our value is an argument list itself, we must check for nested // declarations // Object defaultValue = null; if (defaultFunctor != null) { try { defaultValue = defaultFunctor.perform(call); } catch (FunctorInvocationException e) { throw new DeclarationException(e); } } if (defaultValue instanceof IDeclaration[]) { if (value == null) { value = Args.create(); } DeclaredArgs childDeclaredArgs = new DeclaredArgs((IArgs) value); childDeclaredArgs.setLazy(isLazy()); childDeclaredArgs.setStrict(isStrict()); IDeclaration[] declarations = (IDeclaration[]) defaultValue; for (int i = 0; i < declarations.length; i++) { IDeclaration declaration = declarations[i]; if (!(declaration instanceof ArgumentDeclaration)) { throw new DeclarationException( "ArgumentDeclaration expected"); } ArgumentDeclaration argDecl = (ArgumentDeclaration) declaration; childDeclaredArgs.declare(call, argDecl); } value = childDeclaredArgs; } else { if (value == null) { value = defaultValue; } } } declaredArgs.put(index, value); declaredArgs.put(name, value); } public Object get(int pIndex) { return argsOut.get(pIndex); } public Object get(int pIndex, Object defaultValue) { return argsOut.get(pIndex, defaultValue); } public Object get(String name) { return argsOut.get(name); } public Object get(String name, Object defaultValue) { return argsOut.get(name, defaultValue); } public IArgs getArgsIn() { return argsIn; } public boolean isDefined(int index) { return argsOut.isDefined(index); } public boolean isDefined(String name) { return argsOut.isDefined(name); } public boolean isIndexed() { return true; } protected boolean isLazy() { return lazy; } public boolean isNamed() { return true; } protected boolean isStrict() { return strict; } public Set names() { return argsOut.names(); } public void put(int index, Object value) { switchArgs(); declaredArgs.put(index, value); } public void put(String name, Object value) { switchArgs(); declaredArgs.put(name, value); } protected void setLazy(boolean lazy) { this.lazy = lazy; } protected void setStrict(boolean strict) { this.strict = strict; if (strict && !lazy) { switchArgs(); } } public int size() { return argsOut.size(); } protected void switchArgs() { if (argsIn != argsOut) { return; } declaredArgs = new Args(); if (strict) { argsOut = declaredArgs; } else { argsOut = new ChainedArgs(declaredArgs, argsIn); } } @Override public String toString() { return ArgTools.toString(this, ""); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/SimpleFunctorCallFactory.java0000644000175000017500000000053511355111526030253 0ustar twernertwernerpackage de.intarsys.tools.functor; import de.intarsys.tools.reflect.ObjectCreationException; public class SimpleFunctorCallFactory implements IFunctorCallFactory { public IFunctorCall createFunctorCall(IFunctor functor, Object receiver, IArgs args) throws ObjectCreationException { return new FunctorCall(receiver, args); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/FunctorCall.java0000644000175000017500000000573311411055572025557 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * Generic implementation of {@link IFunctorCall}. * */ public class FunctorCall implements IFunctorCall { /** * Create an {@link IFunctorCall} with receiver as the receiver * and the indexed arguments. * * @param receiver * The receiver for the call. * @param arguments * The indexed arguments for the call. * @return The new {@link IFunctorCall} */ public static FunctorCall create(Object receiver, Object... arguments) { Args args = new Args(arguments); return new FunctorCall(receiver, args); } /** * Create an {@link IFunctorCall} with receiver as the receiver * and no arguments. * * @param receiver * The receiver for the call. * @return The new {@link IFunctorCall} */ public static FunctorCall noargs(Object receiver) { return new FunctorCall(receiver, Args.EMPTY); } private IArgs args; private IArgs currentArgs; private Object receiver; public FunctorCall(Object receiver, IArgs args) { super(); this.args = args; this.currentArgs = args; this.receiver = receiver; } public IArgs getArgs() { return currentArgs; } public Object getReceiver() { return receiver; } public void setArgs(IArgs args) { currentArgs = args; } public void setReceiver(Object receiver) { this.receiver = receiver; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/ArgumentDeclaration.java0000644000175000017500000000603411025430140027253 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * An argument declaration supporting argument reordering/ naming and default * values. * */ public class ArgumentDeclaration extends DeclarationElement implements IArgumentDeclaration { final private IFunctor defaultFunctor; final private int index; public ArgumentDeclaration(Object declarationContext, String name, String modifiers, int index, IDeclaration[] nestedDeclarations) { super(declarationContext, name, modifiers, nestedDeclarations); this.defaultFunctor = new ConstantFunctor(nestedDeclarations); this.index = index; } public ArgumentDeclaration(Object declarationContext, String name, String modifiers, int index, IFunctor defaultFunctor) { super(declarationContext, name, modifiers); this.defaultFunctor = defaultFunctor; this.index = index; } public IFunctorCall accept(IFunctorCall call) throws DeclarationException { IArgs currentArgs = call.getArgs(); DeclaredArgs declaredArgs = null; if (currentArgs instanceof DeclaredArgs) { declaredArgs = (DeclaredArgs) currentArgs; } else { declaredArgs = createDeclaredArgs(currentArgs); call.setArgs(declaredArgs); } declaredArgs.declare(call, this); return call; } protected DeclaredArgs createDeclaredArgs(IArgs currentArgs) { return DeclaredArgs.createTransparent(currentArgs); } public IFunctor getDefaultFunctor() { return defaultFunctor; } public int getIndex() { return index; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/DeclarationElement.java0000644000175000017500000000607611411055572027103 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * A common superclass for {@link IDeclarationElement} instances. This one has a * very simple implementation for modifiers. Only the presence of the modifier * string fragment in declared modifier string is checked. * */ abstract public class DeclarationElement extends Declaration implements IDeclarationElement, IDeclarationBlock { final private String modifiers; final private String name; final private IDeclaration[] nestedDeclarations; public DeclarationElement(Object declarationContext, String name, String modifiers) { super(declarationContext); this.modifiers = modifiers; this.name = name; this.nestedDeclarations = null; } public DeclarationElement(Object declarationContext, String name, String modifiers, IDeclaration[] nestedDeclarations) { super(declarationContext); this.modifiers = modifiers; this.name = name; this.nestedDeclarations = nestedDeclarations; } public IDeclaration[] getDeclarations() { return nestedDeclarations; } public String getName() { return name; } public boolean hasModifier(String modifier) { if (modifiers == null) { return false; } return modifiers.indexOf(modifier) >= 0; } @Override public boolean isBlock() { return size() > 0; } public int size() { return nestedDeclarations == null ? 0 : nestedDeclarations.length; } @Override public String toString() { return "declaration <'" + getName() + "'> [" + modifiers + "]"; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/Args.java0000644000175000017500000001425211256644772024250 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * A concrete generic implementation for {@link IArgs}. * */ public class Args implements IArgs { public static final IArgs EMPTY = new EmptyArgs(); public static Args create() { return new Args(); } public static Args createIndexed() { List list = new ArrayList(); return new Args(list); } public static Args createIndexed(Object p1) { List list = new ArrayList(); list.add(p1); return new Args(list); } public static Args createIndexed(Object p1, Object p2) { List list = new ArrayList(); list.add(p1); list.add(p2); return new Args(list); } public static Args createIndexed(Object p1, Object p2, Object p3) { List list = new ArrayList(); list.add(p1); list.add(p2); list.add(p3); return new Args(list); } public static Args createNamed() { Map map = new HashMap(); return new Args(map); } public static Args createNamed(String key, Object value) { Map map = new HashMap(); map.put(key, value); return new Args(map); } public static Args createNamed(String key1, Object value1, String key2, Object value2) { Map map = new HashMap(); map.put(key1, value1); map.put(key2, value2); return new Args(map); } private Map valueMap; private List valueList; public Args() { super(); } public Args(IArgs args) { super(); if (args == null) { return; } // we can support both... if (args.isIndexed()) { valueList = new ArrayList(); for (int i = 0; i < args.size(); i++) { valueList.add(args.get(i)); } } if (args.isNamed()) { valueMap = new HashMap(); for (Iterator i = args.names().iterator(); i.hasNext();) { String name = (String) i.next(); valueMap.put(name, args.get(name)); } } } public Args(List values) { super(); this.valueList = values; } public Args(Map values) { super(); this.valueMap = values; } public Args(Object[] values) { super(); if (values != null) { // its common for values to be null, for example in java reflection // code // -> support it this.valueList = Arrays.asList(values); } } public void add(Object object) { if (valueList == null) { valueList = new ArrayList(); } valueList.add(object); } public void clear() { if (valueList != null) { valueList.clear(); } if (valueMap != null) { valueMap.clear(); } } public IArgs declare(String name, int index, Object value) { put(index, value); put(name, value); return this; } public Object get(int index) { if ((valueList == null) || index < 0 || (valueList.size() <= index)) { return null; } return valueList.get(index); } public Object get(int index, Object defaultValue) { if ((valueList == null) || index < 0 || (valueList.size() <= index)) { return defaultValue; } return valueList.get(index); } public Object get(String name) { if (valueMap == null) { return null; } return valueMap.get(name); } public Object get(String name, Object defaultValue) { if (valueMap == null) { return defaultValue; } Object result = valueMap.get(name); if (result == null && !valueMap.containsKey(name)) { return defaultValue; } return result; } public boolean isDefined(int index) { if (valueList == null) { return false; } return index >= 0 && index < valueList.size(); } public boolean isDefined(String name) { if (valueMap == null) { return false; } return valueMap.containsKey(name); } public boolean isIndexed() { return valueList != null; } public boolean isNamed() { return valueMap != null; } public Set names() { if (valueMap == null) { return Collections.EMPTY_SET; } return valueMap.keySet(); } public void put(int index, Object value) { if (valueList == null) { valueList = new ArrayList(); } while (index >= valueList.size()) { valueList.add(null); } valueList.set(index, value); } public void put(String name, Object value) { if (valueMap == null) { valueMap = new HashMap(); } valueMap.put(name, value); } public int size() { if (valueList != null) { return valueList.size(); } if (valueMap != null) { return valueMap.size(); } return 0; } @Override public String toString() { return ArgTools.toString(this, ""); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/IArgumentDeclaration.java0000644000175000017500000000335311024145300027365 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * The declaration for an argument to an {@link IFunctorCall}. * */ public interface IArgumentDeclaration extends IDeclarationElement { } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/ChainedArgs.java0000644000175000017500000001414711256644772025527 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; import java.util.HashSet; import java.util.Set; /** * An {@link IArgs} implementation allowing to concat two {@link IArgs} * together. Lookup will be performed in "args" first. If nothing is found, * lookup is done in "fallbackArgs". * */ public class ChainedArgs implements IArgs { private IArgs args; private IArgs fallbackArgs; /** * Create new {@link ChainedArgs} where args are always * looked up first. If lookup fails, fallbackArgs are used. * * @param args * The main {@link IArgs} to use for lookup * @param fallbackArgs * The fallback {@link IArgs} for lookup */ public ChainedArgs(IArgs args, IArgs fallbackArgs) { super(); this.args = args; this.fallbackArgs = fallbackArgs; } public void add(Object object) { args.add(object); } public void clear() { args.clear(); } /* * (non-Javadoc) * * @see de.intarsys.tools.functor.IArgs#get(int) */ public Object get(int index) { Object result = args.get(index); if (result == null) { return fallbackArgs.get(index); } else if (result instanceof IArgs) { Object fallbackResult = fallbackArgs.get(index); if (fallbackResult instanceof IArgs) { return new ChainedArgs((IArgs) result, (IArgs) fallbackResult); } } return result; } /* * (non-Javadoc) * * @see de.intarsys.tools.functor.IArgs#get(int, java.lang.Object) */ public Object get(int index, Object defaultValue) { Object result = args.get(index); if (result == null) { return fallbackArgs.get(index, defaultValue); } else if (result instanceof IArgs) { Object fallbackResult = fallbackArgs.get(index); if (fallbackResult instanceof IArgs) { return new ChainedArgs((IArgs) result, (IArgs) fallbackResult); } } return result; } /* * (non-Javadoc) * * @see de.intarsys.tools.functor.IArgs#get(java.lang.String) */ public Object get(String name) { Object result = args.get(name); if (result == null) { if (!args.isDefined(name)) { result = fallbackArgs.get(name); } } else if (result instanceof IArgs) { Object fallbackResult = fallbackArgs.get(name); if (fallbackResult instanceof IArgs) { result = new ChainedArgs((IArgs) result, (IArgs) fallbackResult); } } return result; } /* * (non-Javadoc) * * @see de.intarsys.tools.functor.IArgs#get(java.lang.String, * java.lang.Object) */ public Object get(String name, Object defaultValue) { Object result = args.get(name); if (result == null) { if (!args.isDefined(name)) { result = fallbackArgs.get(name, defaultValue); } } else if (result instanceof IArgs) { Object fallbackResult = fallbackArgs.get(name); if (fallbackResult instanceof IArgs) { result = new ChainedArgs((IArgs) result, (IArgs) fallbackResult); } } return result; } /** * The main (primary) {@link IArgs}. * * @return The main (primary) {@link IArgs}. */ public IArgs getArgs() { return args; } /** * The fallback (secondary) {@link IArgs}; * * @return The fallback (secondary) {@link IArgs}; */ public IArgs getFallbackArgs() { return fallbackArgs; } public boolean isDefined(int index) { if (args.isDefined(index)) { return true; } return fallbackArgs.isDefined(index); } public boolean isDefined(String name) { if (args.isDefined(name)) { return true; } return fallbackArgs.isDefined(name); } /* * (non-Javadoc) * * @see de.intarsys.tools.functor.IArgs#isIndexed() */ public boolean isIndexed() { return args.isIndexed() || fallbackArgs.isIndexed(); } /* * (non-Javadoc) * * @see de.intarsys.tools.functor.IArgs#isNamed() */ public boolean isNamed() { return args.isNamed() || fallbackArgs.isNamed(); } /* * (non-Javadoc) * * @see de.intarsys.tools.functor.IArgs#names() */ public Set names() { Set names = new HashSet(args.names()); names.addAll(fallbackArgs.names()); return names; } public void put(int index, Object value) { args.put(index, value); } public void put(String name, Object value) { args.put(name, value); } /* * (non-Javadoc) * * @see de.intarsys.tools.functor.IArgs#size() */ public int size() { if (isIndexed()) { return Math.max(args.size(), fallbackArgs.size()); } return names().size(); } @Override public String toString() { return ArgTools.toString(this, ""); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/EventFunctorCallFactory.java0000644000175000017500000000132611355113426030103 0ustar twernertwernerpackage de.intarsys.tools.functor; import de.intarsys.tools.event.RequestEvent; import de.intarsys.tools.event.IRequestEvent; import de.intarsys.tools.facade.FacadeTools; import de.intarsys.tools.reflect.ObjectCreationException; public class EventFunctorCallFactory implements IFunctorCallFactory { public IFunctorCall createFunctorCall(IFunctor functor, Object receiver, IArgs args) throws ObjectCreationException { RequestEvent event = new RequestEvent(receiver); event.setTarget(args.get("event.target")); event.setArgs(args); args.put(IRequestEvent.ARG_EVENT, FacadeTools.createFacade(event)); args.put(IRequestEvent.ARG_JEVENT, event); return new FunctorCall(receiver, args); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/IDeclarationElement.java0000644000175000017500000000504511024145276027210 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * A concrete named declaration. An {@link IDeclarationElement} may have * optional modifiers, supporting fine tuning of its behavior. * */ public interface IDeclarationElement extends IDeclaration { /** * An optional name for the declaration element. * * @return An optional name for the declaration element. */ public String getName(); /** * true if the declaration has the requested modifier. *

* An implementation is free to support modifiers and define their * respective semantics. *

* An example for a modifier may be "persistent" to indicate the * implementation should store argument values to be able to present them * again in a later call (in a wizard for example). * * @param modifier * The modifier name. * * @return true if the declaration has the requested * modifier. * */ public boolean hasModifier(String modifier); } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/CommonFunctor.java0000644000175000017500000000332510751651500026126 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * A common superclass for implementing {@link IFunctor}. */ abstract public class CommonFunctor implements IFunctor { } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/IFunctorCallFactory.java0000644000175000017500000000407511411055572027216 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; import de.intarsys.tools.reflect.ObjectCreationException; /** * A factory for {@link IFunctorCall} objects. * */ public interface IFunctorCallFactory { /** * Create a new {@link IFunctorCall}. * * @param functor * @param receiver * @param args * * @return The new {@link IFunctorCall} * @throws ObjectCreationException */ public IFunctorCall createFunctorCall(IFunctor functor, Object receiver, IArgs args) throws ObjectCreationException; }libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/DeclarationException.java0000644000175000017500000000374711024145276027453 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * An exception while accepting a declaration. * */ public class DeclarationException extends Exception { public DeclarationException() { } public DeclarationException(String message) { super(message); } public DeclarationException(String message, Throwable cause) { super(message, cause); } public DeclarationException(Throwable cause) { super(cause); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/IDeclaration.java0000644000175000017500000000636611024145276025705 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * A declaration allows to modify the state and or behavior of an * {@link IFunctorCall}. The {@link IDeclaration} is attached to an object * owning an {@link IFunctor} and should be executed against the * {@link IFunctorCall} prior to performing the call. *

* An example for a declaration is {@link IArgumentDeclaration}, allowing for * argument naming and ordering and to provide default values when an argument * is missing. *

* Syntax, semantics and application to the {@link IFunctorCall} of declarations * are up to the client. * */ public interface IDeclaration { /** * Apply this declaration to call. *

* The semantics of this method is up to the designer. * * @param call * The {@link IFunctorCall} to be modified. * @return The modified or new {@link IFunctorCall}. * * @throws DeclarationException */ public IFunctorCall accept(IFunctorCall call) throws DeclarationException; /** * An optional declaration context. This may be for example the object that * will launch the {@link IFunctorCall} later and has parsed some * declarations on startup. * * @return An optional declaration context. */ public Object getDeclarationContext(); /** * true if this declaration has child elements itself. *

* A {@link IDeclarationElement} may be a {@link IDeclarationBlock}, * supporting nested declarations. You should not use "instanceof * IDeclarationBlock" to check this behavior but this method. * * @return true if this declaration has child elements * itself. */ public boolean isBlock(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/EmptyArgs.java0000644000175000017500000000601611256644772025266 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; import java.util.HashSet; import java.util.Set; /** * Helper implementation for empty argument list. * */ public class EmptyArgs implements IArgs { public void add(Object object) { throw new UnsupportedOperationException("can't write to EmptyArgs"); } public void clear() { throw new UnsupportedOperationException("can't write to EmptyArgs"); } public IArgs declare(String name, int index, Object value) { Args result = new Args(); return result.declare(name, index, value); } public Object get(int index) { return null; } public Object get(int index, Object defaultValue) { return defaultValue; } public Object get(String name) { return null; } public Object get(String name, Object defaultValue) { return defaultValue; } public boolean isDefined(int index) { return false; } public boolean isDefined(String name) { return false; } public boolean isIndexed() { return false; } public boolean isNamed() { return false; } public Set names() { return new HashSet(); } public void put(int index, Object value) { throw new UnsupportedOperationException("can't write to EmptyArgs"); } public void put(String name, Object value) { throw new UnsupportedOperationException("can't write to EmptyArgs"); } public int size() { return 0; } @Override public String toString() { return ArgTools.toString(this, ""); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/FunctorTools.java0000644000175000017500000000516311030721456025777 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Tool class for handling functor specific tasks. * */ public class FunctorTools { private FunctorTools() { // tool class } public static boolean toBoolean(Object object) { if (object instanceof Boolean) { return ((Boolean) object).booleanValue(); } if (object instanceof String) { return ((String) object).equalsIgnoreCase("true"); } if (object instanceof Number) { return ((Number) object).intValue() != 0; } return false; } public static List toList(IArgs args) { List result = new ArrayList(); int len = args.size(); for (int i = 0; i < len; i++) { result.add(args.get(i)); } return result; } public static Map toMap(IArgs args) { Map result = new HashMap(); for (Iterator it = args.names().iterator(); it.hasNext();) { String name = (String) it.next(); result.put(name, args.get(name)); } return result; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/StandardFunctorOutlet.java0000644000175000017500000000143611276777320027650 0ustar twernertwernerpackage de.intarsys.tools.functor; import java.util.ArrayList; import java.util.List; public class StandardFunctorOutlet implements IFunctorOutlet { private List factories = new ArrayList(); public List getFunctorFactories() { return new ArrayList(factories); } public IFunctorFactory lookupFunctorFactory(String id) { if (id == null) { return null; } for (IFunctorFactory factory : factories) { if (factory.getId().equals(id)) { return factory; } } return null; } public void registerFunctorFactory(IFunctorFactory factory) { factories.add(factory); } public void unregisterFunctorFactory(IFunctorFactory factory) { factories.remove(factory); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/IArgs.java0000644000175000017500000001136411411055572024345 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; import java.util.Set; /** * The arguments for executing an {@link IFunctor} implementation. * */ public interface IArgs { /** * Generic option for the transport of IArgs. */ public static final String ARG_ARGS = "args"; //$NON-NLS-1$ public void add(Object object); public void clear(); /** * The argument at position index. * * @param index * The index of the argument to return. * * @return The argument at position index. */ public Object get(int index); /** * The argument at position index * * @param index * The index of the argument to return. * @param defaultValue * The default value to be returned if argument is not available. * * @return The argument at position index */ public Object get(int index, Object defaultValue); /** * The argument named name. * * @param name * The name of the argument to return. * * @return The argument named name . */ public Object get(String name); /** * The argument named name or the defaultValue if not * available. * * @param name * The name of the argument to return. * @param defaultValue * The default value to be returned if argument is not available. * * @return The argument named name */ public Object get(String name, Object defaultValue); /** * true if an argument at index is defined. * * @param index * @return true if an argument at index is * defined. */ public boolean isDefined(int index); /** * true if an argument named name is defined. * * @param name * @return true if an argument named name is * defined. */ public boolean isDefined(String name); /** * true if this argument list is indexed. This means its * elements are available via integer indexes. *

* This does NOT mean the arguments are not available via names - there are * implementations that can support both. * * @return true if this argument list is indexed. */ public boolean isIndexed(); /** * true if this argument list is named. This means its elements * are available via names. *

* This does NOT mean the arguments are not available via indexes - there * are implementations that can support both. * * @return true if this argument list is named. */ public boolean isNamed(); /** * The set of all argument names in the argument list if this argument list * is not indexed or null. * * @return The set of all argument names in the argument list if this * argument list is not indexed or null. */ public Set names(); public void put(int index, Object value); public void put(String name, Object value); /** * The total number of arguments. * * @return The total number of arguments. */ public int size(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/EchoFunctor.java0000644000175000017500000000364711006026312025552 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * Echo the incoming arguments. * */ public class EchoFunctor extends CommonFunctor { /* * (non-Javadoc) * * @see de.intarsys.tools.functor.IFunctor#perform(de.intarsys.tools.functor.IFunctorCall) */ public Object perform(IFunctorCall call) throws FunctorInvocationException { return call.getArgs(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/IFunctorOutlet.java0000644000175000017500000000053611276777320026300 0ustar twernertwernerpackage de.intarsys.tools.functor; import java.util.List; public interface IFunctorOutlet { public List getFunctorFactories(); public IFunctorFactory lookupFunctorFactory(String id); public void registerFunctorFactory(IFunctorFactory factory); public void unregisterFunctorFactory(IFunctorFactory factory); } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/IFunctorFactory.java0000644000175000017500000000417411411055572026422 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; import de.intarsys.tools.reflect.ObjectCreationException; /** * A factory for {@link IFunctor} objects. * */ public interface IFunctorFactory { /** * Create a new {@link IFunctor} object. * * @return The new {@link IFunctor}. * * @throws ObjectCreationException */ public IFunctor createFunctor() throws ObjectCreationException; /** * The unique id for this {@link IFunctorFactory} instance. *

* * @return The unique id for this {@link IFunctorFactory} instance. */ public String getId(); }libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/IFunctorCall.java0000644000175000017500000000467011052776536025702 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * An object representing the actual call of an {@link IFunctor}. This may be * used to transport call context and state such as arguments etc. * */ public interface IFunctorCall { /** * The arguments currently associated with the call. * * @return The arguments currently associated with the call. */ public IArgs getArgs(); /** * The receiver for the behavior implemented. * * @return The receiver for the behavior implemented. */ public Object getReceiver(); /** * Assign an argument list for the call. *

* This is for example useful when handling with declarations modifying the * original functor call. */ public void setArgs(IArgs args); /** * Assign a new receiver. * * @param receiver * The new receiver */ public void setReceiver(Object receiver); } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/FunctorFieldHandler.java0000644000175000017500000000702711363543130027221 0ustar twernertwernerpackage de.intarsys.tools.functor; import de.intarsys.tools.attribute.IAttributeSupport; import de.intarsys.tools.event.EventType; import de.intarsys.tools.event.INotificationListener; import de.intarsys.tools.event.INotificationSupport; import de.intarsys.tools.reflect.FieldAccessException; import de.intarsys.tools.reflect.IFieldHandler; import de.intarsys.tools.reflect.ObjectCreationException; public class FunctorFieldHandler implements IFieldHandler, INotificationSupport, IAttributeSupport { private IFunctor getter; private String name; private IFunctor setter; public FunctorFieldHandler() { } public FunctorFieldHandler(String name, IFunctor getter, IFunctor setter) { super(); this.name = name; this.getter = getter; this.setter = setter; } public void addNotificationListener(EventType type, INotificationListener listener) { if (getter instanceof INotificationSupport) { ((INotificationSupport) getter).addNotificationListener(type, listener); } } public Object getAttribute(Object key) { if (getter instanceof IAttributeSupport) { return ((IAttributeSupport) getter).getAttribute(key); } return null; } public IFunctor getGetter() { return getter; } public String getName() { return name; } public IFunctor getSetter() { return setter; } public Object getValue(Object object) throws FieldAccessException { if (getter == null) { return null; } IFunctorCall call; if (object instanceof IFunctorCallFactory) { try { call = ((IFunctorCallFactory) object).createFunctorCall(getter, object, Args.create()); } catch (ObjectCreationException e) { throw new FieldAccessException(getName(), e); } } else { call = new FunctorCall(object, Args.EMPTY); } try { return getter.perform(call); } catch (FunctorInvocationException e) { Throwable cause = e.getCause() == null ? e : e.getCause(); throw new FieldAccessException(getName(), cause); } } public Object removeAttribute(Object key) { if (getter instanceof IAttributeSupport) { return ((IAttributeSupport) getter).removeAttribute(key); } return null; } public void removeNotificationListener(EventType type, INotificationListener listener) { if (getter instanceof INotificationSupport) { ((INotificationSupport) getter).removeNotificationListener(type, listener); } } public Object setAttribute(Object key, Object value) { if (getter instanceof IAttributeSupport) { return ((IAttributeSupport) getter).setAttribute(key, value); } return null; } public void setGetter(IFunctor getter) { this.getter = getter; } public void setName(String name) { this.name = name; } public void setSetter(IFunctor setter) { this.setter = setter; } public Object setValue(Object object, Object value) throws FieldAccessException { if (setter == null) { return null; } IFunctorCall call; if (object instanceof IFunctorCallFactory) { try { call = ((IFunctorCallFactory) object).createFunctorCall(setter, object, Args.createIndexed(value)); } catch (ObjectCreationException e) { throw new FieldAccessException(getName(), e); } } else { call = new FunctorCall(object, Args.createIndexed(value)); } try { return setter.perform(call); } catch (FunctorInvocationException e) { Throwable cause = e.getCause() == null ? e : e.getCause(); throw new FieldAccessException(getName(), cause); } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/Declaration.java0000644000175000017500000000400611024145276025561 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * A common superclass for implementing {@link IDeclaration}. * */ public abstract class Declaration implements IDeclaration { final private Object declarationContext; public Declaration(Object declarationContext) { super(); this.declarationContext = declarationContext; } public Object getDeclarationContext() { return declarationContext; } public boolean isBlock() { return false; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/IFunctor.java0000644000175000017500000000465110751651500025071 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * An iconified behavior. The object implementing this interface is the * encapsulation of a business logic that can be executed using an {@link IArgs} * argument. *

* There is no statement about the concurrency or state restrictions of the * IFunctor in this interface. Such restrictions must be stated with the * implementation itself. */ public interface IFunctor { /** * Perform the encapsulated business logic in the context defined in "call". * * @param call * The call context * @return The behavior execution result. * * @throws FunctorInvocationException * An exception that raised while executing the business logic * will be wrapped in a FunctorInvocationException. */ public Object perform(IFunctorCall call) throws FunctorInvocationException; } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/IDeclarationBlock.java0000644000175000017500000000404211024145300026631 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * A group of {@link IDeclaration} instances. * */ public interface IDeclarationBlock extends IDeclaration { /** * The array of {@link IDeclaration} instances in this block. * * @return The array of {@link IDeclaration} instances in this block. */ public IDeclaration[] getDeclarations(); /** * The number of declarations in this block. * * @return The number of declarations in this block. */ public int size(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/ConstantFunctor.java0000644000175000017500000000415611006026310026457 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * A common utility {@link IFunctor} returning a constant value. */ public class ConstantFunctor extends CommonFunctor { private Object constant; public ConstantFunctor(Object constant) { this.constant = constant; } public Object getConstant() { return constant; } /* * (non-Javadoc) * * @see de.intarsys.tools.functor.IFunctor#perform(de.intarsys.tools.functor.IFunctorCall) */ public Object perform(IFunctorCall call) throws FunctorInvocationException { return getConstant(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/FunctorMethodHandler.java0000644000175000017500000000436211357307244027424 0ustar twernertwernerpackage de.intarsys.tools.functor; import de.intarsys.tools.attribute.IAttributeSupport; import de.intarsys.tools.reflect.IMethodHandler; import de.intarsys.tools.reflect.MethodInvocationException; import de.intarsys.tools.reflect.ObjectCreationException; public class FunctorMethodHandler implements IMethodHandler, IAttributeSupport { public static IMethodHandler create(IFunctor functor) { if (functor instanceof IMethodHandler) { return (IMethodHandler) functor; } else { if (functor instanceof INamedFunctor) { return new FunctorMethodHandler(((INamedFunctor) functor) .getId(), functor); } else { return new FunctorMethodHandler("unknown", functor); } } } final private IFunctor invoker; final private String name; public FunctorMethodHandler(String name, IFunctor invoker) { super(); this.name = name; this.invoker = invoker; } public Object getAttribute(Object key) { if (invoker instanceof IAttributeSupport) { return ((IAttributeSupport) invoker).getAttribute(key); } return null; } public IFunctor getInvoker() { return invoker; } public String getName() { return name; } public Object invoke(Object receiver, IArgs args) throws MethodInvocationException { if (invoker == null) { return null; } IFunctorCall call; if (receiver instanceof IFunctorCallFactory) { try { call = ((IFunctorCallFactory) receiver).createFunctorCall( invoker, receiver, args); } catch (ObjectCreationException e) { throw new MethodInvocationException(getName(), e); } } else { call = new FunctorCall(receiver, args); } try { return invoker.perform(call); } catch (FunctorInvocationException e) { Throwable cause = e.getCause() == null ? e : e.getCause(); throw new MethodInvocationException(getName(), cause); } } public Object removeAttribute(Object key) { if (invoker instanceof IAttributeSupport) { return ((IAttributeSupport) invoker).removeAttribute(key); } return null; } public Object setAttribute(Object key, Object value) { if (invoker instanceof IAttributeSupport) { return ((IAttributeSupport) invoker).setAttribute(key, value); } return null; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/IDeclarationSupport.java0000644000175000017500000000335211024145276027272 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * An object that may have declarations. * */ public interface IDeclarationSupport { public IDeclarationBlock getDeclarationBlock(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/functor/EmptyDeclarationBlock.java0000644000175000017500000000416211031114214027540 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.functor; /** * Helper implementation for an empty declaration block. * */ public class EmptyDeclarationBlock implements IDeclarationBlock { final private IDeclaration[] declarations = new IDeclaration[0]; public IFunctorCall accept(IFunctorCall call) throws DeclarationException { return call; } public Object getDeclarationContext() { return null; } public IDeclaration[] getDeclarations() { return declarations; } public boolean isBlock() { return true; } public int size() { return 0; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/installresource/0000755000175000017500000000000011412336332024223 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/installresource/InstallFileList.java0000644000175000017500000000671311070671202030135 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.installresource; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import de.intarsys.tools.file.TempTools; import de.intarsys.tools.stream.StreamTools; /** * An abstraction to access a directory structure to be deployed along with the * application via the class loader. Initially a file containing a list of * filenames is searched. All files referenced in the list are created in a * common directory. */ public class InstallFileList extends Install { public InstallFileList(String path, String name, boolean platformDependent) { super(path, name, platformDependent); } protected void loadEntry(File parent, String name) throws IOException { if (name.length() == 0 || name.startsWith("#")) { //$NON-NLS-1$ return; } Enumeration urls = find(name); if (urls != null) { if (urls.hasMoreElements()) { URL url = urls.nextElement(); File entryFile = new File(parent, name); File entryDir = entryFile.getParentFile(); if (entryDir != null && !entryDir.exists()) { entryDir.mkdirs(); } copy(url, entryFile); } } } protected void loadList(File parent, InputStream is) throws IOException { StringBuilder sb = new StringBuilder(); int i = is.read(); while (i != -1) { if (i == '\n') { String entryName = sb.toString().trim(); loadEntry(parent, entryName); sb.setLength(0); i = is.read(); continue; } sb.append((char) i); i = is.read(); } String entryName = sb.toString().trim(); loadEntry(parent, entryName); } @Override protected File loadURL(URL url) throws IOException { InputStream is = url.openStream(); try { File file = TempTools.createTempDir("dir", getName()); loadList(file, is); return file; } finally { StreamTools.close(is); } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/installresource/InstallFile.java0000644000175000017500000000613611070671202027300 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.installresource; import java.io.File; import java.io.IOException; import java.net.URL; import de.intarsys.tools.file.TempTools; /** * An abstraction to access a file to be deployed along with the application via * the class loader. *

* The file is searched in the class loader with getResourceAsStream(x) where x * is one of *

    *
  • [path]/[os.name]-[os.arch]/[filename]
  • *
  • [path]/[os.short name]-[os.arch]/[filename]
  • *
  • [path]/default/[filename]
  • *
* * where * *
    *
  • [path] is a path prefix defined upon object creation
  • *
  • [os.name] is the System property os.name in lowercase
  • *
  • [os.short name] is derived from the System property os.name by using the * beginning up to the first whitespace in lowercase
  • *
  • [os.arch] is the System property os.arch in lowercase
  • *
  • [filename] is the name defined upon object creation
  • *
* * example, with NativeCode("foo", "bar.dll") on a Windows Vista machine you * will search for: * *
    *
  • foo/windows vista-x86/bar.dll
  • *
  • foo/windows-x86/bar.dll
  • *
  • foo/default/bar.dll
  • *
*/ public class InstallFile extends Install { public InstallFile(String path, String name, boolean platformDependent) { super(path, name, platformDependent); } @Override protected File loadURL(URL url) throws IOException { File file = TempTools.createTempFile("file", getName()); copy(url, file); return file; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/installresource/InstallZip.java0000644000175000017500000000725111070671202027162 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.installresource; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import de.intarsys.tools.file.TempTools; import de.intarsys.tools.stream.StreamTools; /** * An abstraction to access a directory structure to be deployed along with the * application via the class loader. Initially a ZIP file is searched. The ZIP * is expanded to a temporary directory. */ public class InstallZip extends Install { public InstallZip(String path, String name, boolean platformDependent) { super(path, name, platformDependent); } protected void loadEntry(File parent, ZipFile zipFile, ZipEntry entry) throws IOException, FileNotFoundException { InputStream is = null; FileOutputStream os = null; String entryName = entry.getName(); File entryFile = new File(parent, entryName); if (entry.isDirectory()) { entryFile.mkdirs(); } else { File entryDir = entryFile.getParentFile(); if (entryDir != null && !entryDir.exists()) { entryDir.mkdirs(); } is = zipFile.getInputStream(entry); os = new FileOutputStream(entryFile); StreamTools.copyStream(is, os); } } @Override protected File loadURL(URL url) throws IOException { // create temporary zip file File file = TempTools.createTempFile("file", getName()); copy(url, file); deleteOnExit(file); // fill new temporary directory File dir = TempTools.createTempDir("dir", getName()); loadZip(file, dir); return dir; } protected void loadZip(File zip, File parent) throws ZipException, IOException { ZipFile zipFile = null; try { zipFile = new ZipFile(zip); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); loadEntry(parent, zipFile, entry); } } finally { if (zipFile != null) { zipFile.close(); } } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/installresource/package.html0000644000175000017500000000051011070671202026476 0ustar twernertwerner This is useful package to deploy components along with the classloader. Files or directories are detected in the classloader resources and copied temporarily to the file system. Here you can access the resources as if they were available locally - for example for loading a native library. libisrt-java-4.8.20100629/src/de/intarsys/tools/installresource/Install.java0000644000175000017500000002001011240532240026460 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.installresource; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import de.intarsys.tools.exception.ExceptionTools; import de.intarsys.tools.file.FileTools; import de.intarsys.tools.stream.StreamTools; import de.intarsys.tools.system.SystemTools; /** * Abstract superclass for implementing the resource installation behavior. */ abstract public class Install { private static String platformId; private static String platformFallbackId; private static String platformDefaultId; static protected void copy(URL url, File file) throws IOException, FileNotFoundException { InputStream is = url.openStream(); FileOutputStream os = null; try { os = new FileOutputStream(file); StreamTools.copyStream(is, os); } catch (IOException e) { throw ExceptionTools.createIOException("resource '" + url.getFile() //$NON-NLS-1$ + "' load error", e); //$NON-NLS-1$ } finally { StreamTools.close(is); StreamTools.close(os); } } protected static String createPlatformFallbackId() { String[] split = SystemTools.getOSName().split("\\s"); return (split[0] + "-" + SystemTools.getOSArch()).toLowerCase(); } protected static String createPlatformId() { return (SystemTools.getOSName() + "-" + SystemTools.getOSArch()) .toLowerCase(); } /** * Make file and all descendents subject to delete. * * @param file */ static protected void deleteOnExit(File file) { if (file == null) { return; } if (file.isDirectory()) { File[] children = file.listFiles(); for (int i = 0; i < children.length; i++) { File child = children[i]; deleteOnExit(child); } } file.deleteOnExit(); } public static String getPlatformDefaultId() { if (platformDefaultId == null) { return "default"; } return platformDefaultId; } public static String getPlatformFallbackId() { if (platformFallbackId == null) { return createPlatformFallbackId(); } return platformFallbackId; } public static String getPlatformId() { if (platformId == null) { return createPlatformId(); } return platformId; } public static void setPlatformFallbackId(String value) { platformFallbackId = value; } public static void setPlatformId(String value) { platformId = value; } private boolean platformDependent = false; protected final String name; protected final String path; protected File[] files; protected ClassLoader classLoader; public Install(String path, String name, boolean platformDependent) { super(); this.path = path; this.name = name; this.platformDependent = platformDependent; } /** * Delete the temporary installation. * * @return true if all artifacts are deleted. */ public boolean delete() { if (files == null) { return true; } boolean deleted = true; for (int i = 0; i < files.length; i++) { File file = files[i]; deleted = deleted && FileTools.deleteRecursivly(file); } return deleted; } /** * Find all URL's to a specific resource. * * @param name * @return */ protected Enumeration find(String name) { Enumeration urls = null; try { if (isPlatformDependent()) { urls = open(getResourceNameFull(name)); if (!urls.hasMoreElements()) { urls = open(getResourceNameFallback(name)); if (!urls.hasMoreElements()) { urls = open(getResourceNameDefault(name)); } } } else { urls = open(getResourceNamePlain(name)); } } catch (Exception e) { // } return urls; } public ClassLoader getClassLoader() { if (classLoader == null) { ClassLoader result = Thread.currentThread().getContextClassLoader(); if (result == null) { result = getClass().getClassLoader(); } return result; } return classLoader; } public File getFile() { if (files == null || files.length == 0) { return null; } return files[0]; } public File[] getFiles() { return files; } public String getName() { return name; } public String getPath() { return path; } protected String getResourceNameDefault(String name) { return getPlatformDefaultId() + "/" + name; } protected String getResourceNameFallback(String name) { return getPlatformFallbackId() + "/" + name; } protected String getResourceNameFull(String name) { return getPlatformId() + "/" + name; } protected String getResourceNamePlain(String name) { return name; } public boolean isPlatformDependent() { return platformDependent; } /** * Load the first occurrence of the designated target from the classloader. * * @return Load the first occurrence of the designated target from the * classloader. * @throws IOException */ public File load() throws IOException { Enumeration urls = find(getName()); if (urls != null) { if (urls.hasMoreElements()) { URL url = urls.nextElement(); File file = loadURL(url); deleteOnExit(file); files = new File[] { file }; return file; } } return null; } /** * Load all occurrences of the designated target from the classloader. * * @return Load all occurrences of the designated target from the * classloader. * @throws IOException */ public File[] loadAll() throws IOException { List tempFiles = new ArrayList(); Enumeration urls = find(getName()); if (urls != null) { while (urls.hasMoreElements()) { URL url = urls.nextElement(); File file = loadURL(url); deleteOnExit(file); tempFiles.add(file); } } files = tempFiles.toArray(new File[tempFiles.size()]); return files; } abstract protected File loadURL(URL url) throws IOException; protected Enumeration open(String name) throws IOException { String resourceName = prefix(name); return getClassLoader().getResources(resourceName); } protected String prefix(String name) { StringBuilder sb = new StringBuilder(); if (getPath() != null) { sb.append(getPath()); sb.append("/"); //$NON-NLS-1$ } sb.append(name); return sb.toString(); } public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/enumeration/0000755000175000017500000000000011412336332023333 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/enumeration/EnumItem.java0000644000175000017500000001136211204240560025720 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.enumeration; import java.util.HashMap; import java.util.Map; import de.intarsys.tools.message.Message; /** * The abstract superclass for an enumeration implementation. *

* To implement an enumeration class: * *

 *                 - create a subclass of EnumItem
 *                 - create a final public static attribute named META to the EnumMeta of the class.
 *                     final public static EnumMeta META = getMeta(XYZ.class);
 *                 - create a final public static attribute for every member of the enumeration.
 *                     public static final XYZ ABC = new XYZ("abxc","My ABC");
 * 
*/ public abstract class EnumItem implements Comparable { private static final Map META = new HashMap(); private static int WEIGHT = 0; protected static EnumMeta getMeta(Class clazz) { EnumMeta result = (EnumMeta) META.get(clazz); if (result == null) { result = new EnumMeta(clazz); META.put(clazz, result); } return result; } private String iconName; /** The enumeration id */ private final String id; /** The label to use for the enumeration value */ private String label; private Message message; /** * An integer defining the natural order of the items. */ private final int weight; protected EnumItem(String id) { this.id = id; this.message = new Message(this, id); this.weight = WEIGHT++; getMeta().addItem(this); } protected EnumItem(String id, int weight) { super(); this.id = id; this.message = new Message(this, id); this.weight = weight; getMeta().addItem(this); } protected EnumItem(String id, Message message) { this(id, message, WEIGHT++); } protected EnumItem(String id, Message message, int weight) { super(); this.id = id; this.message = message; this.weight = weight; getMeta().addItem(this); } /** * */ protected EnumItem(String id, String label) { this(id, label, WEIGHT++); } protected EnumItem(String id, String label, int weight) { super(); this.id = id; this.label = label; this.weight = weight; getMeta().addItem(this); } /* * (non-Javadoc) * * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(Object o) { EnumItem other = (EnumItem) o; return (int) Math.signum(this.getWeight() - other.getWeight()); } public String getDescription() { return getTip(); } public String getIconName() { return iconName; } public String getId() { return id; } public String getLabel() { if (label == null) { label = message.get(); } return label; } public String getLocalizedLabel() { return getLabel(); } public Message getMessage() { return message; } protected EnumMeta getMeta() { return getMeta(getClass()); } public String getTip() { return getLabel(); } protected int getWeight() { return weight; } protected void setDefault() { getMeta().setDefault(this); } protected void setIconName(String iconName) { this.iconName = iconName; } @Override public String toString() { return getLabel(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/enumeration/EnumMeta.java0000644000175000017500000000616110755250762025730 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.enumeration; import java.util.ArrayList; import java.util.List; /** * The meta data for an enumeration implementation. This is a completely generic * implementation - you should only subclass "EnumItem" to define a new * enumeration. * */ public class EnumMeta { final private Class enumClazz; final private List items = new ArrayList(); private T enumDefault = null; /** * */ public EnumMeta(Class enumClazz) { super(); this.enumClazz = enumClazz; } protected void addItem(T item) { items.add(item); } public T getDefault() { return enumDefault; } public Class getEnumClazz() { return enumClazz; } public T getItem(String id) { if (id == null) { return null; } for (T element : items) { if (element.getId().equals(id)) { return element; } } return null; } public T getItemOrDefault(String id) { T item = getItem(id); if (item == null) { item = getDefault(); } return item; } public T[] getItems() { return (T[]) items.toArray(new EnumItem[items.size()]); } public T getMax() { T max = null; for (T element : items) { if ((max == null) || (element.getWeight() > max.getWeight())) { max = element; } } return max; } public T getMin() { T min = null; for (T element : items) { if ((min == null) || (element.getWeight() < min.getWeight())) { min = element; } } return min; } protected void setDefault(T item) { enumDefault = item; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/mime/0000755000175000017500000000000011412336332021734 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/mime/IMimeTypeSupport.java0000644000175000017500000000323511030371032026031 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.mime; public interface IMimeTypeSupport { public String getContentType(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/result/0000755000175000017500000000000011412336332022323 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/result/LocatorBasedResult.java0000644000175000017500000000433711031105622026727 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.result; import java.io.IOException; import de.intarsys.tools.locator.ILocator; import de.intarsys.tools.stream.StreamTools; public class LocatorBasedResult extends StreamResult { final private ILocator locator; public LocatorBasedResult(String contentType, ILocator locator) { super(contentType); this.locator = locator; setName(locator.getLocalName()); setType(locator.getType()); } public ILocator getLocator() { return locator; } @Override public String toString() { try { return StreamTools.toString(locator.getReader()); } catch (IOException e) { return ""; //$NON-NLS-1$ } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/result/StringBasedResult.java0000644000175000017500000000421510751651500026576 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.result; import de.intarsys.tools.locator.ILocator; import de.intarsys.tools.locator.StringLocator; public class StringBasedResult extends StreamResult { private String string; public StringBasedResult(String contentType, String string) { super(contentType); this.string = string; setName("string"); //$NON-NLS-1$ setType("txt"); //$NON-NLS-1$ } public ILocator getLocator() { return new StringLocator(string, getName(), getType()); } public String getString() { return string; } public String toString() { return string; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/result/IStreamResult.java0000644000175000017500000000331410751651500025734 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.result; import de.intarsys.tools.locator.ILocatorSupport; public interface IStreamResult extends IResult, ILocatorSupport { } libisrt-java-4.8.20100629/src/de/intarsys/tools/result/ILiteralResult.java0000644000175000017500000000324510751651500026100 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.result; public interface ILiteralResult extends IResult { public Object getValue(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/result/StreamResult.java0000644000175000017500000000401410751651500025621 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.result; abstract public class StreamResult extends CommonResult implements IStreamResult { private String name; private String type; public StreamResult(String contentType) { super(contentType); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/result/LiteralResult.java0000644000175000017500000000373210751651500025770 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.result; import de.intarsys.tools.string.StringTools; public class LiteralResult extends CommonResult implements ILiteralResult { private Object value; public LiteralResult(String contentType, Object value) { super(contentType); this.value = value; } public Object getValue() { return value; } public String toString() { return StringTools.safeString(value); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/result/CommonResult.java0000644000175000017500000000350010751651500025615 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.result; abstract public class CommonResult implements IResult { private String contentType; public String getContentType() { return contentType; } public CommonResult(String contentType) { this.contentType = contentType; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/result/IResult.java0000644000175000017500000000327611030371032024555 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.result; import de.intarsys.tools.mime.IMimeTypeSupport; public interface IResult extends IMimeTypeSupport { } libisrt-java-4.8.20100629/src/de/intarsys/tools/result/ByteBasedResult.java0000644000175000017500000000417610751651500026241 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.result; import de.intarsys.tools.locator.ByteArrayLocator; import de.intarsys.tools.locator.ILocator; public class ByteBasedResult extends StreamResult { private byte[] bytes; public byte[] getBytes() { return bytes; } public ByteBasedResult(String contentType, byte[] bytes) { super(contentType); setName("binary"); //$NON-NLS-1$ setType("dat"); //$NON-NLS-1$ } public ILocator getLocator() { return new ByteArrayLocator(bytes, getName(), getType()); } public String toString() { return new String(bytes); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/collection/0000755000175000017500000000000011412336332023140 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/collection/IntHashMap.java0000644000175000017500000002613611052336474026016 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.collection; /** *

* A hash map that uses primitive ints for the key rather than objects. *

* *

* Copied from Jakarta Commons Lang internal implementation. To be removed as * soon as Jakarta Commons Collections provides it. *

*/ public class IntHashMap { /** * The hash table data. */ private transient Entry[] table; /** * The total number of entries in the hash table. */ private transient int count; /** * The table is rehashed when its size exceeds this threshold. (The value of * this field is (int)(capacity * loadFactor).) * * @serial */ private int threshold; /** * The load factor for the hashtable. * * @serial */ private float loadFactor; /** *

* Innerclass that acts as a datastructure to create a new entry in the * table. *

*/ private static class Entry { int hash; int key; Object value; Entry next; /** *

* Create a new entry with the given values. *

* * @param hash * The code used to hash the object with * @param key * The key used to enter this in the table * @param value * The value for this key * @param next * A reference to the next entry in the table */ protected Entry(int hash, int key, Object value, Entry next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } } /** *

* Constructs a new, empty hashtable with a default capacity and load * factor, which is 20 and 0.75 respectively. *

*/ public IntHashMap() { this(20, 0.75f); } /** *

* Constructs a new, empty hashtable with the specified initial capacity and * default load factor, which is 0.75. *

* * @param initialCapacity * the initial capacity of the hashtable. * @throws IllegalArgumentException * if the initial capacity is less than zero. */ public IntHashMap(int initialCapacity) { this(initialCapacity, 0.75f); } /** *

* Constructs a new, empty hashtable with the specified initial capacity and * the specified load factor. *

* * @param initialCapacity * the initial capacity of the hashtable. * @param loadFactor * the load factor of the hashtable. * @throws IllegalArgumentException * if the initial capacity is less than zero, or if the load * factor is nonpositive. */ public IntHashMap(int initialCapacity, float loadFactor) { super(); if (initialCapacity < 0) { throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity); } if (loadFactor <= 0) { throw new IllegalArgumentException("Illegal Load: " + loadFactor); } if (initialCapacity == 0) { initialCapacity = 1; } this.loadFactor = loadFactor; table = new Entry[initialCapacity]; threshold = (int) (initialCapacity * loadFactor); } /** *

* Returns the number of keys in this hashtable. *

* * @return the number of keys in this hashtable. */ public int size() { return count; } /** *

* Tests if this hashtable maps no keys to values. *

* * @return true if this hashtable maps no keys to values; * false otherwise. */ public boolean isEmpty() { return count == 0; } /** *

* Tests if some key maps into the specified value in this hashtable. This * operation is more expensive than the containsKey method. *

* *

* Note that this method is identical in functionality to containsValue, * (which is part of the Map interface in the collections framework). *

* * @param value * a value to search for. * @return true if and only if some key maps to the * value argument in this hashtable as determined by * the equals method; false otherwise. * @throws NullPointerException * if the value is null. * @see #containsKey(int) * @see #containsValue(Object) * @see java.util.Map */ public boolean contains(Object value) { if (value == null) { throw new NullPointerException(); } Entry[] tab = table; for (int i = tab.length; i-- > 0;) { for (Entry e = tab[i]; e != null; e = e.next) { if (e.value.equals(value)) { return true; } } } return false; } /** *

* Returns true if this HashMap maps one or more keys to this * value. *

* *

* Note that this method is identical in functionality to contains (which * predates the Map interface). *

* * @param value * value whose presence in this HashMap is to be tested. * @return boolean true if the value is contained * @see java.util.Map * @since JDK1.2 */ public boolean containsValue(Object value) { return contains(value); } /** *

* Tests if the specified object is a key in this hashtable. *

* * @param key * possible key. * @return true if and only if the specified object is a key * in this hashtable, as determined by the equals method; * false otherwise. * @see #contains(Object) */ public boolean containsKey(int key) { Entry[] tab = table; int hash = key; int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index]; e != null; e = e.next) { if (e.hash == hash) { return true; } } return false; } /** *

* Returns the value to which the specified key is mapped in this map. *

* * @param key * a key in the hashtable. * @return the value to which the key is mapped in this hashtable; * null if the key is not mapped to any value in this * hashtable. * @see #put(int, Object) */ public Object get(int key) { Entry[] tab = table; int hash = key; int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index]; e != null; e = e.next) { if (e.hash == hash) { return e.value; } } return null; } /** *

* Increases the capacity of and internally reorganizes this hashtable, in * order to accommodate and access its entries more efficiently. *

* *

* This method is called automatically when the number of keys in the * hashtable exceeds this hashtable's capacity and load factor. *

*/ protected void rehash() { int oldCapacity = table.length; Entry[] oldMap = table; int newCapacity = (oldCapacity * 2) + 1; Entry[] newMap = new Entry[newCapacity]; threshold = (int) (newCapacity * loadFactor); table = newMap; for (int i = oldCapacity; i-- > 0;) { for (Entry old = oldMap[i]; old != null;) { Entry e = old; old = old.next; int index = (e.hash & 0x7FFFFFFF) % newCapacity; e.next = newMap[index]; newMap[index] = e; } } } /** *

* Maps the specified key to the specified value * in this hashtable. The key cannot be null. *

* *

* The value can be retrieved by calling the get method with * a key that is equal to the original key. *

* * @param key * the hashtable key. * @param value * the value. * @return the previous value of the specified key in this hashtable, or * null if it did not have one. * @throws NullPointerException * if the key is null. * @see #get(int) */ public Object put(int key, Object value) { // Makes sure the key is not already in the hashtable. Entry[] tab = table; int hash = key; int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index]; e != null; e = e.next) { if (e.hash == hash) { Object old = e.value; e.value = value; return old; } } if (count >= threshold) { // Rehash the table if the threshold is exceeded rehash(); tab = table; index = (hash & 0x7FFFFFFF) % tab.length; } // Creates the new entry. Entry e = new Entry(hash, key, value, tab[index]); tab[index] = e; count++; return null; } /** *

* Removes the key (and its corresponding value) from this hashtable. *

* *

* This method does nothing if the key is not present in the hashtable. *

* * @param key * the key that needs to be removed. * @return the value to which the key had been mapped in this hashtable, or * null if the key did not have a mapping. */ public Object remove(int key) { Entry[] tab = table; int hash = key; int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index], prev = null; e != null; prev = e, e = e.next) { if (e.hash == hash) { if (prev != null) { prev.next = e.next; } else { tab[index] = e.next; } count--; Object oldValue = e.value; e.value = null; return oldValue; } } return null; } /** *

* Clears this hashtable so that it contains no keys. *

*/ public synchronized void clear() { Entry[] tab = table; for (int index = tab.length; --index >= 0;) { tab[index] = null; } count = 0; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/collection/EmptyIterator.java0000644000175000017500000000505010751651476026631 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.collection; import java.util.Iterator; import java.util.NoSuchElementException; /** * An Iterator over an empty collection. * */ public class EmptyIterator implements Iterator { // public static final Iterator UNIQUE = new EmptyIterator(); /** * Create an EmptyIterator. */ protected EmptyIterator() { super(); } /** * Return always false as an emtpy iterator has no elements. * * @return Return always false as an emtpy iterator has no elements. */ public boolean hasNext() { return false; } /** * Throw always exception, as an empty enumeration has no elements. * * @return never * * @throws NoSuchElementException * Is thrown always */ public java.lang.Object next() { throw new NoSuchElementException("no element available"); } /* * (non-Javadoc) * * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/collection/MapTools.java0000644000175000017500000000760010751651476025562 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.collection; import java.util.Iterator; import java.util.List; import java.util.Map; /** * A tool class for Map extensions. */ public class MapTools { // public static final String SEPARATOR = "="; private MapTools() { super(); } /** * Define new entries in map from all declaration strings in * declarations. For every string in the collection, {@link * #defineEntry(Map, String)} is called. * * @param map * The map to receive the new declarations * @param declarations * A collection of declaration strings. * * @return The parameter map */ public static Map defineEntries(Map map, List declarations) { if (declarations == null) { return map; } for (Iterator i = declarations.iterator(); i.hasNext();) { defineEntry(map, (String) i.next()); } return map; } /** * Define a new entry in the map from definition. * definition contains a string in the form "key=value". A * entry is defined in the map with "key" as the entries key and the trimmed * "value" as its value. If no "=" is available, the value will be an empty * string. * * @param map * The map where we will put the key/value pair. * @param declaration * The string representation of the key/value pair. * * @return The parameter map */ public static Map defineEntry(Map map, String declaration) { if (declaration == null) { return map; } String key; String value; int pos = declaration.indexOf(SEPARATOR); if (pos > -1) { key = declaration.substring(0, pos).trim(); value = declaration.substring(pos + 1); } else { key = declaration.trim(); value = ""; } map.put(key, value); return map; } public static Object get(Map map, Object key, Object defaultValue) { if (map == null) { return defaultValue; } Object value = map.get(key); if (value == null) { return defaultValue; } return value; } public static String get(Map map, Object key, String defaultValue) { if (map == null) { return defaultValue; } Object value = map.get(key); if (value == null) { return defaultValue; } return value.toString(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/collection/SingleObjectIterator.java0000644000175000017500000000504311025664516030077 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.collection; import java.util.Iterator; import java.util.NoSuchElementException; /** * An iterator over a single object. * */ public class SingleObjectIterator implements Iterator { private Object singleObject; private boolean hasNext = true; /** * EnumerationIterator constructor comment. * * @param singleton * */ public SingleObjectIterator(Object singleton) { super(); setSingleObject(singleton); } private java.lang.Object getSingleObject() { return singleObject; } public boolean hasNext() { return hasNext; } public java.lang.Object next() { if (hasNext()) { hasNext = false; return getSingleObject(); } else { throw new NoSuchElementException(); } } public void remove() { throw new UnsupportedOperationException( "can not remove from singleton iterator"); } private void setSingleObject(java.lang.Object newSingleObject) { singleObject = newSingleObject; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/collection/ReverseListIterator.java0000644000175000017500000000475511220421154027771 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.collection; import java.util.Iterator; import java.util.List; /** * This iterator enumerates the elements of a list in reverse order. */ public class ReverseListIterator implements Iterator, Iterable { private final List list; private final int size; private int current; /** * */ public ReverseListIterator(List list) { super(); this.list = list; size = list.size(); current = size; } /* * (non-Javadoc) * * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return current > 0; } public Iterator iterator() { return this; } /* * (non-Javadoc) * * @see java.util.Iterator#next() */ public T next() { current--; return list.get(current); } /* * (non-Javadoc) * * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/collection/IntervalIterator.java0000644000175000017500000000633410751651476027325 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.collection; import java.util.Iterator; import java.util.NoSuchElementException; /** * Implement an Iterator over a virtual collection of numbers defined by an * interval. * *

* The iterator returns every number with (from >.= number) and (number <.= * to) starting with from. The current number is incremented by * step after every element access. *

*/ public class IntervalIterator implements Iterator { // private double current; private double from; private double step = 1; private double to; /** * IntervalIterator constructor . * * @param from * The first number to be returned by the iterator. * @param to * The number defining an upper limit to the numbers in the * collection. */ public IntervalIterator(Number from, Number to) { super(); this.from = from.doubleValue(); this.to = to.doubleValue(); current = this.from; } /* * (non-Javadoc) * * @see java.util.Iterator#hasNext() */ public boolean hasNext() { if (current > to) { return false; } else { return true; } } /* * (non-Javadoc) * * @see java.util.Iterator#next() */ public java.lang.Object next() { Number activeElement; if (!hasNext()) { throw new NoSuchElementException("no more elements"); } activeElement = new Double(current); current = current + step; return activeElement; } /* * (non-Javadoc) * * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException( "IntervalIterator not modifiable"); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/collection/ArrayIterator.java0000644000175000017500000000475310751651476026622 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.collection; import java.lang.reflect.Array; import java.util.Iterator; /** * An iterator over an array */ public class ArrayIterator implements Iterator { /** * The wrapped array */ final private Object array; /** * The current index into the array */ private int index = 0; /** * */ public ArrayIterator(Object array) { super(); this.array = array; } /* * (non-Javadoc) * * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException( "can not remove from array iterator"); } /* * (non-Javadoc) * * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return Array.getLength(array) > index; } /* * (non-Javadoc) * * @see java.util.Iterator#next() */ public Object next() { Object result = Array.get(array, index); index++; return result; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/collection/ByteArrayTools.java0000644000175000017500000001112511030721456026727 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.collection; public class ByteArrayTools { public static byte[] concat(byte[] array1, byte[] array2) { byte[] concat = new byte[array1.length + array2.length]; System.arraycopy(array1, 0, concat, 0, array1.length); System.arraycopy(array2, 0, concat, array1.length, array2.length); return concat; } /** * Make a copy of bytes. * * @param bytes * byte[] to be copied * * @return A copy of bytes */ static public byte[] copy(byte[] bytes) { byte[] newbuf = new byte[bytes.length]; System.arraycopy(bytes, 0, newbuf, 0, bytes.length); return newbuf; } /** * Copy length bytes from bytes starting at * from. * * @param bytes * byte[] to be copied * @param offset * starting position to copy from * @param length * number of bytes * * @return A copy of bytes */ static public byte[] copy(byte[] bytes, int offset, int length) { byte[] newbuf = new byte[length]; System.arraycopy(bytes, offset, newbuf, 0, length); return newbuf; } /** * Search index of pattern in source. Algorithm from java.lang.String * * @param source * @param sourceOffset * @param sourceLen * @param pattern * @param patternOffset * @param patternLen * @param fromIndex * @return The index of the first occurrence of pattern or -1. */ static public int indexOf(byte[] source, int sourceOffset, int sourceLen, byte[] pattern, int patternOffset, int patternLen, int fromIndex) { if (fromIndex >= sourceLen) { return (patternLen == 0 ? sourceLen : -1); } if (fromIndex < 0) { fromIndex = 0; } if (patternLen == 0) { return fromIndex; } byte first = pattern[patternOffset]; int max = sourceOffset + (sourceLen - patternLen); for (int i = sourceOffset + fromIndex; i <= max; i++) { /* Look for first byte . */ if (source[i] != first) { while (++i <= max && source[i] != first) { ; } } /* Found first byte, now look at the rest of v2 */ if (i <= max) { int j = i + 1; int end = j + patternLen - 1; for (int k = patternOffset + 1; j < end && source[j] == pattern[k]; j++, k++) { ; } if (j == end) { /* Found whole pattern. */ return i - sourceOffset; } } } return -1; } /** * true if bytes starts with the byte sequence * defined in pattern. * * @param bytes * @param pattern * @return true if bytes starts with the byte * sequence defined in pattern. * */ static public boolean startsWith(byte[] bytes, byte[] pattern) { if (bytes == null) { return false; } if (pattern == null) { return true; } int length = pattern.length; for (int i = 0; i < length; i++) { if (bytes[i] != pattern[i]) { return false; } } return true; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/collection/NestedIterator.java0000644000175000017500000001215511025664516026753 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.collection; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /** * An iterator to enumerate sequentially the elements in a hierarchical * collection. *

* Every node that implements IIteratorSupport itself is enumerated instead of * beeing returned imediately. * */ public class NestedIterator implements Iterator { public static void test1() { java.util.List l = new java.util.ArrayList(); java.util.List li; java.util.List lii; // li = new java.util.ArrayList(); li.add("1.1"); li.add("1.2"); li.add("1.3"); l.add(li); // li = new java.util.ArrayList(); li.add("2.1"); li.add("2.2"); l.add(li); // l.add(null); // li = new java.util.ArrayList(); li.add("3.1"); li.add("3.2"); li.add("3.3"); lii = new java.util.ArrayList(); lii.add("3.3.1"); lii.add("3.3.2"); lii.add("3.3.3"); li.add(lii); li.add("3.4"); li.add("3.5"); l.add(li); li = new java.util.ArrayList(); li.add("4.1"); li.add("4.2"); l.add(li); de.intarsys.tools.collection.NestedIterator ni = new de.intarsys.tools.collection.NestedIterator( l); for (; ni.hasNext();) { System.out.println(ni.next()); } } // private Iterator innerIterator = null; // private Iterator outerIterator = null; private Object outerCurrent; private boolean tryInner = true; public NestedIterator(Iterator i) { super(); setOuterIterator(i); } public NestedIterator(List l) { super(); setOuterIterator(l.iterator()); } protected void createInnerIterator() { setInnerIterator(null); if (getOuterCurrent() != null) { if (getOuterCurrent() instanceof List) { setInnerIterator(new NestedIterator(((List) getOuterCurrent()) .iterator())); } if (getOuterCurrent() instanceof Iterable) { setInnerIterator(new NestedIterator( ((Iterable) getOuterCurrent()).iterator())); } } } protected java.util.Iterator getInnerIterator() { return innerIterator; } protected java.lang.Object getOuterCurrent() { return outerCurrent; } protected java.util.Iterator getOuterIterator() { return outerIterator; } public boolean hasNext() { if (isTryInner()) { if (!getOuterIterator().hasNext()) { return false; } setTryInner(false); setOuterCurrent(getOuterIterator().next()); createInnerIterator(); } if (getInnerIterator() == null) { // no nesting return true; } else { if (getInnerIterator().hasNext()) { // running on inner return true; } else { // inner has run out, reset to outer setTryInner(true); return hasNext(); } } } private boolean isTryInner() { return tryInner; } public java.lang.Object next() { if (!hasNext()) { throw new NoSuchElementException("no more elements"); } if (getInnerIterator() == null) { setTryInner(true); return getOuterCurrent(); } else { return getInnerIterator().next(); } } public void remove() { throw new UnsupportedOperationException( "number iterator not modifiable"); } private void setInnerIterator(java.util.Iterator newInnerIterator) { innerIterator = newInnerIterator; } private void setOuterCurrent(java.lang.Object newOuterCurrent) { outerCurrent = newOuterCurrent; } private void setOuterIterator(java.util.Iterator newOuterIterator) { outerIterator = newOuterIterator; } private void setTryInner(boolean newTryInner) { tryInner = newTryInner; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/collection/EnumerationIterator.java0000644000175000017500000000605610751651476030030 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.collection; import java.util.Enumeration; import java.util.Iterator; import java.util.NoSuchElementException; /** * Wraps an enumeration into an Iterator API. * */ public class EnumerationIterator implements Iterator { private Enumeration enumeration; /** * Create an Iterator over an enumeration. * * @param e * The enumeration to be iterated. */ public EnumerationIterator(Enumeration e) { super(); setEnumeration(e); } private void setEnumeration(java.util.Enumeration newEnumeration) { enumeration = newEnumeration; } protected java.util.Enumeration getEnumeration() { return enumeration; } /** * Return true if underlying enumeration still has elements. * * @return true if underlying enumeration still has elements. */ public boolean hasNext() { if (getEnumeration() == null) { return false; } return getEnumeration().hasMoreElements(); } /** * Return the next element from the underlying enumeration. * * @return the next element from the underlying enumeration. * * @throws NoSuchElementException */ public java.lang.Object next() { if (getEnumeration() == null) { throw new NoSuchElementException("enumeration not available"); } return getEnumeration().nextElement(); } /* * (non-Javadoc) * * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/collection/PartitionedMap.java0000644000175000017500000003231311025664516026735 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.collection; import java.util.AbstractCollection; import java.util.AbstractSet; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; /** * A map that wraps two other maps. * */ public class PartitionedMap implements Map { private class PartitionIterator implements Iterator { Iterator parentIterator = PartitionedMap.this.getParent().entrySet() .iterator(); Iterator subIterator = PartitionedMap.this.getChild().entrySet() .iterator(); int type; PartitionIterator(int type) { this.type = type; } public boolean hasNext() { return parentIterator.hasNext() || subIterator.hasNext(); } public Object next() { Map.Entry e = null; if (parentIterator.hasNext()) { e = (Map.Entry) parentIterator.next(); } else { e = (Map.Entry) subIterator.next(); } if (e != null) { return (type == KEYS) ? e.getKey() : ((type == VALUES) ? e .getValue() : e); } throw new NoSuchElementException(); } public void remove() { throw new UnsupportedOperationException( "Partitioned Maps do not support this"); } } // Types of Iterators private static final int KEYS = 0; private static final int VALUES = 1; private static final int ENTRIES = 2; static public Map create(Map parent, Map child) { if (parent == null) { return child; } if (child == null) { return parent; } return new PartitionedMap(parent, child); } private Map child; private Map parent; public PartitionedMap() { this(null, null); } public PartitionedMap(Map parent, Map child) { super(); setChild((child == null) ? new HashMap() : child); setParent((parent == null) ? new HashMap() : parent); } /** * Removes all mappings from this map (optional operation). */ public void clear() { getChild().clear(); } /** * Returns true if this map contains a mapping for the specified * key. * * @param key * key whose presence in this map is to be tested. * * @return true if this map contains a mapping for the specified * key. */ public boolean containsKey(java.lang.Object key) { return getChild().containsKey(key) || ((getParent() == null) ? false : getParent() .containsKey(key)); } /** * Returns true if this map maps one or more keys to the * specified value. More formally, returns true if and only if * this map contains at least one mapping to a value v such that * (value==null ? v==null : value.equals(v)). This operation * will probably require time linear in the map size for most * implementations of the Map interface. * * @param value * value whose presence in this map is to be tested. * * @return true if this map maps one or more keys to the * specified value. */ public boolean containsValue(java.lang.Object value) { return getChild().containsValue(value) || ((getParent() == null) ? false : getParent().containsValue( value)); } /** * Returns a set view of the mappings contained in this map. Each element in * the returned set is a Map.Entry. The set is backed by the * map, so changes to the map are reflected in the set, and vice-versa. If * the map is modified while an iteration over the set is in progress, the * results of the iteration are undefined. The set supports element removal, * which removes the corresponding mapping from the map, via the * Iterator.remove, Set.remove, removeAll, * retainAll and clear operations. It does not support * the add or addAll operations. * * @return a set view of the mappings contained in this map. */ public java.util.Set entrySet() { Set set = new AbstractSet() { @Override public void clear() { getChild().clear(); } @Override public boolean contains(Object o) { // i dont claim this to be efficient.... return getChild().entrySet().contains(o) || ((getParent() == null) ? false : getParent() .entrySet().contains(o)); } @Override public Iterator iterator() { return new PartitionIterator(ENTRIES); } @Override public boolean remove(Object o) { return getChild().entrySet().remove(o) || ((getParent() == null) ? false : getParent() .entrySet().remove(o)); } @Override public int size() { return getChild().size() + ((getParent() == null) ? 0 : getParent().size()); } }; return set; } /** * Returns the value to which this map maps the specified key. Returns * null if the map contains no mapping for this key. A return * value of null does not necessarily indicate that the * map contains no mapping for the key; it's also possible that the map * explicitly maps the key to null. The containsKey * operation may be used to distinguish these two cases. * * @param key * key whose associated value is to be returned. * * @return the value to which this map maps the specified key, or * null if the map contains no mapping for this key. * * @see #containsKey(Object) */ public java.lang.Object get(java.lang.Object key) { Object result = getChild().get(key); return (result == null) ? ((getParent() == null) ? null : getParent() .get(key)) : result; } protected Map getChild() { return child; } public java.util.Map getParent() { return parent; } /** * Returns true if this map contains no key-value mappings. * * @return true if this map contains no key-value mappings. */ public boolean isEmpty() { return getChild().isEmpty() && ((getParent() == null) ? true : getParent().isEmpty()); } /** * Returns a set view of the keys contained in this map. The set is backed * by the map, so changes to the map are reflected in the set, and * vice-versa. If the map is modified while an iteration over the set is in * progress, the results of the iteration are undefined. The set supports * element removal, which removes the corresponding mapping from the map, * via the Iterator.remove, Set.remove, * removeAllretainAll, and clear * operations. It does not support the add or addAll operations. * * @return a set view of the keys contained in this map. */ public java.util.Set keySet() { Set set = new AbstractSet() { @Override public void clear() { getChild().clear(); } @Override public boolean contains(Object o) { // i dont claim this to be efficient.... return ((getParent() == null) ? false : getParent() .containsKey(o)) || getChild().containsKey(o); } @Override public Iterator iterator() { return new PartitionIterator(KEYS); } @Override public boolean remove(Object o) { return (getChild().remove(o) != null) || ((getParent() == null) ? false : (getParent() .remove(o) != null)); } @Override public int size() { return getChild().size() + ((getParent() == null) ? 0 : getParent().size()); } }; return set; } /** * Associates the specified value with the specified key in this map * (optional operation). If the map previously contained a mapping for this * key, the old value is replaced. * * @param key * key with which the specified value is to be associated. * @param value * value to be associated with the specified key. * * @return previous value associated with specified key, or null * if there was no mapping for key. A null return can * also indicate that the map previously associated null * with the specified key, if the implementation supports * null values. */ public java.lang.Object put(java.lang.Object key, java.lang.Object value) { // not sure if this is really useful - if activated "local" variable // overwrites the parent one // if (getParent().containsKey(key)) { // return getParent().put(key, value); // } return getChild().put(key, value); } /** * Copies all of the mappings from the specified map to this map (optional * operation). These mappings will replace any mappings that this map had * for any of the keys currently in the specified map. * * @param t * Mappings to be stored in this map. */ public void putAll(java.util.Map t) { Iterator i = t.entrySet().iterator(); while (i.hasNext()) { Map.Entry e = (Map.Entry) i.next(); put(e.getKey(), e.getValue()); } } /** * Removes the mapping for this key from this map if present (optional * operation). * * @param key * key whose mapping is to be removed from the map. * * @return previous value associated with specified key, or null * if there was no mapping for key. A null return can * also indicate that the map previously associated null * with the specified key, if the implementation supports * null values. */ public java.lang.Object remove(java.lang.Object key) { if ((getParent() != null) && getParent().containsKey(key)) { return getParent().remove(key); } return getChild().remove(key); } private void setChild(java.util.Map newSubMap) { child = newSubMap; } public void setParent(java.util.Map newParent) { parent = newParent; } /** * Returns the number of key-value mappings in this map. If the map contains * more than Integer.MAX_VALUE elements, returns * Integer.MAX_VALUE. * * @return the number of key-value mappings in this map. */ public int size() { return ((getParent() == null) ? 0 : getParent().size()) + getChild().size(); } @Override public String toString() { return ((getParent() == null) ? "" : (getParent().toString() + System .getProperty("line.separator"))) + getChild().toString(); } /** * Returns a collection view of the values contained in this map. The * collection is backed by the map, so changes to the map are reflected in * the collection, and vice-versa. If the map is modified while an iteration * over the collection is in progress, the results of the iteration are * undefined. The collection supports element removal, which removes the * corresponding mapping from the map, via the Iterator.remove, * Collection.remove, removeAll, retainAll * and clear operations. It does not support the add or * addAll operations. * * @return a collection view of the values contained in this map. */ public java.util.Collection values() { Collection c = new AbstractCollection() { @Override public void clear() { getChild().clear(); } @Override public boolean contains(Object o) { // i dont claim this to be efficient.... return ((getParent() == null) ? false : getParent() .containsValue(o)) || getChild().containsValue(o); } @Override public Iterator iterator() { return new PartitionIterator(VALUES); } @Override public int size() { return getChild().size() + ((getParent() == null) ? 0 : getParent().size()); } }; return c; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/collection/ArrayTools.java0000644000175000017500000000563010762061452026113 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.collection; import java.lang.reflect.Array; import java.util.Collection; import java.util.Iterator; import java.util.List; public class ArrayTools { public static Object createFromList(Class objectClass, List list) { Object array = Array.newInstance(objectClass, list.size()); int index = 0; for (Iterator i = list.iterator(); i.hasNext(); index++) { Object element = i.next(); Array.set(array, index, element); } return array; } public static void reverse(byte[] array) { reverse(array, 0, array.length); } public static void reverse(byte[] array, int index, int length) { byte temp; for (int i = 0; i < length / 2; i++) { temp = array[index + i]; array[index + i] = array[index + length - i - 1]; array[index + length - i - 1] = temp; } } public static void reverse(T[] array) { reverse(array, 0, array.length); } public static void reverse(T[] array, int index, int length) { T temp; for (int i = 0; i < length / 2; i++) { temp = array[index + i]; array[index + i] = array[index + length - i - 1]; array[index + length - i - 1] = temp; } } public static Object toArray(Class clazz, Collection collection) { return collection.toArray((Object[]) Array.newInstance(clazz, collection.size())); } private ArrayTools() { } } libisrt-java-4.8.20100629/src/de/intarsys/tools/collection/ListTools.java0000644000175000017500000000541111411055572025743 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.collection; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * */ public class ListTools { static public List collect(Iterator it) { List result = new ArrayList(); while (it.hasNext()) { result.add(it.next()); } return result; } static public T first(List list) { if (list == null) { return null; } if (list.size() == 0) { return null; } return list.get(0); } static public T last(List list) { if (list == null) { return null; } if (list.size() == 0) { return null; } return list.get(list.size() - 1); } static public List with(T object) { List result = new ArrayList(); result.add(object); return result; } static public List with(T object1, T object2) { List result = new ArrayList(); result.add(object1); result.add(object2); return result; } static public List with(T object1, T object2, T object3) { List result = new ArrayList(); result.add(object1); result.add(object2); result.add(object3); return result; } /** * */ private ListTools() { // tool class } } libisrt-java-4.8.20100629/src/de/intarsys/tools/collection/IteratorEnumeration.java0000644000175000017500000000522110762061506030010 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.collection; import java.util.Enumeration; import java.util.Iterator; import java.util.NoSuchElementException; /** * Wraps an iterator into an enumeration API. * */ public class IteratorEnumeration implements Enumeration { private Iterator iterator; /** * IteratorEnumeration constructor. * * @param i * The Iterator to be enumerated */ public IteratorEnumeration(Iterator i) { super(); setIterator(i); } protected Iterator getIterator() { return iterator; } /* * (non-Javadoc) * * @see java.util.Enumeration#hasMoreElements() */ public boolean hasMoreElements() { if (getIterator() == null) { return false; } return getIterator().hasNext(); } /* * (non-Javadoc) * * @see java.util.Enumeration#nextElement() */ public T nextElement() { if (getIterator() == null) { throw new NoSuchElementException("iterator not available"); } return getIterator().next(); } private void setIterator(Iterator newIterator) { iterator = newIterator; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/collection/EmptyEnumeration.java0000644000175000017500000000466010751651476027334 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.collection; import java.util.Enumeration; import java.util.NoSuchElementException; /** * An Enumeration without elements. */ public class EmptyEnumeration implements Enumeration { // public final static Enumeration UNIQUE = new EmptyEnumeration(); /** * Create an emtpy enumeration */ protected EmptyEnumeration() { super(); } /** * Return always false as an emtpy enumeration has no elements. * * @return Return always false as an emtpy enumeration has no elements. */ public boolean hasMoreElements() { return false; } /** * Throw always exception, as an empty enumeration has no elements. * * @return never * * @throws NoSuchElementException * Is thrown always */ public java.lang.Object nextElement() { throw new NoSuchElementException("no element available"); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/collection/SingleObjectEnumeration.java0000644000175000017500000000574411053301416030570 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.collection; import java.util.Enumeration; import java.util.NoSuchElementException; /** * An enumeration of a single object. * */ public class SingleObjectEnumeration implements Enumeration { private T singleObject; private boolean hasNext = true; /** * EnumerationIterator constructor comment. * * @param single * */ public SingleObjectEnumeration(T single) { super(); setSingleObject(single); } private T getSingleObject() { return singleObject; } public boolean hasMoreElements() { return hasNext; } public T nextElement() { if (hasMoreElements()) { hasNext = false; return getSingleObject(); } throw new NoSuchElementException(); } /** * Removes from the underlying collection the last element returned by the * iterator (optional operation). This method can be called only once per * call to next. The behavior of an iterator is unspecified if * the underlying collection is modified while the iteration is in progress * in any way other than by calling this method. * * @exception UnsupportedOperationException * if the remove operation is not supported by * this Iterator. */ public void remove() { throw new UnsupportedOperationException(); } private void setSingleObject(T newSingleObject) { singleObject = newSingleObject; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/hex/0000755000175000017500000000000011412336332021571 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/hex/HexTools.java0000644000175000017500000003215411412330274024205 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.hex; /** * Helper class for faster mapping of bytes to their hex equivalent */ public class HexTools { /** ASCII byte values for the hex strings. */ public static final byte[][] ByteToHex = { "00".getBytes(), "01".getBytes(), "02".getBytes(), "03".getBytes(), "04".getBytes(), "05".getBytes(), "06".getBytes(), "07".getBytes(), "08".getBytes(), "09".getBytes(), "0A".getBytes(), "0B".getBytes(), "0C".getBytes(), "0D".getBytes(), "0E".getBytes(), "0F".getBytes(), "10".getBytes(), "11".getBytes(), "12".getBytes(), "13".getBytes(), "14".getBytes(), "15".getBytes(), "16".getBytes(), "17".getBytes(), "18".getBytes(), "19".getBytes(), "1A".getBytes(), "1B".getBytes(), "1C".getBytes(), "1D".getBytes(), "1E".getBytes(), "1F".getBytes(), "20".getBytes(), "21".getBytes(), "22".getBytes(), "23".getBytes(), "24".getBytes(), "25".getBytes(), "26".getBytes(), "27".getBytes(), "28".getBytes(), "29".getBytes(), "2A".getBytes(), "2B".getBytes(), "2C".getBytes(), "2D".getBytes(), "2E".getBytes(), "2F".getBytes(), "30".getBytes(), "31".getBytes(), "32".getBytes(), "33".getBytes(), "34".getBytes(), "35".getBytes(), "36".getBytes(), "37".getBytes(), "38".getBytes(), "39".getBytes(), "3A".getBytes(), "3B".getBytes(), "3C".getBytes(), "3D".getBytes(), "3E".getBytes(), "3F".getBytes(), "40".getBytes(), "41".getBytes(), "42".getBytes(), "43".getBytes(), "44".getBytes(), "45".getBytes(), "46".getBytes(), "47".getBytes(), "48".getBytes(), "49".getBytes(), "4A".getBytes(), "4B".getBytes(), "4C".getBytes(), "4D".getBytes(), "4E".getBytes(), "4F".getBytes(), "50".getBytes(), "51".getBytes(), "52".getBytes(), "53".getBytes(), "54".getBytes(), "55".getBytes(), "56".getBytes(), "57".getBytes(), "58".getBytes(), "59".getBytes(), "5A".getBytes(), "5B".getBytes(), "5C".getBytes(), "5D".getBytes(), "5E".getBytes(), "5F".getBytes(), "60".getBytes(), "61".getBytes(), "62".getBytes(), "63".getBytes(), "64".getBytes(), "65".getBytes(), "66".getBytes(), "67".getBytes(), "68".getBytes(), "69".getBytes(), "6A".getBytes(), "6B".getBytes(), "6C".getBytes(), "6D".getBytes(), "6E".getBytes(), "6F".getBytes(), "70".getBytes(), "71".getBytes(), "72".getBytes(), "73".getBytes(), "74".getBytes(), "75".getBytes(), "76".getBytes(), "77".getBytes(), "78".getBytes(), "79".getBytes(), "7A".getBytes(), "7B".getBytes(), "7C".getBytes(), "7D".getBytes(), "7E".getBytes(), "7F".getBytes(), "80".getBytes(), "81".getBytes(), "82".getBytes(), "83".getBytes(), "84".getBytes(), "85".getBytes(), "86".getBytes(), "87".getBytes(), "88".getBytes(), "89".getBytes(), "8A".getBytes(), "8B".getBytes(), "8C".getBytes(), "8D".getBytes(), "8E".getBytes(), "8F".getBytes(), "90".getBytes(), "91".getBytes(), "92".getBytes(), "93".getBytes(), "94".getBytes(), "95".getBytes(), "96".getBytes(), "97".getBytes(), "98".getBytes(), "99".getBytes(), "9A".getBytes(), "9B".getBytes(), "9C".getBytes(), "9D".getBytes(), "9E".getBytes(), "9F".getBytes(), "A0".getBytes(), "A1".getBytes(), "A2".getBytes(), "A3".getBytes(), "A4".getBytes(), "A5".getBytes(), "A6".getBytes(), "A7".getBytes(), "A8".getBytes(), "A9".getBytes(), "AA".getBytes(), "AB".getBytes(), "AC".getBytes(), "AD".getBytes(), "AE".getBytes(), "AF".getBytes(), "B0".getBytes(), "B1".getBytes(), "B2".getBytes(), "B3".getBytes(), "B4".getBytes(), "B5".getBytes(), "B6".getBytes(), "B7".getBytes(), "B8".getBytes(), "B9".getBytes(), "BA".getBytes(), "BB".getBytes(), "BC".getBytes(), "BD".getBytes(), "BE".getBytes(), "BF".getBytes(), "C0".getBytes(), "C1".getBytes(), "C2".getBytes(), "C3".getBytes(), "C4".getBytes(), "C5".getBytes(), "C6".getBytes(), "C7".getBytes(), "C8".getBytes(), "C9".getBytes(), "CA".getBytes(), "CB".getBytes(), "CC".getBytes(), "CD".getBytes(), "CE".getBytes(), "CF".getBytes(), "D0".getBytes(), "D1".getBytes(), "D2".getBytes(), "D3".getBytes(), "D4".getBytes(), "D5".getBytes(), "D6".getBytes(), "D7".getBytes(), "D8".getBytes(), "D9".getBytes(), "DA".getBytes(), "DB".getBytes(), "DC".getBytes(), "DD".getBytes(), "DE".getBytes(), "DF".getBytes(), "E0".getBytes(), "E1".getBytes(), "E2".getBytes(), "E3".getBytes(), "E4".getBytes(), "E5".getBytes(), "E6".getBytes(), "E7".getBytes(), "E8".getBytes(), "E9".getBytes(), "EA".getBytes(), "EB".getBytes(), "EC".getBytes(), "ED".getBytes(), "EE".getBytes(), "EF".getBytes(), "F0".getBytes(), "F1".getBytes(), "F2".getBytes(), "F3".getBytes(), "F4".getBytes(), "F5".getBytes(), "F6".getBytes(), "F7".getBytes(), "F8".getBytes(), "F9".getBytes(), "FA".getBytes(), "FB".getBytes(), "FC".getBytes(), "FD".getBytes(), "FE".getBytes(), "FF".getBytes(), }; /** * ASCII byte values for the hex strings. */ public static final byte[][] byteToHexLower = { "00".getBytes(), "01".getBytes(), "02".getBytes(), "03".getBytes(), "04".getBytes(), "05".getBytes(), "06".getBytes(), "07".getBytes(), "08".getBytes(), "09".getBytes(), "0a".getBytes(), "0b".getBytes(), "0c".getBytes(), "0d".getBytes(), "0e".getBytes(), "0f".getBytes(), "10".getBytes(), "11".getBytes(), "12".getBytes(), "13".getBytes(), "14".getBytes(), "15".getBytes(), "16".getBytes(), "17".getBytes(), "18".getBytes(), "19".getBytes(), "1a".getBytes(), "1b".getBytes(), "1c".getBytes(), "1d".getBytes(), "1e".getBytes(), "1f".getBytes(), "20".getBytes(), "21".getBytes(), "22".getBytes(), "23".getBytes(), "24".getBytes(), "25".getBytes(), "26".getBytes(), "27".getBytes(), "28".getBytes(), "29".getBytes(), "2a".getBytes(), "2b".getBytes(), "2c".getBytes(), "2d".getBytes(), "2e".getBytes(), "2f".getBytes(), "30".getBytes(), "31".getBytes(), "32".getBytes(), "33".getBytes(), "34".getBytes(), "35".getBytes(), "36".getBytes(), "37".getBytes(), "38".getBytes(), "39".getBytes(), "3a".getBytes(), "3b".getBytes(), "3c".getBytes(), "3d".getBytes(), "3e".getBytes(), "3f".getBytes(), "40".getBytes(), "41".getBytes(), "42".getBytes(), "43".getBytes(), "44".getBytes(), "45".getBytes(), "46".getBytes(), "47".getBytes(), "48".getBytes(), "49".getBytes(), "4a".getBytes(), "4b".getBytes(), "4c".getBytes(), "4d".getBytes(), "4e".getBytes(), "4f".getBytes(), "50".getBytes(), "51".getBytes(), "52".getBytes(), "53".getBytes(), "54".getBytes(), "55".getBytes(), "56".getBytes(), "57".getBytes(), "58".getBytes(), "59".getBytes(), "5a".getBytes(), "5b".getBytes(), "5c".getBytes(), "5d".getBytes(), "5e".getBytes(), "5f".getBytes(), "60".getBytes(), "61".getBytes(), "62".getBytes(), "63".getBytes(), "64".getBytes(), "65".getBytes(), "66".getBytes(), "67".getBytes(), "68".getBytes(), "69".getBytes(), "6a".getBytes(), "6b".getBytes(), "6c".getBytes(), "6d".getBytes(), "6e".getBytes(), "6f".getBytes(), "70".getBytes(), "71".getBytes(), "72".getBytes(), "73".getBytes(), "74".getBytes(), "75".getBytes(), "76".getBytes(), "77".getBytes(), "78".getBytes(), "79".getBytes(), "7a".getBytes(), "7b".getBytes(), "7c".getBytes(), "7d".getBytes(), "7e".getBytes(), "7f".getBytes(), "80".getBytes(), "81".getBytes(), "82".getBytes(), "83".getBytes(), "84".getBytes(), "85".getBytes(), "86".getBytes(), "87".getBytes(), "88".getBytes(), "89".getBytes(), "8a".getBytes(), "8b".getBytes(), "8c".getBytes(), "8d".getBytes(), "8e".getBytes(), "8f".getBytes(), "90".getBytes(), "91".getBytes(), "92".getBytes(), "93".getBytes(), "94".getBytes(), "95".getBytes(), "96".getBytes(), "97".getBytes(), "98".getBytes(), "99".getBytes(), "9a".getBytes(), "9b".getBytes(), "9c".getBytes(), "9d".getBytes(), "9e".getBytes(), "9f".getBytes(), "a0".getBytes(), "a1".getBytes(), "a2".getBytes(), "a3".getBytes(), "a4".getBytes(), "a5".getBytes(), "a6".getBytes(), "a7".getBytes(), "a8".getBytes(), "a9".getBytes(), "aa".getBytes(), "ab".getBytes(), "ac".getBytes(), "ad".getBytes(), "ae".getBytes(), "af".getBytes(), "b0".getBytes(), "b1".getBytes(), "b2".getBytes(), "b3".getBytes(), "b4".getBytes(), "b5".getBytes(), "b6".getBytes(), "b7".getBytes(), "b8".getBytes(), "b9".getBytes(), "ba".getBytes(), "bb".getBytes(), "bc".getBytes(), "bd".getBytes(), "be".getBytes(), "bf".getBytes(), "c0".getBytes(), "c1".getBytes(), "c2".getBytes(), "c3".getBytes(), "c4".getBytes(), "c5".getBytes(), "c6".getBytes(), "c7".getBytes(), "c8".getBytes(), "c9".getBytes(), "ca".getBytes(), "cb".getBytes(), "cc".getBytes(), "cd".getBytes(), "ce".getBytes(), "cf".getBytes(), "d0".getBytes(), "d1".getBytes(), "d2".getBytes(), "d3".getBytes(), "d4".getBytes(), "d5".getBytes(), "d6".getBytes(), "d7".getBytes(), "d8".getBytes(), "d9".getBytes(), "da".getBytes(), "db".getBytes(), "dc".getBytes(), "dd".getBytes(), "de".getBytes(), "df".getBytes(), "e0".getBytes(), "e1".getBytes(), "e2".getBytes(), "e3".getBytes(), "e4".getBytes(), "e5".getBytes(), "e6".getBytes(), "e7".getBytes(), "e8".getBytes(), "e9".getBytes(), "ea".getBytes(), "eb".getBytes(), "ec".getBytes(), "ed".getBytes(), "ee".getBytes(), "ef".getBytes(), "f0".getBytes(), "f1".getBytes(), "f2".getBytes(), "f3".getBytes(), "f4".getBytes(), "f5".getBytes(), "f6".getBytes(), "f7".getBytes(), "f8".getBytes(), "f9".getBytes(), "fa".getBytes(), "fb".getBytes(), "fc".getBytes(), "fd".getBytes(), "fe".getBytes(), "ff".getBytes() }; public static String bytesToHexString(byte[] data) { return bytesToHexString(data, 0, data.length); } public static String bytesToHexString(byte[] data, int offset, int length) { return bytesToHexString(data, offset, length, false); } public static String bytesToHexString(byte[] data, int offset, int length, boolean space) { length = data.length - offset < length ? data.length - offset : length; StringBuilder buffer = new StringBuilder(); for (int i = 0; i < length; i++) { byte[] bytes = HexTools.ByteToHex[data[offset + i] & 0xFF]; buffer.append((char) bytes[0]); buffer.append((char) bytes[1]); if (space) { buffer.append(" "); } } return buffer.toString(); } /** * The numeric value for the hex digit, return -1 if not valid digit * * @param c * A char representing a hex digit. * * @return The numeric value of the hex digit */ public static int hexDigitToInt(char c) { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return c - '0'; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': return (10 + c) - 'a'; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': return (10 + c) - 'A'; default: return -1; } } public static byte[] hexStringToBytes(String hexString) { byte[] data = new byte[hexString.length() / 2]; for (int i = 0; i < data.length; i++) { data[i] = (byte) (hexStringToInt(hexString.substring(i * 2, (i * 2) + 2)) & 0xFF); } return data; } public static int hexStringToInt(String hexString) { int result = 0; for (int i = 0; i < hexString.length(); i++) { result = (result << 4) + hexDigitToInt(hexString.charAt(i)); } return result; } /** * Evaluate to true if i is a valid hex digit * * @param i * A char representing a hex digit. * * @return true if i is a valid hex digit. */ public static boolean isHexDigit(char i) { return ((i >= '0') && (i <= '9')) || ((i >= 'a') && (i <= 'f')) || ((i >= 'A') && (i <= 'F')); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/hex/HexRow.java0000644000175000017500000000576110751651476023677 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.hex; /** * */ public class HexRow { public static int DEFAULT_LENGTH = 16; private HexData hexData; private int length = DEFAULT_LENGTH; private int offset; /** * */ protected HexRow(HexData hexData, int offset, int length) { super(); this.hexData = hexData; this.offset = offset; this.length = length; } public String getAsString() { return new String(hexData.basicGetBytes(), offset, Math.min(length, hexData.length() - offset)); } public byte getCellValue(int column) { int index = offset + column; if (index >= hexData.length()) { return 0; } else { return hexData.basicGetValue(offset + column); } } public String getCellValueAsString(int column) { int index = offset + column; if (index >= hexData.length()) { return " "; } else { return new String(HexTools.ByteToHex[0xff & hexData .basicGetValue(offset + column)]); } } public int getLength() { return length; } public int getOffset() { return offset; } public void setCellValue(int column, byte value) { hexData.basicSetValue(offset + column, value); } public void setCellValue(int column, String value) { hexData.basicSetValue(offset + column, (byte) HexTools .hexStringToInt(value)); } public void setLength(int width) { this.length = width; } public void setOffset(int offset) { this.offset = offset; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/hex/HexData.java0000644000175000017500000001133610751651476023774 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.hex; /** * */ public class HexData { private byte[] bytes; private int length; private int offset; private int rowWidth = HexRow.DEFAULT_LENGTH; public HexData(byte[] bytes) { this(bytes, 0, bytes.length); } /** * */ public HexData(byte[] bytes, int offset, int length) { super(); byte[] newBytes = new byte[length]; System.arraycopy(bytes, offset, newBytes, 0, length); this.bytes = newBytes; this.offset = 0; this.length = length; } protected byte[] basicGetBytes() { return bytes; } protected byte basicGetValue(int index) { return bytes[index]; } protected void basicSetValue(int index, byte value) { if (index >= (offset + length)) { // do not write out of bounds int newLength = index - offset + 1; byte[] newBytes = new byte[newLength]; System.arraycopy(bytes, offset, newBytes, 0, length); bytes = newBytes; length = newLength; offset = 0; } bytes[index] = value; } public byte getCellValue(int row, int column) { return getRow(row).getCellValue(column); } public String getCellValueAsString(int row, int column) { return getRow(row).getCellValueAsString(column); } public HexRow getRow(int index) { return new HexRow(this, offset + (index * rowWidth), rowWidth); } public int getRowCount() { return (length / rowWidth) + 1; } public HexRow[] getRows() { int count = getRowCount(); HexRow[] rows = new HexRow[count]; for (int i = 0; i < count; i++) { rows[i] = getRow(i); } return rows; } public byte getValue(int index) { return basicGetValue(offset + index); } public String getValueAsString(int index) { return new String(HexTools.ByteToHex[getValue(index)]); } public void insertCellValue(int row, int column, byte value) { int index = (row * rowWidth) + column; int newLength = length + 1; byte[] newBytes = new byte[newLength]; System.arraycopy(bytes, offset, newBytes, 0, index); newBytes[index] = value; System.arraycopy(bytes, offset + index, newBytes, index + 1, length - index); bytes = newBytes; length = newLength; offset = 0; } public int length() { return bytes.length; } public void removeCellValue(int row, int column) { int index = (row * rowWidth) + column; int newLength = length - 1; byte[] newBytes = new byte[newLength]; System.arraycopy(bytes, offset, newBytes, 0, index); System.arraycopy(bytes, offset + index + 1, newBytes, index, length - index - 1); bytes = newBytes; length = newLength; offset = 0; } public void setCellValue(int row, int column, byte value) { getRow(row).setCellValue(column, value); } public void setCellValue(int row, int column, String value) { getRow(row).setCellValue(column, value); } public void setValue(int index, byte value) { basicSetValue(offset + index, value); } public void setValue(int index, String value) { basicSetValue(offset + index, (byte) HexTools.hexStringToInt(value)); } public byte[] toBytes() { byte[] result = new byte[length]; System.arraycopy(bytes, offset, result, 0, length); return result; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/message/0000755000175000017500000000000011412336332022431 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/message/MessageBundle.java0000644000175000017500000001450211411055574026021 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.message; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.text.MessageFormat; import java.util.Locale; import java.util.ResourceBundle; /** * A wrapper class for defining and accessing ResourceBundles. */ public class MessageBundle { protected static URL[] createURLs(String classpath) { if (classpath == null) { return new URL[0]; } String[] names = classpath.split(";"); URL[] urls = new URL[names.length]; try { for (int i = 0; i < urls.length; i++) urls[i] = new File(names[i]).toURI().toURL(); } catch (MalformedURLException e) { return new URL[0]; } return urls; } private ClassLoader classLoader; private Locale locale = Locale.getDefault(); private String path; private ResourceBundle resourceBundle; /** * */ public MessageBundle() { super(); } public MessageBundle(String path, ClassLoader classLoader) { super(); this.path = path; this.classLoader = classLoader; } public MessageBundle(String path, String classpath) { super(); this.path = path; classLoader = new URLClassLoader(createURLs(classpath), Thread .currentThread().getContextClassLoader()); } protected Object basicGetObject(String key) { try { ResourceBundle myBundle = getResourceBundle(); if (myBundle != null) { return myBundle.getObject(key); } return null; } catch (RuntimeException e) { return null; } } public String basicGetString(String key) { try { ResourceBundle myBundle = getResourceBundle(); if (myBundle != null) { return myBundle.getString(key); } return null; } catch (RuntimeException e) { return null; } } protected ResourceBundle createResourceBundle() { if (getClassLoader() == null) { return ResourceBundle.getBundle(getPath(), getLocale()); } return ResourceBundle.getBundle(getPath(), getLocale(), getClassLoader()); } public ClassLoader getClassLoader() { return classLoader; } protected String getFallbackString(String key, Object[] objects) { StringBuilder sb = new StringBuilder(); sb.append("{"); //$NON-NLS-1$ sb.append(key); sb.append("}"); //$NON-NLS-1$ if (objects != null) { for (int i = 0; i < objects.length; i++) { sb.append("["); //$NON-NLS-1$ sb.append(objects[i]); sb.append("]"); //$NON-NLS-1$ } } return sb.toString(); } public Locale getLocale() { return locale; } public Object getObject(String key) { return basicGetObject(key); } public String getPath() { return path; } public ResourceBundle getResourceBundle() { if (resourceBundle == null) { resourceBundle = createResourceBundle(); } return resourceBundle; } public String getString(String key) { String result = basicGetString(key); if (result == null) { return getFallbackString(key, new String[] {}); } return result.replace("''", "'"); } public String getString(String key, Object arg1) { String pattern = basicGetString(key); if (pattern == null) { return getFallbackString(key, new Object[] { arg1 }); } return MessageFormat.format(pattern, new Object[] { arg1 }); } public String getString(String key, Object arg1, Object arg2) { String pattern = basicGetString(key); if (pattern == null) { return getFallbackString(key, new Object[] { arg1, arg2 }); } return MessageFormat.format(pattern, new Object[] { arg1, arg2 }); } public String getString(String key, Object arg1, Object arg2, Object arg3) { String pattern = basicGetString(key); if (pattern == null) { return getFallbackString(key, new Object[] { arg1, arg2, arg3 }); } return MessageFormat.format(pattern, new Object[] { arg1, arg2, arg3 }); } public String getString(String key, Object arg1, Object arg2, Object arg3, Object arg4) { String pattern = basicGetString(key); if (pattern == null) { return getFallbackString(key, new Object[] { arg1, arg2, arg3, arg4 }); } return MessageFormat.format(pattern, new Object[] { arg1, arg2, arg3, arg4 }); } public String getString(String key, Object[] args) { String pattern = basicGetString(key); if (pattern == null) { return getFallbackString(key, args); } return MessageFormat.format(pattern, args); } public boolean lookupString(String key) { String result = basicGetString(key); if (result == null) { return false; } return true; } public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } public void setLocale(Locale locale) { this.locale = locale; } public void setPath(String resourcesName) { this.path = resourcesName; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/message/Message.java0000644000175000017500000000500610751651500024663 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.message; /** * * */ public class Message { private String key; private String suffix; private Class clazz; private MessageBundle bundle; public Message(Object implementor, String suffix) { if (implementor instanceof Class) { this.clazz = (Class) implementor; } else { this.clazz = implementor.getClass(); } this.suffix = suffix; } public Message(MessageBundle bundle, String key) { this.bundle = bundle; this.key = key; } public MessageBundle getBundle() { if (bundle == null) { bundle = MessageBundleTools.getMessageBundle(clazz); } return bundle; } public String getKey() { if (key == null) { key = MessageBundleTools.getClassName(this.clazz) + "." + suffix; } return key; } public Object getClazz() { return clazz; } public String get() { return getBundle().getString(getKey()); } public String toString() { return get(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/message/LocaleTools.java0000644000175000017500000000167611412330300025513 0ustar twernertwernerpackage de.intarsys.tools.message; import java.util.Locale; public class LocaleTools { /** * @param locale * locale * @return the windows LCID (Language Code Id) */ public static int getLcid(Locale locale) { String lang = locale.getLanguage(); if (Locale.GERMAN.getLanguage().equals(lang)) { return 0x0407; } if (Locale.ENGLISH.getLanguage().equals(lang)) { return 0x0409; } if (Locale.ITALIAN.getLanguage().equals(lang)) { return 0x0410; } if (Locale.FRENCH.getLanguage().equals(lang)) { return 0x040c; } if (Locale.JAPANESE.getLanguage().equals(lang)) { return 0x0411; } if (Locale.KOREAN.getLanguage().equals(lang)) { return 0x0412; } if (Locale.CHINESE.getLanguage().equals(lang)) { return 0x0804; } /** Spanish */ if ("es".equals(lang)) { //$NON-NLS-1$ return 0x040a; } return 0; } private LocaleTools() { // } } libisrt-java-4.8.20100629/src/de/intarsys/tools/message/IMessageBundleAccess.java0000644000175000017500000000402211260360260027241 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.message; /** * An interface indicating support for assigning a {@link MessageBundle}. */ public interface IMessageBundleAccess extends IMessageBundleSupport { /** * Associate the message bundle with the receiver. * * @param messageBundle * A {@link MessageBundle} instance suitable to load messages * associated with the receiver context. */ public void setMessageBundle(MessageBundle messageBundle); } libisrt-java-4.8.20100629/src/de/intarsys/tools/message/TextOrientation.java0000644000175000017500000000460111032427260026434 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.message; import java.awt.ComponentOrientation; import java.util.Locale; /* * DOCME */ public class TextOrientation { public static TextOrientation get() { return new TextOrientation(Locale.getDefault()); } public static TextOrientation getHebrew() { return new TextOrientation(new Locale("iw")); } private Locale locale; private ComponentOrientation orientation; public TextOrientation(Locale locale) { this.locale = locale; } protected ComponentOrientation getOrientation() { if (orientation == null) { orientation = ComponentOrientation.getOrientation(locale); } return orientation; } public boolean isHorizontal() { return getOrientation().isHorizontal(); } public boolean isLeftToRight() { return getOrientation().isLeftToRight(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/message/CommonMessage.java0000644000175000017500000000104511175377374026052 0ustar twernertwernerpackage de.intarsys.tools.message; public class CommonMessage { public final static MessageBundle Messages = MessageBundleTools .getMessageBundle(CommonMessage.class); public static final Message InternalError = new Message(Messages, "CommonMessage.InternalError"); //$NON-NLS-1$ public static final Message InternalErrorTitle = new Message(Messages, "CommonMessage.InternalErrorTitle"); //$NON-NLS-1$ public static final Message ErrorTitle = new Message(Messages, "CommonMessage.ErrorTitle"); //$NON-NLS-1$ } libisrt-java-4.8.20100629/src/de/intarsys/tools/message/IMessageBundleSupport.java0000644000175000017500000000377110751651500027532 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.message; /** * An interface indicating support for accessing a {@link MessageBundle}. */ public interface IMessageBundleSupport { /** * A {@link MessageBundle} instance suitable to load messages associated * with the receiver context. * * @return A {@link MessageBundle} instance suitable to load messages * associated with the receiver context. */ public MessageBundle getMessageBundle(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/message/MessageBundleTools.java0000644000175000017500000000546210751651500027044 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.message; public class MessageBundleTools { public static String MSG = "messages"; //$NON-NLS-1$ public static MessageBundle getMessageBundle(Class clazz) { return new MessageBundle(getBundleName(clazz), clazz.getClassLoader()); } public static MessageBundle getMessageBundle(String name, ClassLoader classloader) { return new MessageBundle(name, classloader); } public static String getBundleName(Class clazz) { return getPackageName(clazz) + "." + MSG; //$NON-NLS-1$ } public static String getBundleName(String className) { return getPackageName(className) + "." + MSG; //$NON-NLS-1$ } public static String getPackageName(Class clazz) { return getPackageName(clazz.getName()); } public static String getPackageName(String className) { int index = className.lastIndexOf('.'); if (index >= 0) { return className.substring(0, index); } else { return ""; //$NON-NLS-1$ } } public static String getClassName(Class clazz) { return getClassName(clazz.getName()); } public static String getClassName(String className) { int index = className.lastIndexOf('.'); if (index >= 0) { return className.substring(index + 1); } else { return className; } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/prompter/0000755000175000017500000000000011412336332022655 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/prompter/IPrompter.java0000644000175000017500000000023611245557126025454 0ustar twernertwernerpackage de.intarsys.tools.prompter; public interface IPrompter { public void setMessage(String message); public void setTitle(String title); } libisrt-java-4.8.20100629/src/de/intarsys/tools/attribute/0000755000175000017500000000000011412336332023010 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/attribute/IAttributeSupport.java0000644000175000017500000000537311412330204027324 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.attribute; /** * This interface declares support for "generic attributes". * *

* This means the object implementing this interface may be extended * transparently by its clients with name/value pairs. These attributes and * their values are stored but not interpreted by the object that implements * this interface. *

*/ public interface IAttributeSupport { /** * Get an attribute value from the context * * @param key * the name of the attribute to get * * @return The value of the attribute key */ public Object getAttribute(Object key); /** * Remove an attribute binding in the context * * @param key * the name of the attribute to remove * * @return The previously associated value for key */ public Object removeAttribute(Object key); /** * Set the value of an attribute in the context * * @param key * the name of the attribute to set * @param value * the new value the attribute * * @return The previously associated value for key */ public Object setAttribute(Object key, Object value); } libisrt-java-4.8.20100629/src/de/intarsys/tools/attribute/Attribute.java0000644000175000017500000000404111133647456025631 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.attribute; /** * A generic object to be used as a key with {@link IAttributeSupport}. *

* ATTENTION: Do NOT override equals as this is intended to be * used in secure environments where foreign code should not be able to gain * access to attributes. * */ public class Attribute { final private String name; public Attribute(String name) { this.name = name; } @Override public String toString() { return name; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/attribute/AttributeMap.java0000644000175000017500000001044611411055570026262 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.attribute; import java.util.Map; /** * A default implementation for {@link IAttributeSupport}. The API is "doubled" * to be usable as a simple replacement for a {@link Map}. *

* The keys are looked up using object identity! */ final public class AttributeMap implements IAttributeSupport { private Object[] keys; private Object[] values; private int length = 0; public AttributeMap() { this(4); } public AttributeMap(int initialCapacity) { keys = new Object[initialCapacity]; values = new Object[initialCapacity]; } synchronized public void clear() { for (int i = 0; i < length; i++) { values[i] = null; keys[i] = null; } length = 0; } public Object get(Object key) { return getAttribute(key); } synchronized public Object getAttribute(Object key) { if (key instanceof String) { key = ((String) key).intern(); } for (int i = 0; i < length; i++) { if (keys[i] == key) { return values[i]; } } return null; } /** * The keys used in this attribute lookup map. *

* !! This is not intended to be published to client code, as this would * compromise IAttributeSupport security !! * * @return The keys used in this attribute lookup map. */ public Object[] getKeys() { Object[] tempKeys = new Object[length]; System.arraycopy(keys, 0, tempKeys, 0, length); return tempKeys; } public Object put(Object key, Object o) { return setAttribute(key, o); } public Object remove(Object key) { return removeAttribute(key); } synchronized public Object removeAttribute(Object key) { if (key instanceof String) { key = ((String) key).intern(); } for (int i = 0; i < length; i++) { if (keys[i] == key) { Object oldValue = values[i]; length--; System.arraycopy(keys, i + 1, keys, i, length - i); System.arraycopy(values, i + 1, values, i, length - i); values[length] = null; keys[length] = null; return oldValue; } } return null; } synchronized public Object setAttribute(Object key, Object value) { if (key instanceof String) { key = ((String) key).intern(); } int i = 0; // replace existing while (i < length) { if (keys[i] == key) { Object oldValue = values[i]; values[i] = value; return oldValue; } i++; } if (i >= values.length) { // expand Object[] newKeys = new Object[length + 4]; System.arraycopy(keys, 0, newKeys, 0, length); keys = newKeys; Object[] newValues = new Object[length + 4]; System.arraycopy(values, 0, newValues, 0, length); values = newValues; } // add new values[length] = value; keys[length] = key; length++; return null; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/0000755000175000017500000000000011412336332022126 5ustar twernertwernerlibisrt-java-4.8.20100629/src/de/intarsys/tools/event/AttributeChangedEvent.java0000644000175000017500000000560011164634706027223 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * An event representing an objects state change. */ public class AttributeChangedEvent extends Event { public static final EventType ID = new EventType( AttributeChangedEvent.class.getName()); private Object attribute; private Object oldValue; private Object newValue; public AttributeChangedEvent(Object source, Object attribute, Object oldValue, Object newValue) { super(source); this.attribute = attribute; this.oldValue = oldValue; this.newValue = newValue; } /** * The attribute slot that has changed. * * @return The attribute slot that has changed. */ public Object getAttribute() { return attribute; } @Override public EventType getEventType() { return ID; } /** * The new value of the attribute. * * @return The new value of the attribute. */ public Object getNewValue() { return newValue; } /** * The previous value of the attribute. * * @return The previous value of the attribute. */ public Object getOldValue() { return oldValue; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("attribute '"); sb.append(attribute); sb.append("' changed on '"); sb.append(getSource()); sb.append("'"); return sb.toString(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/AttributeChangeListener.java0000644000175000017500000000435111044323606027554 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * A convenience implementation for listening to attribute change events. */ public abstract class AttributeChangeListener implements INotificationListener { private final Object attribute; /** * */ public AttributeChangeListener(Object attribute) { super(); this.attribute = attribute; } public abstract void handleAttributeChange(AttributeChangedEvent event); public final void handleEvent(Event event) { if ((((AttributeChangedEvent) event).getAttribute() == null) || ((AttributeChangedEvent) event).getAttribute().equals( attribute)) { handleAttributeChange((AttributeChangedEvent) event); } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/EventTools.java0000644000175000017500000000361311411055572025101 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; import de.intarsys.tools.functor.IArgs; public class EventTools { public static IRequestEvent getEvent(IArgs args) { return (IRequestEvent) args.get(IRequestEvent.ARG_EVENT); } public static IRequestEvent getJEvent(IArgs args) { return (IRequestEvent) args.get(IRequestEvent.ARG_JEVENT); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/IEvent.java0000644000175000017500000000540011044323606024163 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * An object indicating an event. * */ public interface IEvent { /** * Indicate that this event does not need to be propagated any further as it * is already processed by some listener. */ public void consume(); /** * A name for this event. * * @return A name for this event. */ public String getName(); /** * The object originating the event instance. * * @return The object originating the event instance. */ public Object getSource(); /** * A type for this event. * * @return A type for this event. */ public EventType getEventType(); /** * true if this event is already consumed by some listener. * * @return true if this event is already consumed by some * listener. */ public boolean isConsumed(); /** * true if this event is already vetoed by some listener. * * @return true if this event is already vetoed by some * listener. */ public boolean isVetoed(); /** * Indicate that the behavior associated with this event should not be * performed by the source. */ public void veto(); } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/OkEvent.java0000644000175000017500000000364011044323606024350 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * An event indicating the positively acknowledged outcome of an execution. * */ public class OkEvent extends Event { public static final EventType ID = new EventType(OkEvent.class.getName()); public OkEvent(Object source) { super(source); } @Override public EventType getEventType() { return ID; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/NotificationSupportProxy.java0000644000175000017500000000176211204240614030060 0ustar twernertwernerpackage de.intarsys.tools.event; public class NotificationSupportProxy implements INotificationSupport { private EventDispatcher dispatcher = new EventDispatcher(this); private INotificationSupport delegate; public void addNotificationListener(EventType type, INotificationListener listener) { dispatcher.addNotificationListener(type, listener); if (delegate != null) { delegate.addNotificationListener(type, listener); } } public INotificationSupport getDelegate() { return delegate; } public void removeNotificationListener(EventType type, INotificationListener listener) { dispatcher.removeNotificationListener(type, listener); if (delegate != null) { delegate.removeNotificationListener(type, listener); } } public void setDelegate(INotificationSupport pDelegate) { if (delegate != null) { dispatcher.detach(delegate); } this.delegate = pDelegate; if (delegate != null) { dispatcher.attach(delegate); } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/EventType.java0000644000175000017500000000401711411055572024721 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; import java.io.Serializable; /** * The type of an {@link Event}. *

* This is an unique object representing the type / class of an event instance. * */ public class EventType implements Serializable { public static final EventType ALWAYS = new EventType("always"); //$NON-NLS-1$ final private String name; public EventType(String name) { this.name = name; } public String getName() { return name; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/ResumedEvent.java0000644000175000017500000000363411306225252025405 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * An event indicating that a component is resumed. * */ public class ResumedEvent extends Event { public static final EventType ID = new EventType(ResumedEvent.class .getName()); public ResumedEvent(Object source) { super(source); } @Override public EventType getEventType() { return ID; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/CancelRequestedEvent.java0000644000175000017500000000370111044323606027044 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * An event indicating the request to deny positive termination. * */ public class CancelRequestedEvent extends Event { public static final EventType ID = new EventType(CancelRequestedEvent.class .getName()); public CancelRequestedEvent(Object source) { super(source); } @Override public EventType getEventType() { return ID; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/SuspendedEvent.java0000644000175000017500000000364311306225252025733 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * An event indicating that a component is supended. * */ public class SuspendedEvent extends Event { public static final EventType ID = new EventType(SuspendedEvent.class .getName()); public SuspendedEvent(Object source) { super(source); } @Override public EventType getEventType() { return ID; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/Event.java0000644000175000017500000000542111044323606024055 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; import java.util.EventObject; /** * Abstract superclass for event implementations. * */ public class Event extends EventObject implements IEvent { public static final Object ID_ALL = new Object(); public static final EventType ID = new EventType("Event"); /** Flag if the event is already handled. */ protected boolean consumed = false; /** * Flag if execution of the action that is announced by the event is * interrupted by one of the listeners. */ protected boolean veto = false; /** * Create a new event object. * * @param source * The object that created the event. */ public Event(Object source) { super(source); } public void consume() { consumed = true; } public EventType getEventType() { return ID; } public String getName() { return getEventType().getName(); } public boolean getRc() { return !isVetoed(); } public boolean isConsumed() { return consumed; } public boolean isVetoed() { return veto; } public void setRc(boolean value) { setVeto(!value); } public void setVeto(boolean value) { veto = value; } public void veto() { veto = true; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/IEventDispatcher.java0000644000175000017500000000333511044323606026177 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * An object that supports event broadcasting. */ public interface IEventDispatcher { public void triggerEvent(Event event); } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/RequestEventFacade.java0000644000175000017500000000671111355113426026517 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * */ public class RequestEventFacade extends AbstractEventFacade { /** * */ public RequestEventFacade(RequestEvent event) { super(event); } /* * (non-Javadoc) * * @see de.intarsys.tools.event.IEvent#consume() */ public void consume() { ((RequestEvent) object).consume(); } public Object getArgs() { return ((RequestEvent) object).getArgs(); } public EventType getEventType() { return ((RequestEvent) object).getEventType(); } public String getName() { return ((RequestEvent) object).getName(); } public boolean getRc() { return ((RequestEvent) object).getRc(); } public Object getSource() { return createFacade(((RequestEvent) object).getSource()); } public Object getTarget() { return createFacade(((RequestEvent) object).getTarget()); } @Override public String getType() { return ((RequestEvent) object).getEventType().getName(); } public Object getValue() { return createFacade(((RequestEvent) object).getValue()); } @Override public boolean getVeto() { return ((RequestEvent) object).isVetoed(); } public boolean isConsumed() { return ((RequestEvent) object).isConsumed(); } /* * (non-Javadoc) * * @see de.intarsys.tools.event.IEvent#isVetoed() */ public boolean isVetoed() { return ((RequestEvent) object).isVetoed(); } public void setRc(boolean value) { ((RequestEvent) object).setRc(value); } public void setTarget(Object target) { ((RequestEvent) object).setTarget(target); } public void setValue(Object value) { ((RequestEvent) object).setValue(value); } @Override public void setVeto(boolean value) { ((RequestEvent) object).setVeto(value); } /* * (non-Javadoc) * * @see de.intarsys.tools.event.IEvent#veto() */ public void veto() { ((RequestEvent) object).veto(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/CancelEvent.java0000644000175000017500000000366111044323606025167 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * An event indicating the negatively acknowledged outcome of an execution. * */ public class CancelEvent extends Event { public static final EventType ID = new EventType(CancelEvent.class .getName()); public CancelEvent(Object source) { super(source); } @Override public EventType getEventType() { return ID; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/AbstractEventFacade.java0000644000175000017500000000367011411055572026633 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; import de.intarsys.tools.facade.Facade; /** * */ abstract public class AbstractEventFacade extends Facade implements IRequestEvent { /** * */ protected AbstractEventFacade(Object impl) { super(impl); } abstract public String getType(); abstract public boolean getVeto(); abstract public void setVeto(boolean value); } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/IChangeSupport.java0000644000175000017500000000455611044323606025677 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * The implementor supports the broadcast of attribute change notifications to * INotificationListener objects. * * @deprecated use {@link INotificationSupport} */ @Deprecated public interface IChangeSupport { /** * Add listener to the collection of objects to be informed * when the receiver triggers a change event. * * @param listener * The object to be informed about change event occurrence */ public void addChangeListener(INotificationListener listener); /** * Remove listener from the collection of objects to be * informed about change events. * * @param listener * The object registered for the event */ public void removeChangeListener(INotificationListener listener); } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/IRequestEvent.java0000644000175000017500000000401111355113426025533 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * */ public interface IRequestEvent extends IEvent { public static final String ARG_EVENT = "event"; //$NON-NLS-1$ public static final String ARG_JEVENT = "jEvent"; //$NON-NLS-1$ public static final String DEPR_ARG_JEVENT = "jevent"; //$NON-NLS-1$ public boolean getRc(); public Object getTarget(); public Object getValue(); public void setRc(boolean value); public void setValue(Object value); } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/INotificationListener.java0000644000175000017500000000434111044323606027241 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; import java.util.EventListener; /** * Called to inform a listener about an event occurrence. * *

* INotificationListener may be attached via * INotificationSupport.addNotificationListener to express * interest in a special type of events. To end notification, the listener is * detached via INotificationSupport.removeNotificationListener *

*/ public interface INotificationListener extends EventListener { /** * Called when an event occurs. * * @param event * The event object giving detail information about the context. */ public void handleEvent(Event event); } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/RequestEvent.java0000644000175000017500000000643611355113426025437 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; import de.intarsys.tools.facade.IFacade; import de.intarsys.tools.facade.IFacadeSupport; import de.intarsys.tools.string.StringTools; /** * */ public class RequestEvent extends Event implements IRequestEvent, IFacadeSupport { public static final EventType TYPE = new EventType("Generic"); //$NON-NLS-1$ private EventType type; private String name; private Object target; private Object value; private Object args; private IFacade facade; public RequestEvent(Object source) { this(source, TYPE, StringTools.EMPTY); } /** * @param source * @param type * TODO * @param name * TODO */ public RequestEvent(Object source, EventType type, String name) { super(source); this.type = type; this.name = name; } /* * (non-Javadoc) * * @see de.intarsys.tools.facade.IFacadeSupport#createFacade() */ public IFacade createFacade() { if (facade == null) { facade = new RequestEventFacade(this); } return facade; } public Object getArgs() { return args; } @Override public EventType getEventType() { return type; } @Override public String getName() { return name; } public Object getTarget() { return target; } public Object getValue() { return value; } public void setArgs(Object args) { this.args = args; } /* * (non-Javadoc) * * @see de.intarsys.tools.event.Event#setRc(boolean) */ @Override public void setRc(boolean value) { super.setRc(value); setValue(Boolean.valueOf(value)); } public void setTarget(Object target) { this.target = target; } public void setValue(Object value) { this.value = value; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/ActivatedEvent.java0000644000175000017500000000366311044323606025710 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * An event indicating the activation of an application component. * */ public class ActivatedEvent extends Event { public static final EventType ID = new EventType(ActivatedEvent.class .getName()); public ActivatedEvent(Object source) { super(source); } @Override public EventType getEventType() { return ID; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/LifecycleWatchdog.java0000644000175000017500000002527311411055572026365 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import de.intarsys.tools.component.IStartStop; /** * A tool for intercepting and handling lifecycle related events. * */ abstract public class LifecycleWatchdog implements IStartStop { final private INotificationSupport object; final private List armedObjects = new ArrayList(); private boolean started = false; private String label; /** * A listener for object lifecycle events */ final protected INotificationListener listenObjectLifecycle = new INotificationListener() { public void handleEvent(Event event) { onObjectLifecycleEvent(event); } @Override public String toString() { return LifecycleWatchdog.this.toString(); } }; /** * A listener for factory lifecycle events */ final protected INotificationListener listenFactoryLifecycle = new INotificationListener() { public void handleEvent(Event event) { onFactoryLifecycleEvent(event); } @Override public String toString() { return LifecycleWatchdog.this.toString(); } }; public LifecycleWatchdog(INotificationSupport factory) { super(); if (factory == null) { throw new NullPointerException("watchdog must have a factory"); } this.object = factory; } protected void arm(INotificationSupport object) { // synchronized (armedObjects) { armedObjects.add(object); } // object.addNotificationListener(StartedEvent.ID, listenObjectLifecycle); object .addNotificationListener(ActivatedEvent.ID, listenObjectLifecycle); object.addNotificationListener(DeactivatedEvent.ID, listenObjectLifecycle); object.addNotificationListener(StopRequestedEvent.ID, listenObjectLifecycle); object.addNotificationListener(StoppedEvent.ID, listenObjectLifecycle); } protected void disarm(INotificationSupport object) { // synchronized (armedObjects) { armedObjects.remove(object); } // object.removeNotificationListener(StartedEvent.ID, listenObjectLifecycle); object.removeNotificationListener(ActivatedEvent.ID, listenObjectLifecycle); object.removeNotificationListener(DeactivatedEvent.ID, listenObjectLifecycle); object.removeNotificationListener(StopRequestedEvent.ID, listenObjectLifecycle); object.removeNotificationListener(StoppedEvent.ID, listenObjectLifecycle); } public String getLabel() { return label; } public INotificationSupport getObject() { return object; } public boolean isStarted() { return started; } final protected void myFactoryStarted(Event event) { start(); } final protected void myFactoryStopped(Event event) { stop(); } /** * A previously armed IObject is activated. * * @param event * The activation event instance */ final protected void myObjectActivated(Object object) { objectActivated(object); } /** * A new IObject is created and armed for further notification. * * @param event * The activation event instance */ final protected void myObjectCreated(Object object) { if (!supports(object)) { return; } arm((INotificationSupport) object); objectCreated(object); } /** * A previously armed IObject is deactivated. * * @param event * The activation event instance */ final protected void myObjectDeactivated(Object object) { objectDeactivated(object); } /** * A previously armed IObject is destroyed. * * @param event * The activation event instance */ final protected void myObjectDestroyed(Object object) { disarm((INotificationSupport) object); objectDestroyed(object); } /** * A previously armed IObject is started. * * @param event * The activation event instance */ final protected void myObjectStarted(Object object) { objectStarted(object); } /** * A previously armed IObject is stopped. All notification listeners are * removed. * * @param event * The activation event instance */ final protected void myObjectStopped(Object object) { disarm((INotificationSupport) object); objectStopped(object); } /** * A previously armed IObject is requested to stop. * * @param event * The event instance */ final protected boolean myObjectStopRequested(Object object) { return objectStopRequested(object); } /** * Redefine to get informed when an IObject is activated. * * @param object * The object that was activated. */ protected void objectActivated(Object object) { // redefine } /** * Redefine to get informed when an IObject is created. * * @param object * The object that was created, */ protected void objectCreated(Object object) { // redefine } /** * Redefine to get informed when an IObject is deactivated. * * @param object * the object that was deactivated. */ protected void objectDeactivated(Object object) { // redefine } /** * Redefine to get informed when an IObject is destroyed. * * @param object * The object that was destroyed. */ protected void objectDestroyed(Object object) { // redefine } /** * Redefine to get informed when an IObject is started. * * @param object * The object that was started. */ protected void objectStarted(Object object) { // redefine } /** * Redefine to get informed when an IObject is requested to stop. * * @param object * The object that was stopped. */ protected void objectStopped(Object object) { // redefine } /** * Redefine to get informed when an IObject is stopped. * * @param object * The object that should be stopped. */ protected boolean objectStopRequested(Object object) { // redefine return true; } /** * A previously armed object is activated. * * @param event * The activation event instance */ protected void onFactoryLifecycleEvent(Event event) { if (event instanceof StartedEvent) { myFactoryStarted(event); } else if (event instanceof StoppedEvent) { myFactoryStopped(event); } else { // ?? } } /** * A previously armed object is activated. * * @param event * The activation event instance */ protected void onObjectLifecycleEvent(Event event) { if (event instanceof CreatedEvent) { CreatedEvent cpe = (CreatedEvent) event; myObjectCreated(cpe.getInstance()); } else if (event instanceof DestroyedEvent) { myObjectDestroyed(event.getSource()); } else if (event instanceof StartedEvent) { myObjectStarted(event.getSource()); } else if (event instanceof ActivatedEvent) { myObjectActivated(event.getSource()); } else if (event instanceof DeactivatedEvent) { myObjectDeactivated(event.getSource()); } else if (event instanceof StopRequestedEvent) { event.setRc(myObjectStopRequested(event.getSource())); } else if (event instanceof StoppedEvent) { myObjectStopped(event.getSource()); } else { // ?? } } public void setLabel(String label) { this.label = label; } /** * Arm the watchdog itself. From now it will listen to the creation of new * instances. * * @see de.intarsys.tools.component.IStartStop#start() */ public void start() { object.addNotificationListener(CreatedEvent.ID, listenObjectLifecycle); started = true; } /** * Arm the watchdog itself. From now it will listen to the creation of new * instances. * * @see de.intarsys.tools.component.IStartStop#start() */ public void startAuto() { object.addNotificationListener(StartedEvent.ID, listenFactoryLifecycle); } /** * Disarm the watchdog itself. From now it will not longer listen to the * creation of new instances. * * @see de.intarsys.tools.component.IStartStop#stop() */ public void stop() { object.removeNotificationListener(CreatedEvent.ID, listenObjectLifecycle); // disarm all already armed IObject instances, use copy to // avoid concurrent modification List toBeDisarmed; synchronized (armedObjects) { toBeDisarmed = new ArrayList(armedObjects); } for (Iterator it = toBeDisarmed.iterator(); it.hasNext();) { INotificationSupport object = (INotificationSupport) it.next(); disarm(object); } } /* * (non-Javadoc) * * @see de.intarsys.tools.component.IStartStop#stopRequested() */ public boolean stopRequested(Set visited) { return true; } /** * Answer true if we are interested in the object * instance. If we are interested the watchdog will register itself for the * lifecycle events. * * @param object * The newly created object. * @return Answer true if we are interested in the * object instance. */ protected boolean supports(Object object) { return true; } @Override public String toString() { return getLabel(); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/INotificationSupport.java0000644000175000017500000000504611044323606027133 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * The implementor supports registration of {@link INotificationListener} * objects to be informed about event. */ public interface INotificationSupport { /** * Add listener to the collection of objects to be informed * when the receiver triggers an event of type name. * * @param type * The event type we are interested in. * @param listener * The object to be informed about an event occurrence */ public void addNotificationListener(EventType type, INotificationListener listener); /** * Remove listener from the collection of objects to be * informed about events of type name. * * @param type * The event type we are no longer interested in. * @param listener * The object registered for the event till now. */ public void removeNotificationListener(EventType type, INotificationListener listener); } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/StopRequestedEvent.java0000644000175000017500000000416011044404144026601 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; import java.util.Set; /** * An event indicating that the stop for an application component was requested. * */ public class StopRequestedEvent extends Event { public static final EventType ID = new EventType(StopRequestedEvent.class .getName()); final private Set visited; public StopRequestedEvent(Object source, Set visited) { super(source); this.visited = visited; } @Override public EventType getEventType() { return ID; } public Set getVisited() { return visited; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/EventDispatcher.java0000644000175000017500000001171211411055572026066 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; import java.io.Serializable; /** * Helper object for management and dispatching of events. */ public class EventDispatcher implements INotificationSupport, INotificationListener, Serializable { /** The owner originating the events */ private final Object owner; private EventType[] types = new EventType[4]; private INotificationListener[] listeners = new INotificationListener[4]; public EventDispatcher(Object pOwner) { super(); owner = pOwner; } public synchronized void addNotificationListener(EventType type, INotificationListener listener) { if (listener == null) { throw new NullPointerException("listener may not be null"); } // if (hasListener(type, listener)) { // // debug code // toString(); // } int length = listeners.length; int i = 0; while (i < length) { if (listeners[i] == null) { break; } i++; } if (i >= length) { INotificationListener[] tempListeners = new INotificationListener[length + 4]; System.arraycopy(listeners, 0, tempListeners, 0, length); listeners = tempListeners; EventType[] tempIds = new EventType[length + 4]; System.arraycopy(types, 0, tempIds, 0, length); types = tempIds; } types[i] = type; listeners[i] = listener; } synchronized public void attach(INotificationSupport support) { int length = listeners.length; for (int i = 0; i < length; i++) { EventType tempType = types[i]; if (tempType != null) { support.addNotificationListener(tempType, listeners[i]); } } } public synchronized void clear() { types = new EventType[4]; listeners = new INotificationListener[4]; } synchronized public void detach(INotificationSupport support) { int length = listeners.length; for (int i = 0; i < length; i++) { EventType tempType = types[i]; if (tempType != null) { support.removeNotificationListener(tempType, listeners[i]); } } } public Object getOwner() { return owner; } public void handleEvent(Event event) { Object typeId = event.getEventType(); int length = listeners.length; for (int i = 0; i < length; i++) { Object id = types[i]; if (id != typeId && id != EventType.ALWAYS) { continue; } listeners[i].handleEvent(event); } } protected boolean hasListener(EventType type, INotificationListener listener) { int length = listeners.length; int i = 0; while (i < length) { if (types[i] == type && listeners[i] == listener) { return true; } i++; } return false; } public synchronized boolean isEmpty() { for (int i = 0; i < listeners.length; i++) { if (listeners[i] != null) { return false; } } return true; } public synchronized void removeNotificationListener(EventType type, INotificationListener listener) { int length = listeners.length; int i = 0; while (i < length) { if (types[i] == type && listeners[i] == listener) { types[i] = null; listeners[i] = null; break; } i++; } } public void triggerEvent(Event event) { handleEvent(event); } public void triggerEventReverse(Event event) { Object typeId = event.getEventType(); for (int i = listeners.length; i >= 0; i--) { Object id = types[i]; if (id != typeId && id != EventType.ALWAYS) { continue; } listeners[i].handleEvent(event); } } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/CommonNotificationSupport.java0000644000175000017500000000530611110305166030165 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * A convenience implementation to plugin {@link INotificationSupport}. */ public class CommonNotificationSupport implements INotificationSupport { private EventDispatcher dispatcher = new EventDispatcher(this); public void addNotificationListener(EventType type, INotificationListener listener) { dispatcher.addNotificationListener(type, listener); } protected void markDirty(Object attribute, Object oldValue, Object newValue) { // } public void removeNotificationListener(EventType type, INotificationListener listener) { dispatcher.removeNotificationListener(type, listener); } protected void triggerChanged(Object attribute, Object oldValue, Object newValue) { markDirty(attribute, oldValue, newValue); triggerChangedBasic(attribute, oldValue, newValue); } protected void triggerChangedBasic(Object attribute, Object oldValue, Object newValue) { AttributeChangedEvent event = new AttributeChangedEvent(this, attribute, oldValue, newValue); triggerEvent(event); } protected void triggerEvent(Event event) { dispatcher.triggerEvent(event); } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/SelectionEvent.java0000644000175000017500000000362411304677012025730 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * An event indicating a selection. * */ public class SelectionEvent extends Event { public static final EventType ID = new EventType(SelectionEvent.class .getName()); public SelectionEvent(Object source) { super(source); } @Override public EventType getEventType() { return ID; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/DeactivatedEvent.java0000644000175000017500000000367211044323606026221 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * An event indicating the de-activation of an application component. * */ public class DeactivatedEvent extends Event { public static final EventType ID = new EventType(DeactivatedEvent.class .getName()); public DeactivatedEvent(Object source) { super(source); } @Override public EventType getEventType() { return ID; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/CreatedEvent.java0000644000175000017500000000417411044323606025351 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * An event indicating the creation of a new instance by a factory. * */ public class CreatedEvent extends Event { public static final EventType ID = new EventType(CreatedEvent.class .getName()); /** The instance created by a factory */ private Object instance; public CreatedEvent(Object source) { super(source); } public Object getInstance() { return instance; } @Override public EventType getEventType() { return ID; } public void setInstance(Object instance) { this.instance = instance; } }libisrt-java-4.8.20100629/src/de/intarsys/tools/event/StoppedEvent.java0000644000175000017500000000364511044323606025422 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * An event indicating the stop of an application component. * */ public class StoppedEvent extends Event { public static final EventType ID = new EventType(StoppedEvent.class .getName()); public StoppedEvent(Object source) { super(source); } @Override public EventType getEventType() { return ID; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/OkRequestedEvent.java0000644000175000017500000000366411044323606026240 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * An event indicating the the request to positively terminate. * */ public class OkRequestedEvent extends Event { public static final EventType ID = new EventType(OkRequestedEvent.class .getName()); public OkRequestedEvent(Object source) { super(source); } @Override public EventType getEventType() { return ID; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/StartedEvent.java0000644000175000017500000000364611044323606025413 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * An event indicating the start of an application component. * */ public class StartedEvent extends Event { public static final EventType ID = new EventType(StartedEvent.class .getName()); public StartedEvent(Object source) { super(source); } @Override public EventType getEventType() { return ID; } } libisrt-java-4.8.20100629/src/de/intarsys/tools/event/DestroyedEvent.java0000644000175000017500000000415411044323606025742 0ustar twernertwerner/* * Copyright (c) 2007, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys 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 de.intarsys.tools.event; /** * An event indicating the destruction of an instance. * */ public class DestroyedEvent extends Event { public static final EventType ID = new EventType(DestroyedEvent.class .getName()); /** The instance destroyed */ private Object instance; public DestroyedEvent(Object source) { super(source); } public Object getInstance() { return instance; } @Override public EventType getEventType() { return ID; } public void setInstance(Object instance) { this.instance = instance; } } libisrt-java-4.8.20100629/src/overview.html0000644000175000017500000000613311256153702020144 0ustar twernertwerner The basic runtime tools and interfaces for intarsys components.

Content

  1. Installation
  2. Overview
  3. License
  4. Service and support

Installation

To use this implementation, you have to include the jar files in the "lib" directory in your classpath.

Overview

This is the base for most of the intarsys Java software components.

License

This library is released under a BSD style license. The license is included with the sources and at numerous other places, for example here:
/*
 * Copyright (c) 2007, intarsys consulting GmbH
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * - Neither the name of intarsys 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.
 */
As far as we need 3rd party components, the respective licenses are included in the "3rd_party_licenses" directory.

Service & Support

More information about this component you will find at http://opensource.intarsys.de If you need further support, feel free to contact us. intarsys consulting GmbH
Bahnhofplatz 8
76137 Karlsruhe
Fon +49 721 38479-0
Fax +49 721 38479-60
info@intarsys.de
www.intarsys.de

For service and support contact

  1. EMail support: support@intarsys.de
libisrt-java-4.8.20100629/src/META-INF/0000755000175000017500000000000011412336332016541 5ustar twernertwernerlibisrt-java-4.8.20100629/src/META-INF/MANIFEST.MF0000644000175000017500000000004711255645430020203 0ustar twernertwernerManifest-Version: 1.0 Class-Path: libisrt-java-4.8.20100629/lib/0000755000175000017500000000000011412336332015360 5ustar twernertwernerlibisrt-java-4.8.20100629/javadoc/0000755000175000017500000000000011412336334016223 5ustar twernertwerner